rakeshkumar1812 commited on
Commit
9913d56
·
verified ·
1 Parent(s): 5b54d0b

Upload 5 files

Browse files
Files changed (6) hide show
  1. .gitattributes +1 -0
  2. app.py +102 -0
  3. database.py +41 -0
  4. requirements.txt +4 -0
  5. table_data.xlsx +3 -0
  6. utils.py +24 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ table_data.xlsx filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+
3
+ load_dotenv() # Load All the environment variables
4
+ import streamlit as st
5
+ import os
6
+ import sqlite3
7
+ import google.generativeai as genai
8
+ import pandas as pd
9
+ from database import df
10
+ from utils import remove_triple_quotes
11
+
12
+ # configure genai key
13
+
14
+ genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))
15
+
16
+ # Function to load Google Gemini Model and provide query as response
17
+
18
+ def get_gemini_response(question, prompt):
19
+ model=genai.GenerativeModel('gemini-pro')
20
+ response=model.generate_content([prompt[0], question])
21
+ return response.text
22
+
23
+ # function to retrieve query from the database
24
+
25
+ def read_sql_query(sql, db):
26
+ conn = sqlite3.connect(db)
27
+ cur = conn.cursor()
28
+ cur.execute(sql)
29
+ rows = cur.fetchall()
30
+ # Convert results to pandas DataFrame
31
+ sql_output_df = pd.DataFrame(rows, columns=[description[0] for description in cur.description])
32
+ conn.commit()
33
+ conn.close()
34
+ for row in rows:
35
+ print(row)
36
+ return rows, sql_output_df
37
+
38
+
39
+ ## Define your prompt
40
+ prompt = [
41
+ """ You are an expert in converting English questions to SQL query!
42
+ The SQL database has the name test_db and the SQL table name is tbl_customer
43
+ and has the following columns -
44
+ CustomerKey,GeographyKey,CustomerAlternateKey,Title,FirstName,MiddleName,
45
+ LastName,NameStyle,BirthDate,MaritalStatus,Suffix,Gender,EmailAddress,
46
+ YearlyIncome,TotalChildren,NumberChildrenAtHome,EnglishEducation,
47
+ SpanishEducation,FrenchEducation,EnglishOccupation,SpanishOccupation,
48
+ FrenchOccupation,HouseOwnerFlag,NumberCarsOwned,AddressLine1,AddressLine2,
49
+ Phone,DateFirstPurchase,CommuteDistance.
50
+
51
+ \n\nFor example, \nExample 1 - How many entries of records are present?,
52
+ the SQL command will be something like this SELECT COUNT(*) FROM tbl_customer ;
53
+
54
+ \nExample 2 - Tell me all the customers who has CustomerKey greater than 11000?,
55
+ the SQL command will be something like this SELECT * FROM tbl_customer where CustomerKey > 11000";
56
+ also the sql code should NOT have ``` in beginning or end and sql word in output
57
+ also there should NOT be sql keyword at the beginning of the output """
58
+ ]
59
+
60
+ st.set_page_config(page_title="I can retrieve any SQL query")
61
+ st.header("Gemini App to Retrieve SQL data")
62
+
63
+ question = st.text_input("Input: ", key=input)
64
+ submit=st.button("Ask the Question :")
65
+
66
+ # # If Submit is clicked...
67
+ # if submit:
68
+ # generated_sql_query = get_gemini_response(question, prompt)
69
+ # print(generated_sql_query)
70
+ # response = read_sql_query(generated_sql_query, "student.db")
71
+ # st.subheader("The Response is :")
72
+ # for row in response:
73
+ # print(row)
74
+ # st.header(row)
75
+
76
+
77
+ # Display DataFrame in Streamlit
78
+ st.write('##### This is the sample table...')
79
+ st.write(df.head(5))
80
+
81
+
82
+ # If Submit is clicked...
83
+ if submit:
84
+ generated_sql_query = get_gemini_response(question, prompt)
85
+ generated_sql_query = remove_triple_quotes(generated_sql_query)
86
+ print("The generated sql_quey is :")
87
+ print(generated_sql_query)
88
+ response, sql_output_df = read_sql_query(generated_sql_query, "test_db.db")
89
+ st.write('##### used SQL query is:')
90
+ st.write(generated_sql_query)
91
+ st.write("#### The Response is :")
92
+ # Display the DataFrame in Streamlit
93
+ st.write(sql_output_df)
94
+
95
+ # for row in response:
96
+ # print(row)
97
+
98
+ # st.write(row)
99
+
100
+
101
+
102
+
database.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import sqlite3
3
+
4
+ # Specify the path to your Excel file
5
+ excel_file_path = 'C:\\Users\\rakes\\sql\\table_data.xlsx'
6
+
7
+ # Read the Excel file into a pandas DataFrame
8
+ df = pd.read_excel(excel_file_path, sheet_name='Customer_Data')
9
+
10
+ # Display the DataFrame
11
+ # print(df.shape)
12
+ # print(df.head())
13
+
14
+
15
+ # connect to SQLite3
16
+ connection = sqlite3.connect("test_db.db")
17
+
18
+ # Create a Cursor object to insert Record, Create Table
19
+ cursor = connection.cursor()
20
+
21
+ # Delete the table if already exists the table.
22
+ cursor.execute("DROP TABLE IF EXISTS tbl_customer");
23
+
24
+ # Convert DataFrame to SQL table and insert data
25
+ df.to_sql('tbl_customer', connection, if_exists='replace', index=False)
26
+
27
+
28
+ ## Display All the records
29
+ print('the inserted records are ....')
30
+ data = cursor.execute('''
31
+ Select CustomerKey,GeographyKey,CustomerAlternateKey,Title,FirstName,
32
+ MiddleName,LastName from tbl_customer LIMIT 1''')
33
+
34
+ for row in data:
35
+ print(row)
36
+
37
+ # Commit changes
38
+ connection.commit()
39
+
40
+ # Close the connection
41
+ connection.close()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ python-dotenv
2
+ streamlit
3
+ google-generativeai
4
+ openpyxl
table_data.xlsx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1a25cbdc998486b1112b3722632bc0a1f34fca37fe8e3c60a9e1e7e113187ef
3
+ size 3170199
utils.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ def remove_triple_quotes(sql_query):
3
+ print('the incoming sql_query is :\n', sql_query)
4
+
5
+ if sql_query.startswith('"""') and sql_query.endswith('"""'):
6
+ sql_query = sql_query[3:-3].strip()
7
+ print('the outgoing sql_query is :\n', sql_query)
8
+ return sql_query
9
+
10
+ elif sql_query.startswith("'''") and sql_query.endswith("'''"):
11
+ sql_query = sql_query[3:-3].strip()
12
+ print('the outgoing sql_query is :\n', sql_query)
13
+ return sql_query
14
+
15
+ elif sql_query.startswith("```") and sql_query.endswith("```"):
16
+ sql_query = sql_query[3:-3].strip()
17
+ print('the outgoing sql_query is :\n', sql_query)
18
+ return sql_query
19
+
20
+ else:
21
+ print('the outgoing sql_query is :\n', sql_query)
22
+ return sql_query
23
+
24
+