Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,38 +1,39 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import time
|
| 4 |
-
import sqlite3
|
| 5 |
-
import textwrap
|
| 6 |
-
import requests
|
| 7 |
import gradio as gr
|
| 8 |
|
| 9 |
-
# -----------------------------
|
| 10 |
-
#
|
| 11 |
-
# -----------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
DB_PATH = "company.db"
|
| 13 |
SCHEMA_FILE = "schema.sql"
|
| 14 |
-
MODEL_ID = "tscholak/t5-base-spider"
|
| 15 |
-
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
|
| 16 |
-
HF_TOKEN = os.getenv("HF_TOKEN") # set in Space > Settings > Secrets
|
| 17 |
-
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 18 |
|
| 19 |
-
# -----------------------------
|
| 20 |
-
#
|
| 21 |
-
# -----------------------------
|
| 22 |
def create_db_if_needed():
|
|
|
|
| 23 |
if os.path.exists(DB_PATH):
|
| 24 |
return
|
| 25 |
if not os.path.isfile(SCHEMA_FILE):
|
| 26 |
-
raise FileNotFoundError("schema.sql
|
| 27 |
-
with open(SCHEMA_FILE) as f:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
# -----------------------------
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def nlp_to_sql(nl_query: str, schema_ddl: str) -> str:
|
| 36 |
prompt = textwrap.dedent(f"""
|
| 37 |
### Task
|
| 38 |
Translate the following natural language question into ONE valid SQLite SQL query.
|
|
@@ -41,93 +42,84 @@ def nlp_to_sql(nl_query: str, schema_ddl: str) -> str:
|
|
| 41 |
{schema_ddl}
|
| 42 |
|
| 43 |
### Question
|
| 44 |
-
{
|
| 45 |
|
| 46 |
### SQL
|
| 47 |
""")
|
| 48 |
-
payload = {
|
| 49 |
-
"inputs": prompt,
|
| 50 |
-
"parameters": {"max_new_tokens": 256}
|
| 51 |
-
}
|
| 52 |
|
| 53 |
try:
|
| 54 |
-
|
| 55 |
except Exception as e:
|
| 56 |
-
return f"β
|
| 57 |
|
| 58 |
-
if
|
| 59 |
-
return f"β API error {
|
| 60 |
|
|
|
|
| 61 |
try:
|
| 62 |
-
|
| 63 |
-
except
|
| 64 |
-
return "β
|
| 65 |
-
|
| 66 |
-
if not isinstance(output, list) or not output:
|
| 67 |
-
return "β Model returned empty output."
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
else:
|
| 73 |
-
sql = generated.strip()
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# -----------------------------
|
| 78 |
-
# Pipeline: NL β SQL β Execute
|
| 79 |
-
# -----------------------------
|
| 80 |
def run_pipeline(nl_query: str):
|
|
|
|
| 81 |
trace = []
|
| 82 |
-
t0 = time.time()
|
| 83 |
|
| 84 |
-
#
|
| 85 |
create_db_if_needed()
|
| 86 |
|
| 87 |
-
#
|
| 88 |
with open(SCHEMA_FILE) as f:
|
| 89 |
schema_ddl = f.read()
|
| 90 |
-
trace.append(("Schema
|
| 91 |
|
| 92 |
-
#
|
| 93 |
sql_query = nlp_to_sql(nl_query, schema_ddl)
|
| 94 |
-
trace.append(("LLM
|
| 95 |
|
| 96 |
-
#
|
| 97 |
try:
|
| 98 |
with sqlite3.connect(DB_PATH) as conn:
|
| 99 |
cur = conn.execute(sql_query)
|
| 100 |
rows = cur.fetchall()
|
| 101 |
cols = [d[0] for d in cur.description] if cur.description else []
|
| 102 |
result = {"columns": cols, "rows": rows}
|
| 103 |
-
trace.append(("
|
| 104 |
except Exception as e:
|
| 105 |
result = {"error": str(e)}
|
| 106 |
-
trace.append(("
|
| 107 |
-
|
| 108 |
-
trace.append(("
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
# -----------------------------
|
| 117 |
-
#
|
| 118 |
-
# -----------------------------
|
| 119 |
-
with gr.Blocks(title="NLP
|
| 120 |
-
gr.Markdown("## NLP β SQL
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
with gr.Row():
|
| 124 |
-
sql_out
|
| 125 |
-
|
| 126 |
trace_out = gr.Textbox(label="Trace", lines=6)
|
| 127 |
-
|
| 128 |
run_btn = gr.Button("Run")
|
| 129 |
-
run_btn.click(
|
| 130 |
-
outputs=[sql_out, result_out, trace_out])
|
| 131 |
|
| 132 |
if __name__ == "__main__":
|
| 133 |
demo.launch()
|
|
|
|
| 1 |
+
import os, time, json, sqlite3, textwrap, requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
|
| 4 |
+
# -------------------------------------------------
|
| 5 |
+
# 1. CONFIGURATION
|
| 6 |
+
# -------------------------------------------------
|
| 7 |
+
MODEL_ID = "defog/sqlcoder-7b-nl2sql-beta" # working public model
|
| 8 |
+
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
|
| 9 |
+
|
| 10 |
+
HF_TOKEN = os.getenv("HF_TOKEN") # set in Space β Settings β Secrets
|
| 11 |
+
if not HF_TOKEN:
|
| 12 |
+
raise RuntimeError("HF_TOKEN secret not found. "
|
| 13 |
+
"Add it in Space Settings β Secrets.")
|
| 14 |
+
|
| 15 |
+
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 16 |
+
|
| 17 |
DB_PATH = "company.db"
|
| 18 |
SCHEMA_FILE = "schema.sql"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
# -------------------------------------------------
|
| 21 |
+
# 2. UTIL: BUILD SQLITE DB IF NEEDED
|
| 22 |
+
# -------------------------------------------------
|
| 23 |
def create_db_if_needed():
|
| 24 |
+
"""Create SQLite DB from schema.sql the first time the app runs."""
|
| 25 |
if os.path.exists(DB_PATH):
|
| 26 |
return
|
| 27 |
if not os.path.isfile(SCHEMA_FILE):
|
| 28 |
+
raise FileNotFoundError("schema.sql file is missing in the Space.")
|
| 29 |
+
with open(SCHEMA_FILE) as f, sqlite3.connect(DB_PATH) as conn:
|
| 30 |
+
conn.executescript(f.read())
|
| 31 |
+
|
| 32 |
+
# -------------------------------------------------
|
| 33 |
+
# 3. UTIL: CALL HUGGING FACE MODEL
|
| 34 |
+
# -------------------------------------------------
|
| 35 |
+
def nlp_to_sql(question: str, schema_ddl: str) -> str:
|
| 36 |
+
"""Call HF model to convert NL question into SQL."""
|
|
|
|
| 37 |
prompt = textwrap.dedent(f"""
|
| 38 |
### Task
|
| 39 |
Translate the following natural language question into ONE valid SQLite SQL query.
|
|
|
|
| 42 |
{schema_ddl}
|
| 43 |
|
| 44 |
### Question
|
| 45 |
+
{question}
|
| 46 |
|
| 47 |
### SQL
|
| 48 |
""")
|
| 49 |
+
payload = {"inputs": prompt, "parameters": {"max_new_tokens": 256}}
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
try:
|
| 52 |
+
r = requests.post(API_URL, headers=HEADERS, json=payload, timeout=60)
|
| 53 |
except Exception as e:
|
| 54 |
+
return f"β Connection error: {e}"
|
| 55 |
|
| 56 |
+
if r.status_code != 200:
|
| 57 |
+
return f"β API error {r.status_code}: {r.text}"
|
| 58 |
|
| 59 |
+
# Parse JSON
|
| 60 |
try:
|
| 61 |
+
generated = r.json()[0]["generated_text"]
|
| 62 |
+
except Exception:
|
| 63 |
+
return "β Invalid JSON response."
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
# Extract SQL
|
| 66 |
+
sql = generated.split("### SQL")[-1].strip()
|
| 67 |
+
return sql or "β Empty SQL returned."
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
# -------------------------------------------------
|
| 70 |
+
# 4. PIPELINE: NL β SQL β EXECUTE
|
| 71 |
+
# -------------------------------------------------
|
|
|
|
|
|
|
| 72 |
def run_pipeline(nl_query: str):
|
| 73 |
+
start = time.time()
|
| 74 |
trace = []
|
|
|
|
| 75 |
|
| 76 |
+
# DB setup
|
| 77 |
create_db_if_needed()
|
| 78 |
|
| 79 |
+
# Load schema
|
| 80 |
with open(SCHEMA_FILE) as f:
|
| 81 |
schema_ddl = f.read()
|
| 82 |
+
trace.append(("Schema", "loaded"))
|
| 83 |
|
| 84 |
+
# Convert NL β SQL
|
| 85 |
sql_query = nlp_to_sql(nl_query, schema_ddl)
|
| 86 |
+
trace.append(("LLM", sql_query))
|
| 87 |
|
| 88 |
+
# Execute SQL
|
| 89 |
try:
|
| 90 |
with sqlite3.connect(DB_PATH) as conn:
|
| 91 |
cur = conn.execute(sql_query)
|
| 92 |
rows = cur.fetchall()
|
| 93 |
cols = [d[0] for d in cur.description] if cur.description else []
|
| 94 |
result = {"columns": cols, "rows": rows}
|
| 95 |
+
trace.append(("Exec", f"{len(rows)} rows"))
|
| 96 |
except Exception as e:
|
| 97 |
result = {"error": str(e)}
|
| 98 |
+
trace.append(("Exec error", str(e)))
|
| 99 |
+
|
| 100 |
+
trace.append(("Time", f"{time.time() - start:.2f}s"))
|
| 101 |
+
|
| 102 |
+
return (
|
| 103 |
+
sql_query,
|
| 104 |
+
json.dumps(result, indent=2, ensure_ascii=False),
|
| 105 |
+
"\n".join(f"{s}: {m}" for s, m in trace),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# -------------------------------------------------
|
| 109 |
+
# 5. GRADIO UI
|
| 110 |
+
# -------------------------------------------------
|
| 111 |
+
with gr.Blocks(title="NLP β SQL (SQLite, HF Hub)") as demo:
|
| 112 |
+
gr.Markdown("### NLP β SQL demo β’ SQLite backend β’ Hugging Face Inference API")
|
| 113 |
+
query_in = gr.Textbox(
|
| 114 |
+
label="Natural-language question",
|
| 115 |
+
placeholder="e.g. List all employees in Engineering hired after 2021",
|
| 116 |
+
)
|
| 117 |
with gr.Row():
|
| 118 |
+
sql_out = gr.Code(label="Generated SQL", language="sql")
|
| 119 |
+
res_out = gr.Code(label="Query result (JSON)")
|
| 120 |
trace_out = gr.Textbox(label="Trace", lines=6)
|
|
|
|
| 121 |
run_btn = gr.Button("Run")
|
| 122 |
+
run_btn.click(run_pipeline, query_in, [sql_out, res_out, trace_out])
|
|
|
|
| 123 |
|
| 124 |
if __name__ == "__main__":
|
| 125 |
demo.launch()
|