Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,31 @@
|
|
| 1 |
-
import
|
|
|
|
|
|
|
| 2 |
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
| 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,13 +33,48 @@ def test_together_api():
|
|
| 15 |
}
|
| 16 |
payload = {
|
| 17 |
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 18 |
-
"messages": [{"role": "user", "content":
|
| 19 |
"temperature": 0.2,
|
| 20 |
"max_tokens": 200
|
| 21 |
}
|
| 22 |
|
| 23 |
response = requests.post(url, headers=headers, json=payload)
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import duckdb
|
| 4 |
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
|
| 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 |
url = "https://api.together.xyz/v1/chat/completions"
|
| 30 |
headers = {
|
| 31 |
"Authorization": f"Bearer {TOGETHER_API_KEY}",
|
|
|
|
| 33 |
}
|
| 34 |
payload = {
|
| 35 |
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 36 |
+
"messages": [{"role": "user", "content": full_prompt}],
|
| 37 |
"temperature": 0.2,
|
| 38 |
"max_tokens": 200
|
| 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 compatibility
|
| 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 function
|
| 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 with Together API")
|
| 69 |
+
with gr.Row():
|
| 70 |
+
file_input = gr.File(label="π Upload Excel File (.xlsx)")
|
| 71 |
+
question = gr.Textbox(label="π§ Ask a question", placeholder="e.g., Show average salary by department")
|
| 72 |
+
submit = gr.Button("π Generate & Query")
|
| 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 |
+
# π Launch the app
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
demo.launch()
|