Curranj commited on
Commit
edbd074
·
1 Parent(s): 423041c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -0
app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import gradio as gr
3
+ import pandas as pd
4
+ import sqlite3
5
+ import os
6
+ openai.api_key = os.environ["Secret"]
7
+
8
+ #OpenAi call
9
+ def gpt3(texts):
10
+ response = openai.Completion.create(
11
+ engine="code-davinci-002",
12
+ prompt= texts,
13
+ temperature=0,
14
+ max_tokens=750,
15
+ top_p=1,
16
+ frequency_penalty=0.0,
17
+ presence_penalty=0.0,
18
+ stop = (";", "/*", "</code>")
19
+ )
20
+ x = response.choices[0].text
21
+
22
+ return x
23
+
24
+ # Function to elicit sql response from model
25
+
26
+
27
+
28
+ # Function to elicit sql response from model
29
+
30
+
31
+ def greet(prompt, file = None):
32
+
33
+ #get the file path from the file object
34
+ file_path = file.name
35
+
36
+ # read the file and get the column names
37
+ if file_path:
38
+ if file_path.endswith(".csv"):
39
+ df = pd.read_csv(file_path)
40
+ columns = " ".join(df.columns)
41
+
42
+
43
+
44
+
45
+ elif file_path.endswith((".xls", ".xlsx")):
46
+ df = pd.read_excel(file_path)
47
+ columns = " ".join(df.columns)
48
+ else:
49
+ return "Invalid file type. Please provide a CSV or Excel file."
50
+
51
+ # create a SQLite database in memory
52
+ con = sqlite3.connect(":memory:")
53
+ # extract the table name so it can be used in the SQL query
54
+ # in order to get the table name, we need to remove the file extension
55
+
56
+ table_name =
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+ # write the DataFrame to a SQL table
65
+
66
+
67
+
68
+ df.to_sql(table_name, con)
69
+ else:
70
+ return "Please upload a file."
71
+ txt= (f'''/*Prompt: {prompt}\nColumns: {columns}\nTable: {table_name}*/ \n —-SQL Code:\n''')
72
+ sql = gpt3(txt)
73
+
74
+
75
+ # execute the SQL query
76
+ if con:
77
+ df = pd.read_sql_query(sql, con)
78
+ return sql, df
79
+ else:
80
+ return sql, None
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+ #Code to set up Gradio UI
89
+ iface = gr.Interface(greet,
90
+ inputs = ["text", ("file")],
91
+ outputs = ["text",gr.Dataframe(type="pandas")],
92
+ title="Natural Language to SQL",
93
+ description="Enter any prompt and get a SQL statement back! For better results, give it more context")
94
+ iface.launch()