Team Ai
Apppublic

manoj-codes/TextToSQLGenAI

sourceHugging Faceapache-2.0updated 1y agoView on Hugging Face
0likes
app.py58 linesDownload Raw Back to root
1from dotenv import load_dotenv
2load_dotenv()  # load all the environment variables
3
4import os
5import streamlit as st
6import sqlite3
7
8import google.generativeai as genai
9
10# configure genai api key
11genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
12
13# function to load Google Gemini model and provides queries as response
14def get_gemini_response(question,prompt):
15    model=genai.GenerativeModel("gemini-2.5-pro")
16    response=model.generate_content([prompt[0],question])
17    return response.text
18
19# function to retrive queries from database
20
21def read_sql_query(sql,db):
22    conn=sqlite3.connect(db)
23    cur=conn.cursor()
24    cur.execute(sql)
25    rows= cur.fetchall()
26    for row in rows:
27        print(row)
28    return rows
29
30# Define the prompt
31prompt=["""
32You are an expert in converting English questions to SQL query!
33        The SQL Database has the name STUDENT and has the columns - NAME, CLASS, SECTION
34        \n\nExample 1 - How many entries of records are present?,
35        The SQL command will be something like this SELECT COUNT(*) FROM STUDENT ;
36        \nExample 2 - Tell me all the students studing in Data Science CLASS?,
37        the SQL command will be like this SELECT * FROM STUDENT where CLASS='Data Science';
38        also the sql code should not have ''' in beginning or end and sql word in output  
39"""] 
40
41# streamlit app
42
43st.set_page_config(page_title="I can Retrieve any query")
44st.header("Gemini App To Retrieve Any SQL Data")
45
46question= st.text_input("Input :",key="input")
47
48submmit = st.button("Ask the question")
49
50# if submit is clicked
51if submmit:
52    response= get_gemini_response(question,prompt)
53    print(response)
54    response=read_sql_query(response,"student.db")
55    st.subheader('The response is')
56    for row in response:
57        print(row)
58        st.header(row)