AliInamdar commited on
Commit
0cd2878
Β·
verified Β·
1 Parent(s): 454008d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -38
app.py CHANGED
@@ -5,67 +5,76 @@ import requests
5
  import re
6
  import os
7
 
8
- # Securely load Together API Key
9
- def get_api_key():
10
- key = os.getenv("TOGETHER_API_KEY")
11
  if not key:
12
- raise RuntimeError("πŸ”΄ TOGETHER_API_KEY not found!")
13
  return key
14
 
15
- API_KEY = get_api_key()
 
 
 
 
 
 
 
16
 
17
- # Generate SQL from prompt
18
- def generate_sql(prompt, df):
19
- schema = ", ".join([f"{col} ({dtype})" for col, dtype in df.dtypes.items()])
20
- full_prompt = f"""You are a SQL expert. Table 'df' schema: {schema}
21
  User question: "{prompt}"
22
- Return only valid SQL."""
23
-
24
- url = "https://api.together.xyz/v1/completions"
 
 
25
  headers = {
26
- "Authorization": f"Bearer {API_KEY}",
27
  "Content-Type": "application/json"
28
  }
29
  payload = {
30
- "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
31
- "prompt": full_prompt,
32
- "max_tokens": 300,
33
- "temperature": 0.3
34
  }
35
 
36
- resp = requests.post(url, headers=headers, json=payload)
37
- resp.raise_for_status()
38
- return resp.json()["choices"][0]["text"].strip()
 
39
 
40
- # Clean SQL for DuckDB
41
- def clean_sql(sql, cols):
42
  sql = sql.replace("`", '"')
43
- for c in cols:
44
- if " " in c and f'"{c}"' not in sql:
45
- sql = re.sub(rf'\b{re.escape(c)}\b', f'"{c}"', sql)
 
46
  return sql
47
 
48
- # Main interface logic
49
- def chat_interface(file, question):
50
  try:
51
  df = pd.read_excel(file)
52
- sql = generate_sql(question, df)
53
- sql = clean_sql(sql, df.columns)
54
- result_df = duckdb.query(sql).to_df()
55
- return f"πŸ“œ SQL:\n```sql\n{sql}\n```", result_df
56
  except Exception as e:
57
- return f"❌ Error: {e}", pd.DataFrame()
58
 
59
- # Gradio UI
60
  with gr.Blocks() as demo:
61
- gr.Markdown("## πŸ“Š Excel SQL Chatbot using Together API")
62
- file_input = gr.File(label="πŸ“‚ Upload Excel File (.xlsx)")
63
- question = gr.Textbox(label="🧠 Ask your SQL question")
 
64
  submit = gr.Button("πŸš€ Generate & Run")
65
  sql_output = gr.Markdown()
66
  result_table = gr.Dataframe()
67
 
68
- submit.click(fn=chat_interface, inputs=[file_input, question], outputs=[sql_output, result_table])
69
 
 
70
  if __name__ == "__main__":
71
- demo.launch()
 
5
  import re
6
  import os
7
 
8
+ # πŸ” Load Groq API Key securely
9
+ def get_groq_api_key():
10
+ key = os.environ.get("GROQ_API_KEY")
11
  if not key:
12
+ raise RuntimeError("❌ GROQ_API_KEY not found in environment. Add it in Hugging Face Secrets.")
13
  return key
14
 
15
+ GROQ_API_KEY = get_groq_api_key()
16
+
17
+ # 🧠 Generate SQL using Groq LLaMA3 model
18
+ def generate_sql_from_prompt(prompt, df):
19
+ schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
20
+ full_prompt = f"""
21
+ You are a SQL expert. The table is called 'df' and has the following columns:
22
+ {schema}
23
 
 
 
 
 
24
  User question: "{prompt}"
25
+
26
+ Write a valid SQL query using the 'df' table. Return only the SQL code.
27
+ """
28
+
29
+ url = "https://api.groq.com/openai/v1/chat/completions"
30
  headers = {
31
+ "Authorization": f"Bearer {GROQ_API_KEY}",
32
  "Content-Type": "application/json"
33
  }
34
  payload = {
35
+ "model": "llama3-70b-8192",
36
+ "messages": [{"role": "user", "content": full_prompt}],
37
+ "temperature": 0.3,
38
+ "max_tokens": 300
39
  }
40
 
41
+ response = requests.post(url, headers=headers, json=payload)
42
+ response.raise_for_status()
43
+ result = response.json()
44
+ return result['choices'][0]['message']['content'].strip("```sql").strip("```").strip()
45
 
46
+ # 🧽 Clean SQL for DuckDB
47
+ def clean_sql_for_duckdb(sql, df_columns):
48
  sql = sql.replace("`", '"')
49
+ for col in df_columns:
50
+ if " " in col and f'"{col}"' not in sql:
51
+ pattern = r'\b' + re.escape(col) + r'\b'
52
+ sql = re.sub(pattern, f'"{col}"', sql)
53
  return sql
54
 
55
+ # πŸ’¬ Main chatbot logic
56
+ def chatbot_interface(file, question):
57
  try:
58
  df = pd.read_excel(file)
59
+ sql = generate_sql_from_prompt(question, df)
60
+ cleaned_sql = clean_sql_for_duckdb(sql, df.columns)
61
+ result = duckdb.query(cleaned_sql).to_df()
62
+ return f"πŸ“œ SQL Query:\n```sql\n{sql}\n```", result
63
  except Exception as e:
64
+ return f"❌ Error: {str(e)}", pd.DataFrame()
65
 
66
+ # πŸŽ›οΈ Gradio UI
67
  with gr.Blocks() as demo:
68
+ gr.Markdown("## 🧠 Excel SQL Chatbot powered by Groq + LLaMA3")
69
+ with gr.Row():
70
+ file_input = gr.File(label="πŸ“‚ Upload Excel File (.xlsx)")
71
+ question = gr.Textbox(label="🧠 Ask your SQL question")
72
  submit = gr.Button("πŸš€ Generate & Run")
73
  sql_output = gr.Markdown()
74
  result_table = gr.Dataframe()
75
 
76
+ submit.click(fn=chatbot_interface, inputs=[file_input, question], outputs=[sql_output, result_table])
77
 
78
+ # πŸš€ Run the app
79
  if __name__ == "__main__":
80
+ demo.launch()