PD03 commited on
Commit
0b8ba87
·
verified ·
1 Parent(s): 0c9daeb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -49
app.py CHANGED
@@ -1,73 +1,81 @@
1
- import os
 
2
  import gradio as gr
3
  import pandas as pd
4
  import duckdb
5
- import openai
6
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
7
- import openai.error
8
 
9
- # Load OpenAI key
10
- openai.api_key = os.getenv("OPENAI_API_KEY")
 
 
 
 
 
11
 
12
- # Prepare DuckDB
13
- df = pd.read_csv("synthetic_profit.csv")
14
- conn = duckdb.connect(":memory:"); conn.register("sap", df)
15
- schema = ", ".join(df.columns)
16
 
17
- # Prepare HF fallback pipeline once —
18
- HF_MODEL = "google/flan-t5-small"
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"You are an expert SQL generator for DuckDB table `sap` with columns: {schema}.\n"
26
- f"Translate the user’s question into a valid SQL query. Return ONLY the SQL."
 
27
  )
28
- try:
29
- resp = openai.chat.completions.create(
30
- model="gpt-3.5-turbo",
31
- messages=[
32
- {"role":"system","content":prompt},
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
- out_df = conn.execute(sql).df()
55
  except Exception as e:
56
- return f"❌ SQL error:\n{e}\n\n```sql\n{sql}\n```"
57
- if out_df.empty:
 
 
 
 
 
58
  return f"No results.\n\n```sql\n{sql}\n```"
59
- if out_df.shape == (1,1):
60
- return str(out_df.iat[0,0])
61
- return out_df.to_markdown(index=False)
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="Uses OpenAI → DuckDB, falling back to Flan-T5-Small on 429s.",
 
 
 
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)