Dannychemm commited on
Commit
bb7922d
·
verified ·
1 Parent(s): bae13dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -111
app.py CHANGED
@@ -1,111 +1,121 @@
1
- from dotenv import load_dotenv
2
- import streamlit as st
3
- import os
4
- import sqlite3
5
- import google.generativeai as genai
6
-
7
-
8
- load_dotenv()
9
- env_var = os.getenv('GOOGLE_API_KEY')
10
- if env_var is None:
11
- raise EnvironmentError("GOOGLE_API_KEY not found in environment variables.")
12
- genai.configure(api_key=env_var)
13
-
14
- def get_gemini_response(question, prompt):
15
- try:
16
- # Initialize the generative model
17
- model = genai.GenerativeModel("gemini-pro")
18
-
19
- # Generate content using the model
20
- response = model.generate_content(prompt + question)
21
-
22
- # Return the response text
23
- return response.text
24
-
25
- except genai.api_core.exceptions.GoogleAPICallError as e:
26
- print(f"A Google API call error occurred: {e}")
27
- return None
28
- except genai.api_core.exceptions.RetryError as e:
29
- print(f"A retry error occurred: {e}")
30
- return None
31
- except Exception as e:
32
- print(f"An unexpected error occurred: {e}")
33
- return None
34
-
35
- # Function to retrieve query from database
36
- def read_sql_query(sql, db):
37
- try:
38
- con = sqlite3.connect(db)
39
- cur = con.cursor()
40
- cur.execute(sql)
41
- rows = cur.fetchall()
42
- except sqlite3.Error as e:
43
- print(f"An error occurred: {e}")
44
- rows = []
45
- finally:
46
- if con:
47
- con.close()
48
- return rows
49
-
50
- prompt = """
51
- You are an expert in converting complex English questions to SQL queries!
52
- The SQL database has the name STUDENTS and has the following columns - NAME, CLASS, LEVEL, MARKS.
53
-
54
- For example,
55
-
56
- Example 1 - How many entries of records are present?
57
- The SQL command will be something like this: SELECT COUNT(*) FROM STUDENTS;
58
-
59
- Example 2 - List all student names.
60
- The SQL command will be something like this: SELECT NAME FROM STUDENTS;
61
-
62
- Example 3 - Find the number of students in each class.
63
- The SQL command will be something like this: SELECT CLASS, COUNT(*) FROM STUDENTS GROUP BY CLASS;
64
-
65
- Example 4 - Retrieve all information for students in level 'LEVEL 100'.
66
- The SQL command will be something like this: SELECT * FROM STUDENTS WHERE LEVEL = 'LEVEL 100';
67
-
68
- Example 5 - Get the names of students in class 'AI'.
69
- The SQL command will be something like this: SELECT NAME FROM STUDENTS WHERE CLASS = 'AI';
70
-
71
- Example 6 - Count the number of students in level 'LEVEL 300'.
72
- The SQL command will be something like this: SELECT COUNT(*) FROM STUDENTS WHERE LEVEL = 'LEVEL 300';
73
-
74
- Example 7 - Find the average marks of students in each class.
75
- The SQL command will be something like this: SELECT CLASS, AVG(MARKS) FROM STUDENTS GROUP BY CLASS;
76
-
77
- Example 8 - Retrieve the names and marks of students who have marks greater than 90.
78
- The SQL command will be something like this: SELECT NAME, MARKS FROM STUDENTS WHERE MARKS > 90;
79
-
80
- Example 9 - List the names of students in 'Data Science' class and 'Level 100'.
81
- The SQL command will be something like this: SELECT NAME FROM STUDENTS WHERE CLASS = 'Data Science' AND LEVEL = 'Level 100';
82
-
83
- Example 10 - Find the student with the highest marks.
84
- The SQL command will be something like this: SELECT NAME, MARKS FROM STUDENTS WHERE MARKS = (SELECT MAX(MARKS) FROM STUDENTS);
85
-
86
- also the sql code should not have ``` in beginning or end and sql word in output
87
- """
88
-
89
- st.set_page_config(page_title="I Can Retrieve Any SQL Query")
90
- st.header("Gemini App To Retrieve SQL Data")
91
-
92
- question = st.text_input("Input: ", key="input")
93
- submit = st.button("Ask the Question")
94
-
95
- # If submit is clicked
96
- if submit:
97
- response = get_gemini_response(question, prompt)
98
- if response:
99
- print(response)
100
- try:
101
- response = read_sql_query(response, "students.db")
102
- st.subheader("The Response is")
103
- for row in response:
104
- print(row)
105
- st.write(row)
106
- except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:
107
- st.error(f"A database error occurred: {e}")
108
- except Exception as e:
109
- st.error(f"An unexpected error occurred while executing the SQL query: {e}")
110
- else:
111
- st.error("Failed to generate a valid SQL query.")
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import streamlit as st
3
+ import os
4
+ import sqlite3
5
+ import google.generativeai as genai
6
+
7
+
8
+ load_dotenv()
9
+ env_var = os.getenv('GOOGLE_API_KEY')
10
+ if env_var is None:
11
+ raise EnvironmentError("GOOGLE_API_KEY not found in environment variables.")
12
+ genai.configure(api_key=env_var)
13
+
14
+ def get_gemini_response(question, prompt):
15
+ try:
16
+ # Initialize the generative model
17
+ model = genai.GenerativeModel("gemini-pro")
18
+
19
+ # Generate content using the model
20
+ response = model.generate_content(prompt + question)
21
+
22
+ # Return the response text
23
+ return response.text
24
+
25
+ except genai.api_core.exceptions.GoogleAPICallError as e:
26
+ print(f"A Google API call error occurred: {e}")
27
+ return None
28
+ except genai.api_core.exceptions.RetryError as e:
29
+ print(f"A retry error occurred: {e}")
30
+ return None
31
+ except Exception as e:
32
+ print(f"An unexpected error occurred: {e}")
33
+ return None
34
+
35
+ # Function to retrieve query from database
36
+ def read_sql_query(sql, db):
37
+ try:
38
+ con = sqlite3.connect(db)
39
+ cur = con.cursor()
40
+ cur.execute(sql)
41
+ rows = cur.fetchall()
42
+ except sqlite3.Error as e:
43
+ print(f"An error occurred: {e}")
44
+ rows = []
45
+ finally:
46
+ if con:
47
+ con.close()
48
+ return rows
49
+
50
+ prompt = """
51
+ You are an expert in converting complex English questions to SQL queries!
52
+ The SQL database has the name STUDENTS and has the following columns - NAME, CLASS, LEVEL, MARKS.
53
+
54
+ For example,
55
+
56
+ Example 1 - How many entries of records are present?
57
+ The SQL command will be something like this: SELECT COUNT(*) FROM STUDENTS;
58
+
59
+ Example 2 - List all student names.
60
+ The SQL command will be something like this: SELECT NAME FROM STUDENTS;
61
+
62
+ Example 3 - Find the number of students in each class.
63
+ The SQL command will be something like this: SELECT CLASS, COUNT(*) FROM STUDENTS GROUP BY CLASS;
64
+
65
+ Example 4 - Retrieve all information for students in level 'LEVEL 100'.
66
+ The SQL command will be something like this: SELECT * FROM STUDENTS WHERE LEVEL = 'LEVEL 100';
67
+
68
+ Example 5 - Get the names of students in class 'AI'.
69
+ The SQL command will be something like this: SELECT NAME FROM STUDENTS WHERE CLASS = 'AI';
70
+
71
+ Example 6 - Count the number of students in level 'LEVEL 300'.
72
+ The SQL command will be something like this: SELECT COUNT(*) FROM STUDENTS WHERE LEVEL = 'LEVEL 300';
73
+
74
+ Example 7 - Find the average marks of students in each class.
75
+ The SQL command will be something like this: SELECT CLASS, AVG(MARKS) FROM STUDENTS GROUP BY CLASS;
76
+
77
+ Example 8 - Retrieve the names and marks of students who have marks greater than 90.
78
+ The SQL command will be something like this: SELECT NAME, MARKS FROM STUDENTS WHERE MARKS > 90;
79
+
80
+ Example 9 - List the names of students in 'Data Science' class and 'Level 100'.
81
+ The SQL command will be something like this: SELECT NAME FROM STUDENTS WHERE CLASS = 'Data Science' AND LEVEL = 'Level 100';
82
+
83
+ Example 10 - Find the student with the highest marks.
84
+ The SQL command will be something like this: SELECT NAME, MARKS FROM STUDENTS WHERE MARKS = (SELECT MAX(MARKS) FROM STUDENTS);
85
+
86
+ also the sql code should not have ``` in beginning or end and sql word in output
87
+ """
88
+
89
+ st.set_page_config(page_title="I Can Retrieve Any SQL Query")
90
+ st.header("Gemini App To Retrieve SQL Data")
91
+
92
+ st.set_page_config(page_title="I Can Retrieve Any SQL Query")
93
+ st.header("Gemini App To Retrieve SQL Data")
94
+
95
+ # App description
96
+ st.write("""
97
+ Welcome to the Gemini SQL Query Generator! This app leverages the power of Google's Generative AI to convert your natural language questions into SQL queries.
98
+ Simply input your question in plain English, and our AI model will generate the corresponding SQL query, execute it on the student database, and return the results.
99
+ This tool is perfect for those who want to interact with databases without needing to write SQL queries manually.
100
+ """)
101
+
102
+ question = st.text_input("Input your question related to the student database:", key="input")
103
+ submit = st.button("Ask the Question")
104
+
105
+ # If submit is clicked
106
+ if submit:
107
+ response = get_gemini_response(question, prompt)
108
+ if response:
109
+ print(response)
110
+ try:
111
+ response = read_sql_query(response, "students.db")
112
+ st.subheader("The Response is:")
113
+ for row in response:
114
+ print(row)
115
+ st.write(row)
116
+ except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:
117
+ st.error(f"A database error occurred: {e}")
118
+ except Exception as e:
119
+ st.error(f"An unexpected error occurred while executing the SQL query: {e}")
120
+ else:
121
+ st.error("Failed to generate a valid SQL query.")