azaan34 commited on
Commit
d3d58a3
·
verified ·
1 Parent(s): 5352177

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sqlite3
3
+ import google.generativeai as genai
4
+ import gradio as gr
5
+ from dotenv import load_dotenv
6
+ load_dotenv()
7
+
8
+ # Configure the API Key
9
+ genai.configure(api_key = "AIzaSyChjOLER-nWxh6tcB7vG3hW43o21VPGuu0")
10
+
11
+ # Load Google Gemini model and retireve the sql query as response
12
+ def get_gemini_response(question, prompt):
13
+ model = genai.GenerativeModel('gemini-2.5-flash-preview-04-17')
14
+ response = model.generate_content([prompt, question])
15
+ return response.text
16
+
17
+ # Retrieve query from SQL database
18
+ def read_sql_query(sql, db):
19
+ connection = sqlite3.connect(db) # Connect to the SQLite database
20
+ cursor = connection.cursor() # Create a cursor object to execute SQL commands like SELECT, INSERT, UPDATE, DELETE
21
+ cursor.execute(sql) # Execute the SQL command to create the table
22
+ rows = cursor.fetchall() # Fetch all rows from the executed query
23
+ connection.close() # Close the connection to the database
24
+ for row in rows:
25
+ print(row) # Print each row
26
+ return rows
27
+
28
+ # Prompt for the Gemini model
29
+ prompt = """
30
+ You are an expert in converting English questions to SQL query!
31
+ The SQL database has the name STUDENT and has the following columns - NAME, CLASS,
32
+ SECTION
33
+
34
+ For example,
35
+ Example 1 - How many entries of records are present?,
36
+ the SQL command will be something like this SELECT COUNT(*) FROM STUDENT ;
37
+
38
+ Example 2 - Tell me all the students studying in Data Science class?,
39
+ the SQL command will be something like this SELECT * FROM STUDENT
40
+ where CLASS="Data Science";
41
+ also the sql code should not have ``` in beginning or end and sql word in output
42
+ """
43
+
44
+ def process_question(question):
45
+ response = get_gemini_response(question, prompt)
46
+ data = read_sql_query(response, "student.db")
47
+ result = f"Generated SQL Query:\n{response}\n\nQuery Result:\n"
48
+ for row in data:
49
+ result += f"{str(row)}\n"
50
+ return result
51
+
52
+ # Create Gradio interface
53
+ demo = gr.Interface(
54
+ fn=process_question,
55
+ inputs=gr.Textbox(label="Enter your question"),
56
+ outputs=gr.Textbox(label="Result"),
57
+ title="Azaan's SQL Query Generator",
58
+ description="This app generates SQL queries based on user input questions."
59
+ )
60
+
61
+ if __name__ == "__main__":
62
+ demo.launch()