AliInamdar commited on
Commit
04cb4b7
Β·
verified Β·
1 Parent(s): de1c670

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -27
app.py CHANGED
@@ -6,13 +6,10 @@ import re
6
  import os
7
  from io import BytesIO
8
 
9
- # πŸ” Together API Key (set this securely in Hugging Face Spaces)
10
- TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY") # Must be set in the environment variables
11
 
12
- # πŸ”§ Global DataFrame holder
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
- response = requests.post(url, headers=headers, json=payload)
40
- response.raise_for_status()
41
- result = response.json()
42
- return result['choices'][0]['message']['content'].strip("```sql").strip("```").strip()
 
 
 
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
- # πŸ“¦ Handle Excel upload
 
 
 
54
  def upload_excel(file):
55
- global df
56
- df = pd.read_excel(BytesIO(file.read()))
57
- return f"βœ… Loaded file with shape {df.shape}"
 
 
 
 
 
58
 
59
- # πŸ’¬ Handle chat prompt
60
- def handle_chat(prompt):
61
- global df
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
- # 🎨 Gradio UI
74
  with gr.Blocks() as demo:
75
  gr.Markdown("# πŸ€– SQL Chatbot with Together API + DuckDB")
76
- file_uploader = gr.File(label="πŸ“‚ Upload Excel File", file_types=[".xlsx"])
77
- upload_status = gr.Textbox(label="πŸ“„ File Status", interactive=False)
78
 
79
  with gr.Row():
80
- prompt_box = gr.Textbox(label="πŸ’¬ Ask your Question", placeholder="e.g., What is the total revenue?")
81
- generate_btn = gr.Button("πŸš€ Generate SQL")
82
 
83
  sql_output = gr.Textbox(label="πŸ“œ SQL Query")
84
- result_table = gr.Dataframe(label="πŸ“Š Query Result")
85
 
86
- file_uploader.change(upload_excel, inputs=file_uploader, outputs=upload_status)
87
- generate_btn.click(fn=handle_chat, inputs=prompt_box, outputs=[sql_output, result_table])
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()