|
import openai |
|
import gradio as gr |
|
import pandas as pd |
|
import sqlite3 |
|
import os |
|
openai.api_key = os.environ["Secret"] |
|
|
|
|
|
def gpt3(texts): |
|
response = openai.Completion.create( |
|
engine="code-davinci-002", |
|
prompt= texts, |
|
temperature=0, |
|
max_tokens=750, |
|
top_p=1, |
|
frequency_penalty=0.0, |
|
presence_penalty=0.0, |
|
stop = (";", "/*", "</code>") |
|
) |
|
x = response.choices[0].text |
|
|
|
return x |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def greet(prompt, file = None): |
|
|
|
|
|
file_path = file.name |
|
|
|
|
|
if file_path: |
|
if file_path.endswith(".csv"): |
|
df = pd.read_csv(file_path) |
|
columns = " ".join(df.columns) |
|
|
|
|
|
|
|
|
|
elif file_path.endswith((".xls", ".xlsx")): |
|
df = pd.read_excel(file_path) |
|
columns = " ".join(df.columns) |
|
else: |
|
return "Invalid file type. Please provide a CSV or Excel file." |
|
|
|
|
|
con = sqlite3.connect(":memory:") |
|
|
|
|
|
|
|
table_name = os.path.splitext(os.path.basename(file_path.name))[0] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
df.to_sql(table_name, con) |
|
else: |
|
return "Please upload a file." |
|
txt= (f'''/*Prompt: {prompt}\nColumns: {columns}\nTable: {table_name}*/ \n —-SQL Code:\n''') |
|
sql = gpt3(txt) |
|
|
|
|
|
|
|
if con: |
|
df = pd.read_sql_query(sql, con) |
|
return sql, df |
|
else: |
|
return sql, None |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
iface = gr.Interface(greet, |
|
inputs = ["text", ("file")], |
|
outputs = ["text",gr.Dataframe(type="pandas")], |
|
title="Natural Language to SQL", |
|
description="Enter any prompt and get a SQL statement back! For better results, give it more context") |
|
iface.launch() |
|
|