Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,77 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
"""
|
| 7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
message,
|
| 12 |
-
history: list[tuple[str, str]],
|
| 13 |
-
system_message,
|
| 14 |
-
max_tokens,
|
| 15 |
-
temperature,
|
| 16 |
-
top_p,
|
| 17 |
-
):
|
| 18 |
-
messages = [{"role": "system", "content": system_message}]
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
messages.append({"role": "user", "content": val[0]})
|
| 23 |
-
if val[1]:
|
| 24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
response =
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
"""
|
| 46 |
-
demo = gr.ChatInterface(
|
| 47 |
-
respond,
|
| 48 |
-
additional_inputs=[
|
| 49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 52 |
-
gr.Slider(
|
| 53 |
-
minimum=0.1,
|
| 54 |
-
maximum=1.0,
|
| 55 |
-
value=0.95,
|
| 56 |
-
step=0.05,
|
| 57 |
-
label="Top-p (nucleus sampling)",
|
| 58 |
-
),
|
| 59 |
-
],
|
| 60 |
-
)
|
| 61 |
|
|
|
|
| 62 |
|
|
|
|
| 63 |
if __name__ == "__main__":
|
| 64 |
-
demo.launch()
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
|
| 3 |
import gradio as gr
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import duckdb
|
| 6 |
+
import requests
|
| 7 |
+
import re
|
| 8 |
+
import io
|
| 9 |
+
import os
|
| 10 |
|
| 11 |
+
# Load Together API Key from environment variable or fallback
|
| 12 |
+
TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY", "your-api-key-here") # Replace with HF Secret
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Function to generate SQL from a prompt
|
| 15 |
+
def generate_sql_from_prompt(prompt, df):
|
| 16 |
+
schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
|
| 17 |
+
full_prompt = f"""
|
| 18 |
+
You are a SQL expert. Here is a table called 'df' with the following schema:
|
| 19 |
+
{schema}
|
| 20 |
|
| 21 |
+
User question: "{prompt}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
Write a valid SQL query using the 'df' table. Return only the SQL code.
|
| 24 |
+
"""
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
url = "https://api.together.xyz/v1/chat/completions"
|
| 27 |
+
headers = {
|
| 28 |
+
"Authorization": f"Bearer {TOGETHER_API_KEY}",
|
| 29 |
+
"Content-Type": "application/json"
|
| 30 |
+
}
|
| 31 |
+
payload = {
|
| 32 |
+
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 33 |
+
"messages": [{"role": "user", "content": full_prompt}],
|
| 34 |
+
"temperature": 0.2,
|
| 35 |
+
"max_tokens": 200
|
| 36 |
+
}
|
| 37 |
|
| 38 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 39 |
+
response.raise_for_status()
|
| 40 |
+
result = response.json()
|
| 41 |
+
return result['choices'][0]['message']['content'].strip("```sql").strip("```").strip()
|
| 42 |
|
| 43 |
+
# Function to clean SQL for DuckDB
|
| 44 |
+
def clean_sql_for_duckdb(sql, df_columns):
|
| 45 |
+
sql = sql.replace("`", '"')
|
| 46 |
+
for col in df_columns:
|
| 47 |
+
if " " in col and f'"{col}"' not in sql:
|
| 48 |
+
pattern = r'\b' + re.escape(col) + r'\b'
|
| 49 |
+
sql = re.sub(pattern, f'"{col}"', sql)
|
| 50 |
+
return sql
|
| 51 |
|
| 52 |
+
# Combined Gradio function
|
| 53 |
+
def chatbot_interface(file, question):
|
| 54 |
+
try:
|
| 55 |
+
df = pd.read_excel(file)
|
| 56 |
+
sql = generate_sql_from_prompt(question, df)
|
| 57 |
+
cleaned_sql = clean_sql_for_duckdb(sql, df.columns)
|
| 58 |
+
result = duckdb.query(cleaned_sql).to_df()
|
| 59 |
+
return f"π SQL Query:\n```sql\n{sql}\n```", result
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return f"β Error: {str(e)}", pd.DataFrame()
|
| 62 |
|
| 63 |
+
# Gradio UI
|
| 64 |
+
with gr.Blocks() as demo:
|
| 65 |
+
gr.Markdown("## π Excel SQL Chatbot with Together API")
|
| 66 |
+
file_input = gr.File(label="π Upload Excel File (.xlsx)")
|
| 67 |
+
question = gr.Textbox(label="π§ Ask a question about your data", placeholder="e.g., Show me the average sales by region")
|
| 68 |
+
submit = gr.Button("π Generate & Query")
|
| 69 |
|
| 70 |
+
sql_output = gr.Markdown()
|
| 71 |
+
result_table = gr.Dataframe()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
submit.click(fn=chatbot_interface, inputs=[file_input, question], outputs=[sql_output, result_table])
|
| 74 |
|
| 75 |
+
# Launch app
|
| 76 |
if __name__ == "__main__":
|
| 77 |
+
demo.launch()
|