Curranj/GPT-SQL
3
1import openai2import gradio as gr3import pandas as pd4import sqlite35import os6openai.api_key = os.environ["Secret"]7 8#OpenAi call9def 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 x23 24# Function to elicit sql response from model25 26 27 28# Function to elicit sql response from model29 30 31def greet(prompt, file = None):32 33 #get the file path from the file object34 file_path = file.name35 36 # read the file and get the column names37 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 memory52 con = sqlite3.connect(":memory:")53 # extract the table name so it can be used in the SQL query54 # in order to get the table name, we need to remove the file extension55 56 table_name = os.path.splitext(os.path.basename(file_path.name))[0]57 58 59 60 61 62 63 64 65 # write the DataFrame to a SQL table66 67 68 69 df.to_sql(table_name, con)70 else:71 return "Please upload a file."72 txt= (f'''/*Prompt: {prompt}\nColumns: {columns}\nTable: {table_name}*/ \n —-SQL Code:\n''')73 sql = gpt3(txt)74 75 76 # execute the SQL query77 if con:78 df = pd.read_sql_query(sql, con)79 return sql, df80 else:81 return sql, None82 83 84 85 86 87 88 89#Code to set up Gradio UI90iface = gr.Interface(greet, 91 inputs = ["text", ("file")], 92 outputs = ["text",gr.Dataframe(type="pandas")],93 title="Natural Language to SQL", 94 description="Enter any prompt and get a SQL statement back! For better results, give it more context")95iface.launch()96 