Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,62 +1,85 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
-
import torch
|
| 4 |
import duckdb
|
| 5 |
-
|
| 6 |
|
| 7 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
df = pd.read_csv('synthetic_profit.csv')
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# One-line schema for prompts
|
| 13 |
-
schema = ", ".join(df.columns)
|
| 14 |
-
|
| 15 |
-
# Load TAPEX for SQL generation
|
| 16 |
-
MODEL_ID = "microsoft/tapex-base-finetuned-wikisql"
|
| 17 |
-
device = 0 if torch.cuda.is_available() else -1
|
| 18 |
-
|
| 19 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 20 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID)
|
| 21 |
-
|
| 22 |
-
sql_gen = pipeline(
|
| 23 |
-
"text2text-generation",
|
| 24 |
-
model=model,
|
| 25 |
-
tokenizer=tokenizer,
|
| 26 |
-
framework="pt",
|
| 27 |
-
device=device,
|
| 28 |
-
max_length=128,
|
| 29 |
-
)
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
)
|
| 38 |
-
sql =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
try:
|
| 42 |
-
|
| 43 |
except Exception as e:
|
| 44 |
-
# Use a normal f-string with explicit \n for newlines
|
| 45 |
return (
|
| 46 |
-
f"β **SQL
|
| 47 |
f"```\n{e}\n```\n\n"
|
| 48 |
-
f"**Generated SQL**\n"
|
| 49 |
-
f"```sql\n{sql}\n```"
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
# 3) Format successful result
|
| 53 |
-
if df_out.empty:
|
| 54 |
-
return (
|
| 55 |
-
"No rows returned.\n\n"
|
| 56 |
f"**Generated SQL**\n```sql\n{sql}\n```"
|
| 57 |
)
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
|
|
|
| 4 |
import duckdb
|
| 5 |
+
import openai
|
| 6 |
|
| 7 |
+
# βββ 1) Set your OpenAI key via the SECRET: OPENAI_API_KEY βββββββββββββββββββ
|
| 8 |
+
openai.api_key = os.getenv("
|
| 9 |
+
|
| 10 |
+

|
| 11 |
+
|
| 12 |
+
")
|
| 13 |
+
|
| 14 |
+
# βββ 2) Load your synthetic data into DuckDB βββββββββββββββββββββββββββββββββ
|
| 15 |
df = pd.read_csv('synthetic_profit.csv')
|
| 16 |
+
conn = duckdb.connect(':memory:')
|
| 17 |
+
conn.register('sap', df)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# βββ 3) One-line schema description for prompting βββββββββββββββββββββββββββββ
|
| 20 |
+
schema = ", ".join(df.columns)
|
| 21 |
+
# e.g. "Region,Product,FiscalYear,FiscalQuarter,Revenue,Profit,ProfitMargin"
|
| 22 |
+
|
| 23 |
+
# βββ 4) Function to call OpenAI and generate SQL ββββββββββββββββββββββββββββββ
|
| 24 |
+
def generate_sql(question: str) -> str:
|
| 25 |
+
system = (
|
| 26 |
+
f"You are an expert SQL generator for a DuckDB table named `sap` "
|
| 27 |
+
f"with columns: {schema}. "
|
| 28 |
+
"Generate a valid SQL query that returns exactly what the user is asking. "
|
| 29 |
+
"Only return the SQL query, without any explanation."
|
| 30 |
+
)
|
| 31 |
+
messages = [
|
| 32 |
+
{"role": "system", "content": system},
|
| 33 |
+
{"role": "user", "content": question}
|
| 34 |
+
]
|
| 35 |
+
resp = openai.ChatCompletion.create(
|
| 36 |
+
model="gpt-3.5-turbo",
|
| 37 |
+
messages=messages,
|
| 38 |
+
temperature=0.0,
|
| 39 |
+
max_tokens=150,
|
| 40 |
)
|
| 41 |
+
sql = resp.choices[0].message.content.strip()
|
| 42 |
+
# Strip triple-backticks if present
|
| 43 |
+
if sql.startswith("```") and "```" in sql[3:]:
|
| 44 |
+
sql = "\n".join(sql.splitlines()[1:-1])
|
| 45 |
+
return sql
|
| 46 |
|
| 47 |
+
# βββ 5) Core QA function: NL β SQL β execute β format result βββββββββββββββββ
|
| 48 |
+
def answer_profitability(question: str) -> str:
|
| 49 |
+
# 5a) Generate SQL
|
| 50 |
+
sql = generate_sql(question)
|
| 51 |
+
|
| 52 |
+
# 5b) Try to run it
|
| 53 |
try:
|
| 54 |
+
out_df = conn.execute(sql).df()
|
| 55 |
except Exception as e:
|
|
|
|
| 56 |
return (
|
| 57 |
+
f"β **Error executing SQL**\n\n"
|
| 58 |
f"```\n{e}\n```\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
f"**Generated SQL**\n```sql\n{sql}\n```"
|
| 60 |
)
|
| 61 |
|
| 62 |
+
# 5c) Format the successful result
|
| 63 |
+
if out_df.empty:
|
| 64 |
+
return f"No rows returned.\n\n**SQL**\n```sql\n{sql}\n```"
|
| 65 |
+
# Singleβcell result β scalar
|
| 66 |
+
if out_df.shape == (1,1):
|
| 67 |
+
return str(out_df.iat[0,0])
|
| 68 |
+
# Otherwise β markdown table
|
| 69 |
+
return out_df.to_markdown(index=False)
|
| 70 |
+
|
| 71 |
+
# βββ 6) Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
+
iface = gr.Interface(
|
| 73 |
+
fn=answer_profitability,
|
| 74 |
+
inputs=gr.Textbox(lines=2, placeholder="Ask a question about profitabilityβ¦"),
|
| 75 |
+
outputs=gr.Markdown(),
|
| 76 |
+
title="SAP Profitability Q&A (OpenAI β SQL β DuckDB)",
|
| 77 |
+
description=(
|
| 78 |
+
"Uses OpenAIβs GPT-3.5-Turbo to translate your question into SQL, "
|
| 79 |
+
"executes it on the `sap` table in DuckDB, and returns the result."
|
| 80 |
+
),
|
| 81 |
+
allow_flagging="never",
|
| 82 |
+
)
|
| 83 |
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|