AliInamdar commited on
Commit
2fba167
Β·
verified Β·
1 Parent(s): bdaf6ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -71
app.py CHANGED
@@ -1,45 +1,13 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import duckdb
4
- import requests
5
- import re
6
- import io
7
  import os
 
8
 
9
- def get_together_api_key():
10
- """
11
- Retrieves Together API key from Hugging Face Secrets (hosted) or fallback to local key (dev).
12
- """
13
- key = os.environ.get("TOGETHER_API_KEY")
14
-
15
- if key:
16
- print("βœ… TOGETHER_API_KEY loaded from Hugging Face secret.")
17
- return key
18
 
19
- # For local dev fallback
20
- local_key = "your-local-api-key-here" # πŸ‘ˆ REPLACE with your actual key
21
- if local_key:
22
- print("⚠️ Using local fallback API key.")
23
- return local_key
24
-
25
- raise RuntimeError("❌ TOGETHER_API_KEY is missing. Set it in Hugging Face Secrets or update the fallback.")
26
-
27
-
28
- # βœ… READ API KEY from Hugging Face Secret
29
- TOGETHER_API_KEY = get_together_api_key()
30
- if not TOGETHER_API_KEY:
31
- raise RuntimeError("❌ TOGETHER_API_KEY not found. Set it in Hugging Face > Settings > Secrets.")
32
 
33
- def generate_sql_from_prompt(prompt, df):
34
- schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
35
- full_prompt = f"""
36
- You are a SQL expert. Here is a table called 'df' with the following schema:
37
- {schema}
38
-
39
- User question: "{prompt}"
40
-
41
- Write a valid SQL query using the 'df' table. Return only the SQL code.
42
- """
43
  url = "https://api.together.xyz/v1/chat/completions"
44
  headers = {
45
  "Authorization": f"Bearer {TOGETHER_API_KEY}",
@@ -47,42 +15,13 @@ Write a valid SQL query using the 'df' table. Return only the SQL code.
47
  }
48
  payload = {
49
  "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
50
- "messages": [{"role": "user", "content": full_prompt}],
51
  "temperature": 0.2,
52
  "max_tokens": 200
53
  }
54
 
55
  response = requests.post(url, headers=headers, json=payload)
56
- response.raise_for_status()
57
- result = response.json()
58
- return result['choices'][0]['message']['content'].strip("```sql").strip("```").strip()
59
-
60
- def clean_sql_for_duckdb(sql, df_columns):
61
- sql = sql.replace("`", '"')
62
- for col in df_columns:
63
- if " " in col and f'"{col}"' not in sql:
64
- pattern = r'\b' + re.escape(col) + r'\b'
65
- sql = re.sub(pattern, f'"{col}"', sql)
66
- return sql
67
-
68
- def chatbot_interface(file, question):
69
- try:
70
- df = pd.read_excel(file)
71
- sql = generate_sql_from_prompt(question, df)
72
- cleaned_sql = clean_sql_for_duckdb(sql, df.columns)
73
- result = duckdb.query(cleaned_sql).to_df()
74
- return f"πŸ“œ SQL Query:\n```sql\n{sql}\n```", result
75
- except Exception as e:
76
- return f"❌ Error: {str(e)}", pd.DataFrame()
77
-
78
- with gr.Blocks() as demo:
79
- gr.Markdown("## πŸ“Š Excel SQL Chatbot with Together API")
80
- file_input = gr.File(label="πŸ“‚ Upload Excel File (.xlsx)")
81
- question = gr.Textbox(label="🧠 Ask a question about your data")
82
- submit = gr.Button("πŸš€ Generate & Query")
83
- sql_output = gr.Markdown()
84
- result_table = gr.Dataframe()
85
- submit.click(fn=chatbot_interface, inputs=[file_input, question], outputs=[sql_output, result_table])
86
 
87
- if __name__ == "__main__":
88
- demo.launch()
 
 
 
 
 
 
 
1
  import os
2
+ import requests
3
 
4
+ def test_together_api():
5
+ TOGETHER_API_KEY = os.environ.get("TOGETHER_API_KEY")
6
+ print("πŸ” API Key starts with:", TOGETHER_API_KEY[:8] if TOGETHER_API_KEY else "None")
 
 
 
 
 
 
7
 
8
+ if not TOGETHER_API_KEY:
9
+ raise RuntimeError("❌ TOGETHER_API_KEY not found. Set it in Hugging Face > Settings > Secrets.")
 
 
 
 
 
 
 
 
 
 
 
10
 
 
 
 
 
 
 
 
 
 
 
11
  url = "https://api.together.xyz/v1/chat/completions"
12
  headers = {
13
  "Authorization": f"Bearer {TOGETHER_API_KEY}",
 
15
  }
16
  payload = {
17
  "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
18
+ "messages": [{"role": "user", "content": "Write a SQL query to select all rows from table `df`"}],
19
  "temperature": 0.2,
20
  "max_tokens": 200
21
  }
22
 
23
  response = requests.post(url, headers=headers, json=payload)
24
+ print("βœ… API call status:", response.status_code)
25
+ print("πŸ“¦ Response JSON:", response.json())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ test_together_api()