AliInamdar commited on
Commit
64b7268
Β·
verified Β·
1 Parent(s): ab9e610

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -52
app.py CHANGED
@@ -5,79 +5,75 @@ import requests
5
  import re
6
  import os
7
 
8
- # βœ… Securely load Together API Key
9
- def get_together_api_key():
10
- key = os.environ.get("TOGETHER_API_KEY")
11
- if key:
12
- print("βœ… TOGETHER_API_KEY loaded successfully.")
13
- return key
14
- raise RuntimeError("❌ TOGETHER_API_KEY not found. Set it in Hugging Face > Settings > Secrets.")
15
 
16
- TOGETHER_API_KEY = get_together_api_key()
17
 
18
- # 🧠 Generate SQL from prompt using Together's /inference endpoint
19
- def generate_sql_from_prompt(prompt, df):
20
- schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
21
- full_prompt = f"""
22
- You are a SQL expert. Here is a table called 'df' with the following schema:
23
- {schema}
24
 
25
  User question: "{prompt}"
26
-
27
- Write a valid SQL query using the 'df' table. Return only the SQL code.
28
- """
29
 
30
  url = "https://api.together.xyz/v1/completions"
31
  headers = {
32
- "Authorization": f"Bearer {TOGETHER_API_KEY}",
33
  "Content-Type": "application/json"
34
  }
35
  payload = {
36
- "model": "mistralai/Mixtral-8x7B-Instruct-v0.1", # You can use "meta-llama/Llama-3-8B-Instruct" too
37
  "prompt": full_prompt,
38
- "max_tokens": 300,
39
- "temperature": 0.7,
40
  }
 
 
 
 
 
 
 
 
 
41
 
42
- response = requests.post(url, headers=headers, json=payload)
43
- response.raise_for_status()
44
- result = response.json()
45
- return result['choices'][0]['text'].strip("```sql").strip("```").strip()
46
-
47
- # 🧽 Clean SQL for DuckDB compatibility
48
- def clean_sql_for_duckdb(sql, df_columns):
49
  sql = sql.replace("`", '"')
50
- for col in df_columns:
51
- if " " in col and f'"{col}"' not in sql:
52
- pattern = r'\b' + re.escape(col) + r'\b'
53
- sql = re.sub(pattern, f'"{col}"', sql)
54
  return sql
55
 
56
- # πŸ’¬ Main chatbot function
57
- def chatbot_interface(file, question):
58
  try:
59
  df = pd.read_excel(file)
60
- sql = generate_sql_from_prompt(question, df)
61
- cleaned_sql = clean_sql_for_duckdb(sql, df.columns)
62
- result = duckdb.query(cleaned_sql).to_df()
63
- return f"πŸ“œ SQL Query:\n```sql\n{sql}\n```", result
 
64
  except Exception as e:
65
- return f"❌ Error: {str(e)}", pd.DataFrame()
66
-
67
 
68
-
69
- # πŸŽ›οΈ Gradio UI
70
  with gr.Blocks() as demo:
71
- gr.Markdown("## πŸ“Š Excel SQL Chatbot with Together API")
72
- with gr.Row():
73
- file_input = gr.File(label="πŸ“‚ Upload Excel File (.xlsx)")
74
- question = gr.Textbox(label="🧠 Ask a question", placeholder="e.g., Show average salary by department")
75
- submit = gr.Button("πŸš€ Generate & Query")
76
- sql_output = gr.Markdown()
77
- result_table = gr.Dataframe()
78
-
79
- submit.click(fn=chatbot_interface, inputs=[file_input, question], outputs=[sql_output, result_table])
80
 
81
- # πŸš€ Launch the app
82
  if __name__ == "__main__":
83
  demo.launch()
 
5
  import re
6
  import os
7
 
8
+ # Load API Key
9
+ def get_api_key():
10
+ key = os.getenv("TOGETHER_API_KEY")
11
+ print("πŸ” API KEY:", "FOUND" if key else "NOT FOUND")
12
+ if not key:
13
+ raise RuntimeError("πŸ”΄ MISSING TOGETHER_API_KEY!")
14
+ return key
15
 
16
+ API_KEY = get_api_key()
17
 
18
+ # Generate SQL with detailed logging
19
+ def generate_sql(prompt, df):
20
+ schema = ", ".join([f"{col} ({dtype})" for col, dtype in df.dtypes.items()])
21
+ full_prompt = f"""You are a SQL expert. Table 'df' schema: {schema}
 
 
22
 
23
  User question: "{prompt}"
24
+ Return only valid SQL."""
25
+ print("πŸ“’ FULL PROMPT:\n", full_prompt)
 
26
 
27
  url = "https://api.together.xyz/v1/completions"
28
  headers = {
29
+ "Authorization": f"Bearer {API_KEY}",
30
  "Content-Type": "application/json"
31
  }
32
  payload = {
33
+ "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
34
  "prompt": full_prompt,
35
+ "max_tokens": 200,
36
+ "temperature": 0.2
37
  }
38
+ print("πŸ“‘ Calling Together API:", url, payload)
39
+ resp = requests.post(url, headers=headers, json=payload)
40
+ print("🟒 HTTP Status:", resp.status_code)
41
+ print("🧾 Response Body:", resp.text)
42
+ resp.raise_for_status()
43
+ j = resp.json()
44
+ if "choices" in j:
45
+ return j["choices"][0]["text"].strip()
46
+ return j.get("output", "")
47
 
48
+ # Clean SQL
49
+ def clean_sql(sql, cols):
 
 
 
 
 
50
  sql = sql.replace("`", '"')
51
+ for c in cols:
52
+ if " " in c and f'"{c}"' not in sql:
53
+ sql = re.sub(rf'\b{re.escape(c)}\b', f'"{c}"', sql)
 
54
  return sql
55
 
56
+ # Main function
57
+ def chat_interface(file, q):
58
  try:
59
  df = pd.read_excel(file)
60
+ sql = generate_sql(q, df)
61
+ sql = clean_sql(sql, df.columns)
62
+ print("βœ… Final SQL:", sql)
63
+ df_res = duckdb.query(sql).to_df()
64
+ return f"πŸ“œ SQL:\n```sql\n{sql}\n```", df_res
65
  except Exception as e:
66
+ print("πŸ”₯ EXCEPTION:", repr(e))
67
+ return f"❌ Error: {e}", pd.DataFrame()
68
 
 
 
69
  with gr.Blocks() as demo:
70
+ gr.Markdown("## SQL Chatbot – Debug Mode")
71
+ file_in = gr.File(label="Upload Excel")
72
+ q_in = gr.Textbox(label="Question")
73
+ bt = gr.Button("Run")
74
+ md = gr.Markdown()
75
+ tbl = gr.Dataframe()
76
+ bt.click(chat_interface, [file_in, q_in], [md, tbl])
 
 
77
 
 
78
  if __name__ == "__main__":
79
  demo.launch()