Spaces:
Build error
Build error
Upload 3 files
Browse files
app.py
CHANGED
|
@@ -1,77 +1,133 @@
|
|
| 1 |
-
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
SCHEMA_FILE = "schema.sql"
|
| 6 |
-
MODEL_ID
|
| 7 |
-
HF_TOKEN
|
| 8 |
-
API_URL
|
| 9 |
-
HEADERS
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
def create_db_if_needed():
|
| 12 |
-
if
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
prompt = textwrap.dedent(f"""
|
| 20 |
-
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
|
| 29 |
-
|
| 30 |
""")
|
| 31 |
-
payload = {
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
try:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
return "Error: " + str(response.json())
|
| 38 |
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
trace = []
|
| 41 |
-
|
| 42 |
|
|
|
|
| 43 |
create_db_if_needed()
|
| 44 |
|
|
|
|
| 45 |
with open(SCHEMA_FILE) as f:
|
| 46 |
schema_ddl = f.read()
|
| 47 |
-
trace.append(("Schema
|
| 48 |
|
|
|
|
| 49 |
sql_query = nlp_to_sql(nl_query, schema_ddl)
|
| 50 |
-
trace.append(("LLM
|
| 51 |
|
|
|
|
| 52 |
try:
|
| 53 |
with sqlite3.connect(DB_PATH) as conn:
|
| 54 |
-
|
| 55 |
-
rows =
|
| 56 |
-
|
| 57 |
-
result = {"columns":
|
| 58 |
-
trace.append(("
|
| 59 |
except Exception as e:
|
| 60 |
result = {"error": str(e)}
|
| 61 |
-
trace.append(("Execution
|
| 62 |
|
| 63 |
-
trace.append(("Total
|
| 64 |
-
return sql_query, json.dumps(result, indent=2), "\n".join(f"{step}: {msg}" for step, msg in trace)
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
with gr.Row():
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
run_btn
|
|
|
|
|
|
|
| 75 |
|
| 76 |
if __name__ == "__main__":
|
| 77 |
demo.launch()
|
|
|
|
| 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 |
+
# Config
|
| 11 |
+
# -----------------------------
|
| 12 |
+
DB_PATH = "company.db"
|
| 13 |
SCHEMA_FILE = "schema.sql"
|
| 14 |
+
MODEL_ID = "defog/sqlcoder-7b-2" # swap to another HF model if desired
|
| 15 |
+
HF_TOKEN = os.getenv("HF_TOKEN") # set in Space > Settings > Secrets
|
| 16 |
+
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
|
| 17 |
+
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 18 |
|
| 19 |
+
# -----------------------------
|
| 20 |
+
# Helper: Build DB once
|
| 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 not found in Space.")
|
| 27 |
+
with open(SCHEMA_FILE) as f:
|
| 28 |
+
schema_sql = f.read()
|
| 29 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 30 |
+
conn.executescript(schema_sql)
|
| 31 |
|
| 32 |
+
# -----------------------------
|
| 33 |
+
# Helper: Call HF Inference API
|
| 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.
|
| 39 |
|
| 40 |
+
### Schema
|
| 41 |
+
{schema_ddl}
|
| 42 |
|
| 43 |
+
### Question
|
| 44 |
+
{nl_query}
|
| 45 |
|
| 46 |
+
### SQL
|
| 47 |
""")
|
| 48 |
+
payload = {
|
| 49 |
+
"inputs": prompt,
|
| 50 |
+
"parameters": {"max_new_tokens": 256}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
resp = requests.post(API_URL, headers=HEADERS, json=payload, timeout=60)
|
| 55 |
+
except Exception as e:
|
| 56 |
+
return f"β Exception contacting API: {e}"
|
| 57 |
+
|
| 58 |
+
if resp.status_code != 200:
|
| 59 |
+
return f"β API error {resp.status_code}: {resp.text}"
|
| 60 |
+
|
| 61 |
try:
|
| 62 |
+
output = resp.json()
|
| 63 |
+
except ValueError:
|
| 64 |
+
return "β Non-JSON response from API."
|
|
|
|
| 65 |
|
| 66 |
+
if not isinstance(output, list) or not output:
|
| 67 |
+
return "β Model returned empty output."
|
| 68 |
+
|
| 69 |
+
generated = output[0].get("generated_text", "")
|
| 70 |
+
if "### SQL" in generated:
|
| 71 |
+
sql = generated.split("### SQL")[-1].strip()
|
| 72 |
+
else:
|
| 73 |
+
sql = generated.strip()
|
| 74 |
+
|
| 75 |
+
return sql or "β Empty SQL string returned."
|
| 76 |
+
|
| 77 |
+
# -----------------------------
|
| 78 |
+
# Pipeline: NL β SQL β Execute
|
| 79 |
+
# -----------------------------
|
| 80 |
+
def run_pipeline(nl_query: str):
|
| 81 |
trace = []
|
| 82 |
+
t0 = time.time()
|
| 83 |
|
| 84 |
+
# build db if needed
|
| 85 |
create_db_if_needed()
|
| 86 |
|
| 87 |
+
# load schema for prompt
|
| 88 |
with open(SCHEMA_FILE) as f:
|
| 89 |
schema_ddl = f.read()
|
| 90 |
+
trace.append(("Schema loaded", f"{len(schema_ddl.splitlines())} lines"))
|
| 91 |
|
| 92 |
+
# convert NL β SQL
|
| 93 |
sql_query = nlp_to_sql(nl_query, schema_ddl)
|
| 94 |
+
trace.append(("LLM output", sql_query))
|
| 95 |
|
| 96 |
+
# execute SQL
|
| 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(("Execution", f"{len(rows)} rows"))
|
| 104 |
except Exception as e:
|
| 105 |
result = {"error": str(e)}
|
| 106 |
+
trace.append(("Execution error", str(e)))
|
| 107 |
|
| 108 |
+
trace.append(("Total time", f"{time.time() - t0:.2f}s"))
|
|
|
|
| 109 |
|
| 110 |
+
# stringify outputs for UI
|
| 111 |
+
result_json = json.dumps(result, indent=2, ensure_ascii=False)
|
| 112 |
+
trace_log = "\n".join(f"{s}: {m}" for s, m in trace)
|
| 113 |
+
|
| 114 |
+
return sql_query, result_json, trace_log
|
| 115 |
+
|
| 116 |
+
# -----------------------------
|
| 117 |
+
# Gradio UI
|
| 118 |
+
# -----------------------------
|
| 119 |
+
with gr.Blocks(title="NLP β SQL (SQLite, HF Hub)") as demo:
|
| 120 |
+
gr.Markdown("## NLP β SQL Query Demo (auto-build SQLite, no terminal required)")
|
| 121 |
+
nl_in = gr.Textbox(label="Natural-language question",
|
| 122 |
+
placeholder="e.g. List all employees in Engineering hired after 2021")
|
| 123 |
with gr.Row():
|
| 124 |
+
sql_out = gr.Code(label="Generated SQL", language="sql")
|
| 125 |
+
result_out = gr.Code(label="Query result (JSON)")
|
| 126 |
+
trace_out = gr.Textbox(label="Trace", lines=6)
|
| 127 |
+
|
| 128 |
+
run_btn = gr.Button("Run")
|
| 129 |
+
run_btn.click(fn=run_pipeline, inputs=nl_in,
|
| 130 |
+
outputs=[sql_out, result_out, trace_out])
|
| 131 |
|
| 132 |
if __name__ == "__main__":
|
| 133 |
demo.launch()
|