Spaces:
Running
Running
Update app.py
Browse files
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
|
| 10 |
-
""
|
| 11 |
-
|
| 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 |
-
|
| 20 |
-
|
| 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":
|
| 51 |
"temperature": 0.2,
|
| 52 |
"max_tokens": 200
|
| 53 |
}
|
| 54 |
|
| 55 |
response = requests.post(url, headers=headers, json=payload)
|
| 56 |
-
response.
|
| 57 |
-
|
| 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 |
-
|
| 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()
|
|
|