Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,13 +6,10 @@ import re
|
|
| 6 |
import os
|
| 7 |
from io import BytesIO
|
| 8 |
|
| 9 |
-
# π Together API
|
| 10 |
-
TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
df = None
|
| 14 |
-
|
| 15 |
-
# π§ Generate SQL using Together API
|
| 16 |
def generate_sql_from_prompt(prompt, df):
|
| 17 |
schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
|
| 18 |
full_prompt = f"""
|
|
@@ -36,10 +33,13 @@ Write a valid SQL query using the 'df' table. Return only the SQL code.
|
|
| 36 |
"max_tokens": 200
|
| 37 |
}
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
# π§½ Clean SQL for DuckDB
|
| 45 |
def clean_sql_for_duckdb(sql, df_columns):
|
|
@@ -50,42 +50,52 @@ def clean_sql_for_duckdb(sql, df_columns):
|
|
| 50 |
sql = re.sub(pattern, f'"{col}"', sql)
|
| 51 |
return sql
|
| 52 |
|
| 53 |
-
#
|
|
|
|
|
|
|
|
|
|
| 54 |
def upload_excel(file):
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
# π¬ Handle
|
| 60 |
-
def
|
| 61 |
-
|
| 62 |
if df is None:
|
| 63 |
return "β Please upload an Excel file first.", pd.DataFrame()
|
| 64 |
|
| 65 |
try:
|
| 66 |
sql = generate_sql_from_prompt(prompt, df)
|
|
|
|
|
|
|
|
|
|
| 67 |
cleaned_sql = clean_sql_for_duckdb(sql, df.columns)
|
| 68 |
result_df = duckdb.query(cleaned_sql).to_df()
|
| 69 |
return f"π Generated SQL:\n{sql}", result_df
|
| 70 |
except Exception as e:
|
| 71 |
return f"β Error: {e}", pd.DataFrame()
|
| 72 |
|
| 73 |
-
# π¨
|
| 74 |
with gr.Blocks() as demo:
|
| 75 |
gr.Markdown("# π€ SQL Chatbot with Together API + DuckDB")
|
| 76 |
-
|
| 77 |
-
upload_status = gr.Textbox(label="
|
| 78 |
|
| 79 |
with gr.Row():
|
| 80 |
-
prompt_box = gr.Textbox(label="π¬
|
| 81 |
-
|
| 82 |
|
| 83 |
sql_output = gr.Textbox(label="π SQL Query")
|
| 84 |
-
result_table = gr.Dataframe(label="π Query
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
|
| 89 |
-
# π Launch app
|
| 90 |
if __name__ == "__main__":
|
| 91 |
-
demo.launch()
|
|
|
|
| 6 |
import os
|
| 7 |
from io import BytesIO
|
| 8 |
|
| 9 |
+
# π Read Together API key from Hugging Face Secrets
|
| 10 |
+
TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
|
| 11 |
|
| 12 |
+
# π§ Generate SQL from Prompt
|
|
|
|
|
|
|
|
|
|
| 13 |
def generate_sql_from_prompt(prompt, df):
|
| 14 |
schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
|
| 15 |
full_prompt = f"""
|
|
|
|
| 33 |
"max_tokens": 200
|
| 34 |
}
|
| 35 |
|
| 36 |
+
try:
|
| 37 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 38 |
+
response.raise_for_status()
|
| 39 |
+
result = response.json()
|
| 40 |
+
return result['choices'][0]['message']['content'].strip("```sql").strip("```").strip()
|
| 41 |
+
except Exception as e:
|
| 42 |
+
return f"Error in API call: {str(e)}"
|
| 43 |
|
| 44 |
# π§½ Clean SQL for DuckDB
|
| 45 |
def clean_sql_for_duckdb(sql, df_columns):
|
|
|
|
| 50 |
sql = re.sub(pattern, f'"{col}"', sql)
|
| 51 |
return sql
|
| 52 |
|
| 53 |
+
# π Global dataframe holder
|
| 54 |
+
df_global = {"df": None}
|
| 55 |
+
|
| 56 |
+
# π Upload handler
|
| 57 |
def upload_excel(file):
|
| 58 |
+
if file is None:
|
| 59 |
+
return "β No file uploaded."
|
| 60 |
+
try:
|
| 61 |
+
df = pd.read_excel(BytesIO(file.read()))
|
| 62 |
+
df_global["df"] = df
|
| 63 |
+
return f"β
Uploaded file with shape: {df.shape}"
|
| 64 |
+
except Exception as e:
|
| 65 |
+
return f"β Failed to load file: {e}"
|
| 66 |
|
| 67 |
+
# π¬ Handle prompt
|
| 68 |
+
def handle_query(prompt):
|
| 69 |
+
df = df_global.get("df")
|
| 70 |
if df is None:
|
| 71 |
return "β Please upload an Excel file first.", pd.DataFrame()
|
| 72 |
|
| 73 |
try:
|
| 74 |
sql = generate_sql_from_prompt(prompt, df)
|
| 75 |
+
if sql.startswith("Error"):
|
| 76 |
+
return sql, pd.DataFrame()
|
| 77 |
+
|
| 78 |
cleaned_sql = clean_sql_for_duckdb(sql, df.columns)
|
| 79 |
result_df = duckdb.query(cleaned_sql).to_df()
|
| 80 |
return f"π Generated SQL:\n{sql}", result_df
|
| 81 |
except Exception as e:
|
| 82 |
return f"β Error: {e}", pd.DataFrame()
|
| 83 |
|
| 84 |
+
# π¨ UI
|
| 85 |
with gr.Blocks() as demo:
|
| 86 |
gr.Markdown("# π€ SQL Chatbot with Together API + DuckDB")
|
| 87 |
+
file_input = gr.File(label="π Upload Excel File (.xlsx only)", file_types=[".xlsx"])
|
| 88 |
+
upload_status = gr.Textbox(label="Status", interactive=False)
|
| 89 |
|
| 90 |
with gr.Row():
|
| 91 |
+
prompt_box = gr.Textbox(label="π¬ Your Question", placeholder="e.g., Show me total sales by region")
|
| 92 |
+
run_button = gr.Button("π Generate SQL + Run")
|
| 93 |
|
| 94 |
sql_output = gr.Textbox(label="π SQL Query")
|
| 95 |
+
result_table = gr.Dataframe(label="π Query Results")
|
| 96 |
|
| 97 |
+
file_input.change(upload_excel, inputs=file_input, outputs=upload_status)
|
| 98 |
+
run_button.click(handle_query, inputs=prompt_box, outputs=[sql_output, result_table])
|
| 99 |
|
|
|
|
| 100 |
if __name__ == "__main__":
|
| 101 |
+
demo.launch()
|