Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,29 +4,27 @@ import pandas as pd
|
|
4 |
import duckdb
|
5 |
import openai
|
6 |
|
7 |
-
# 1)
|
8 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
9 |
|
10 |
-
# 2)
|
11 |
df = pd.read_csv('synthetic_profit.csv')
|
12 |
conn = duckdb.connect(':memory:')
|
13 |
conn.register('sap', df)
|
14 |
|
15 |
-
#
|
16 |
-
schema = ", ".join(df.columns)
|
17 |
-
# e.g. "Region,Product,FiscalYear,FiscalQuarter,Revenue,Profit,ProfitMargin"
|
18 |
|
19 |
-
#
|
20 |
def generate_sql(question: str) -> str:
|
21 |
system = (
|
22 |
f"You are an expert SQL generator for a DuckDB table named `sap` "
|
23 |
f"with columns: {schema}. "
|
24 |
-
"
|
25 |
-
"Only return the SQL query, without any explanation."
|
26 |
)
|
27 |
messages = [
|
28 |
-
{"role": "system",
|
29 |
-
{"role": "user",
|
30 |
]
|
31 |
resp = openai.ChatCompletion.create(
|
32 |
model="gpt-3.5-turbo",
|
@@ -35,40 +33,38 @@ def generate_sql(question: str) -> str:
|
|
35 |
max_tokens=150,
|
36 |
)
|
37 |
sql = resp.choices[0].message.content.strip()
|
38 |
-
#
|
39 |
-
if sql.startswith("```") and "```"
|
40 |
sql = "\n".join(sql.splitlines()[1:-1])
|
41 |
return sql
|
42 |
|
43 |
-
#
|
44 |
def answer_profitability(question: str) -> str:
|
45 |
-
#
|
46 |
sql = generate_sql(question)
|
47 |
-
|
48 |
-
# 5b) Try to run it
|
49 |
try:
|
50 |
-
|
51 |
except Exception as e:
|
52 |
return (
|
53 |
f"β **Error executing SQL**\n\n"
|
54 |
f"```\n{e}\n```\n\n"
|
55 |
f"**Generated SQL**\n```sql\n{sql}\n```"
|
56 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
-
|
59 |
-
if out_df.empty:
|
60 |
-
return f"No rows returned.\n\n**SQL**\n```sql\n{sql}\n```"
|
61 |
-
# Singleβcell result β scalar
|
62 |
-
if out_df.shape == (1,1):
|
63 |
-
return str(out_df.iat[0,0])
|
64 |
-
# Otherwise β markdown table
|
65 |
-
return out_df.to_markdown(index=False)
|
66 |
-
|
67 |
-
# βββ 6) Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
68 |
iface = gr.Interface(
|
69 |
fn=answer_profitability,
|
70 |
inputs=gr.Textbox(lines=2, placeholder="Ask a question about profitabilityβ¦"),
|
71 |
-
outputs=gr.Markdown(),
|
72 |
title="SAP Profitability Q&A (OpenAI β SQL β DuckDB)",
|
73 |
description=(
|
74 |
"Uses OpenAIβs GPT-3.5-Turbo to translate your question into SQL, "
|
|
|
4 |
import duckdb
|
5 |
import openai
|
6 |
|
7 |
+
# 1) Read your OpenAI key from the Spaceβs Secrets
|
8 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
9 |
|
10 |
+
# 2) Load your synthetic data into DuckDB
|
11 |
df = pd.read_csv('synthetic_profit.csv')
|
12 |
conn = duckdb.connect(':memory:')
|
13 |
conn.register('sap', df)
|
14 |
|
15 |
+
# 3) Build a one-line schema description for prompts
|
16 |
+
schema = ", ".join(df.columns) # e.g. "Region,Product,FiscalYear,FiscalQuarter,Revenue,Profit,ProfitMargin"
|
|
|
17 |
|
18 |
+
# 4) SQL-generation via OpenAI
|
19 |
def generate_sql(question: str) -> str:
|
20 |
system = (
|
21 |
f"You are an expert SQL generator for a DuckDB table named `sap` "
|
22 |
f"with columns: {schema}. "
|
23 |
+
"Translate the userβs question into a valid SQL query and return _only_ the SQL."
|
|
|
24 |
)
|
25 |
messages = [
|
26 |
+
{"role": "system", "content": system},
|
27 |
+
{"role": "user", "content": question},
|
28 |
]
|
29 |
resp = openai.ChatCompletion.create(
|
30 |
model="gpt-3.5-turbo",
|
|
|
33 |
max_tokens=150,
|
34 |
)
|
35 |
sql = resp.choices[0].message.content.strip()
|
36 |
+
# strip triple-backticks if present
|
37 |
+
if sql.startswith("```") and sql.endswith("```"):
|
38 |
sql = "\n".join(sql.splitlines()[1:-1])
|
39 |
return sql
|
40 |
|
41 |
+
# 5) Core QA function: NL β SQL β execute β format
|
42 |
def answer_profitability(question: str) -> str:
|
43 |
+
# a) generate SQL
|
44 |
sql = generate_sql(question)
|
45 |
+
# b) try to run it
|
|
|
46 |
try:
|
47 |
+
result_df = conn.execute(sql).df()
|
48 |
except Exception as e:
|
49 |
return (
|
50 |
f"β **Error executing SQL**\n\n"
|
51 |
f"```\n{e}\n```\n\n"
|
52 |
f"**Generated SQL**\n```sql\n{sql}\n```"
|
53 |
)
|
54 |
+
# c) format the result
|
55 |
+
if result_df.empty:
|
56 |
+
return f"No rows returned.\n\n**Generated SQL**\n```sql\n{sql}\n```"
|
57 |
+
# single-cell β just the value
|
58 |
+
if result_df.shape == (1,1):
|
59 |
+
return str(result_df.iat[0,0])
|
60 |
+
# otherwise, markdown table
|
61 |
+
return result_df.to_markdown(index=False)
|
62 |
|
63 |
+
# 6) Gradio UI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
iface = gr.Interface(
|
65 |
fn=answer_profitability,
|
66 |
inputs=gr.Textbox(lines=2, placeholder="Ask a question about profitabilityβ¦"),
|
67 |
+
outputs=gr.Markdown(), # renders errors, code, and tables nicely
|
68 |
title="SAP Profitability Q&A (OpenAI β SQL β DuckDB)",
|
69 |
description=(
|
70 |
"Uses OpenAIβs GPT-3.5-Turbo to translate your question into SQL, "
|