Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,73 +1,81 @@
|
|
1 |
-
|
|
|
2 |
import gradio as gr
|
3 |
import pandas as pd
|
4 |
import duckdb
|
5 |
-
import
|
6 |
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
7 |
-
import openai.error
|
8 |
|
9 |
-
#
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
|
15 |
-
schema = ", ".join(df.columns)
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
hf_tok = AutoTokenizer.from_pretrained(HF_MODEL)
|
20 |
-
hf_mod = AutoModelForSeq2SeqLM.from_pretrained(HF_MODEL)
|
21 |
-
hf_gen = pipeline("text2text-generation", model=hf_mod, tokenizer=hf_tok, device=-1)
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
def generate_sql(question: str) -> str:
|
24 |
prompt = (
|
25 |
-
f"
|
26 |
-
f"
|
|
|
27 |
)
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
{"role":"user","content":question}
|
34 |
-
],
|
35 |
-
temperature=0.0,
|
36 |
-
max_tokens=150,
|
37 |
-
)
|
38 |
-
sql = resp.choices[0].message.content.strip()
|
39 |
-
except openai.error.InvalidRequestError as e:
|
40 |
-
# catch non-quota OpenAI errors here if you want
|
41 |
-
raise
|
42 |
-
except openai.error.RateLimitError as e:
|
43 |
-
# 429 fallback to Hugging Face
|
44 |
-
fallback_prompt = f"Translate to SQL over `sap({schema})`:\n{question}"
|
45 |
-
sql = hf_gen(fallback_prompt, max_length=128)[0]["generated_text"]
|
46 |
-
# strip ``` fences if present
|
47 |
-
if sql.startswith("```") and sql.endswith("```"):
|
48 |
-
sql = "\n".join(sql.splitlines()[1:-1])
|
49 |
-
return sql
|
50 |
|
|
|
51 |
def answer_profitability(question: str) -> str:
|
|
|
52 |
sql = generate_sql(question)
|
|
|
|
|
53 |
try:
|
54 |
-
|
55 |
except Exception as e:
|
56 |
-
return
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
58 |
return f"No results.\n\n```sql\n{sql}\n```"
|
59 |
-
if
|
60 |
-
return str(
|
61 |
-
return
|
62 |
|
|
|
63 |
iface = gr.Interface(
|
64 |
fn=answer_profitability,
|
65 |
-
inputs=gr.Textbox(lines=2, label="Question"),
|
66 |
-
outputs=gr.Textbox(lines=8, label="Answer"),
|
67 |
-
title="SAP Profitability Q&A",
|
68 |
-
description=
|
|
|
|
|
|
|
69 |
allow_flagging="never",
|
70 |
)
|
71 |
|
72 |
-
if __name__=="__main__":
|
73 |
iface.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
1 |
+
# app.py
|
2 |
+
|
3 |
import gradio as gr
|
4 |
import pandas as pd
|
5 |
import duckdb
|
6 |
+
import torch
|
7 |
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
|
|
8 |
|
9 |
+
# 1) Load your synthetic data into DuckDB
|
10 |
+
df = pd.read_csv("synthetic_profit.csv")
|
11 |
+
conn = duckdb.connect(":memory:")
|
12 |
+
conn.register("sap", df)
|
13 |
+
|
14 |
+
# 2) Build a one-line schema string for prompts
|
15 |
+
schema = ", ".join(df.columns) # e.g. "Region, Product, FiscalYear, ..."
|
16 |
|
17 |
+
# 3) Load an open-source model fine-tuned on WikiSQL for SQL generation
|
18 |
+
MODEL_ID = "mrm8488/t5-base-finetuned-wikisql"
|
19 |
+
device = 0 if torch.cuda.is_available() else -1
|
|
|
20 |
|
21 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
22 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID)
|
|
|
|
|
|
|
23 |
|
24 |
+
sql_generator = pipeline(
|
25 |
+
"text2text-generation",
|
26 |
+
model=model,
|
27 |
+
tokenizer=tokenizer,
|
28 |
+
framework="pt",
|
29 |
+
device=device,
|
30 |
+
max_length=128,
|
31 |
+
)
|
32 |
+
|
33 |
+
# 4) Function to turn a natural-language question into SQL
|
34 |
def generate_sql(question: str) -> str:
|
35 |
prompt = (
|
36 |
+
f"Translate the following English question into SQL for a DuckDB table named `sap` "
|
37 |
+
f"with columns ({schema}):\n\n"
|
38 |
+
f"Question: {question}\nSQL:"
|
39 |
)
|
40 |
+
out = sql_generator(prompt)[0]["generated_text"].strip()
|
41 |
+
# strip triple-backticks if present
|
42 |
+
if out.startswith("```") and out.endswith("```"):
|
43 |
+
out = "\n".join(out.splitlines()[1:-1])
|
44 |
+
return out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
# 5) Core Q&A function: NL → SQL → execute → format
|
47 |
def answer_profitability(question: str) -> str:
|
48 |
+
# a) generate the SQL
|
49 |
sql = generate_sql(question)
|
50 |
+
|
51 |
+
# b) execute it
|
52 |
try:
|
53 |
+
result_df = conn.execute(sql).df()
|
54 |
except Exception as e:
|
55 |
+
return (
|
56 |
+
f"❌ SQL execution error:\n{e}\n\n"
|
57 |
+
f"Generated SQL:\n```sql\n{sql}\n```"
|
58 |
+
)
|
59 |
+
|
60 |
+
# c) format the result
|
61 |
+
if result_df.empty:
|
62 |
return f"No results.\n\n```sql\n{sql}\n```"
|
63 |
+
if result_df.shape == (1,1):
|
64 |
+
return str(result_df.iat[0,0])
|
65 |
+
return result_df.to_markdown(index=False)
|
66 |
|
67 |
+
# 6) Gradio UI with explicit inputs & outputs
|
68 |
iface = gr.Interface(
|
69 |
fn=answer_profitability,
|
70 |
+
inputs=gr.Textbox(lines=2, placeholder="Ask a question about profitability…", label="Question"),
|
71 |
+
outputs=gr.Textbox(lines=8, placeholder="Answer appears here", label="Answer"),
|
72 |
+
title="SAP Profitability Q&A (HF SQL Generation + DuckDB)",
|
73 |
+
description=(
|
74 |
+
"Uses an open-source Hugging Face model fine-tuned on WikiSQL to translate your question into SQL, "
|
75 |
+
"executes it against the `sap` table in DuckDB, and returns the result."
|
76 |
+
),
|
77 |
allow_flagging="never",
|
78 |
)
|
79 |
|
80 |
+
if __name__ == "__main__":
|
81 |
iface.launch(server_name="0.0.0.0", server_port=7860)
|