Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,25 +5,22 @@ import requests
|
|
| 5 |
import re
|
| 6 |
import os
|
| 7 |
|
| 8 |
-
#
|
| 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("π΄
|
| 14 |
return key
|
| 15 |
|
| 16 |
API_KEY = get_api_key()
|
| 17 |
|
| 18 |
-
# Generate SQL
|
| 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 |
-
|
| 26 |
-
|
| 27 |
url = "https://api.together.xyz/v1/completions"
|
| 28 |
headers = {
|
| 29 |
"Authorization": f"Bearer {API_KEY}",
|
|
@@ -32,20 +29,15 @@ Return only valid SQL."""
|
|
| 32 |
payload = {
|
| 33 |
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 34 |
"prompt": full_prompt,
|
| 35 |
-
"max_tokens":
|
| 36 |
-
"temperature": 0.
|
| 37 |
}
|
| 38 |
-
|
| 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 |
-
|
| 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:
|
|
@@ -53,27 +45,27 @@ def clean_sql(sql, cols):
|
|
| 53 |
sql = re.sub(rf'\b{re.escape(c)}\b', f'"{c}"', sql)
|
| 54 |
return sql
|
| 55 |
|
| 56 |
-
# Main
|
| 57 |
-
def chat_interface(file,
|
| 58 |
try:
|
| 59 |
df = pd.read_excel(file)
|
| 60 |
-
sql = generate_sql(
|
| 61 |
sql = clean_sql(sql, df.columns)
|
| 62 |
-
|
| 63 |
-
|
| 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
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
| 77 |
|
| 78 |
if __name__ == "__main__":
|
| 79 |
demo.launch()
|
|
|
|
| 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}",
|
|
|
|
| 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:
|
|
|
|
| 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()
|