sagar312 commited on
Commit
13a76e8
·
verified ·
1 Parent(s): d29c75e

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +394 -0
  2. requirements.txt +30 -0
app.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Text-to-SQL demo — Hugging Face Spaces (Gradio)
3
+
4
+ Stopgap public deployment using a pretrained community model
5
+ (Ellbendls/Qwen-2.5-3b-Text_to_SQL) while the project's own fine-tuned
6
+ adapter continues training separately on Kaggle. Swap MODEL_ID below (and
7
+ add PEFT adapter loading, see the main project's generation/sql_generator.py)
8
+ once the custom adapter is ready and validated.
9
+
10
+ Reuses this project's schema retrieval (hybrid dense+BM25, in-memory
11
+ Qdrant), AST validation (read-only guardrails, bounded LIMIT), and safe
12
+ execution (read-only transaction, statement timeout) logic — these are the
13
+ same tested patterns from the main project and the Kaggle test notebook,
14
+ not reimplemented from scratch.
15
+
16
+ Required Space secrets (Settings -> Repository secrets):
17
+ DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD
18
+ """
19
+ import os
20
+ import re
21
+ import uuid
22
+
23
+ import gradio as gr
24
+ import pandas as pd
25
+ import spaces
26
+ import torch
27
+ from transformers import AutoModelForCausalLM, AutoTokenizer
28
+ from sqlalchemy import create_engine, inspect, text as sqltext
29
+ from qdrant_client import QdrantClient
30
+ from qdrant_client.models import Distance, VectorParams, PointStruct
31
+ from sentence_transformers import SentenceTransformer
32
+ from rank_bm25 import BM25Okapi
33
+ import sqlglot
34
+ from sqlglot import exp
35
+
36
+ MODEL_ID = "Ellbendls/Qwen-2.5-3b-Text_to_SQL"
37
+
38
+ DB_HOST = os.environ["DB_HOST"]
39
+ DB_PORT = os.environ.get("DB_PORT", "5432")
40
+ DB_NAME = os.environ.get("DB_NAME", "postgres")
41
+ DB_USER = os.environ["DB_USER"]
42
+ DB_PASSWORD = os.environ["DB_PASSWORD"]
43
+
44
+ DEFAULT_ROW_LIMIT = 100
45
+ STATEMENT_TIMEOUT_MS = 5000
46
+ MAX_RETRIES = 3
47
+
48
+
49
+ # ============================================================
50
+ # Schema introspection (same exclusion list as the main project's
51
+ # schema/introspector.py — Supabase's internal schemas are platform
52
+ # plumbing, never the user's actual business tables)
53
+ # ============================================================
54
+ _EXCLUDED_SCHEMAS = {
55
+ "information_schema", "pg_catalog", "pg_toast", "mysql", "sys", "performance_schema",
56
+ "auth", "storage", "realtime", "vault", "extensions",
57
+ "graphql", "graphql_public", "pgbouncer", "pgsodium", "pgsodium_masks",
58
+ "supabase_functions", "supabase_migrations", "net", "cron",
59
+ }
60
+
61
+
62
+ class TableSchema:
63
+ def __init__(self, name, schema, columns):
64
+ self.name = name
65
+ self.schema = schema
66
+ self.columns = columns # list of (name, type, is_primary_key)
67
+
68
+ def to_ddl(self):
69
+ lines = [f"CREATE TABLE {self.schema}.{self.name} ("]
70
+ col_lines = []
71
+ for col_name, col_type, is_pk in self.columns:
72
+ pk = " PRIMARY KEY" if is_pk else ""
73
+ col_lines.append(f" {col_name} {col_type}{pk}")
74
+ lines.append(",\n".join(col_lines))
75
+ lines.append(");")
76
+ return "\n".join(lines)
77
+
78
+ def to_retrieval_document(self):
79
+ parts = [f"{self.schema}.{self.name}"] + [c[0] for c in self.columns]
80
+ return " | ".join(parts)
81
+
82
+
83
+ def extract_schema(engine):
84
+ inspector = inspect(engine)
85
+ tables = []
86
+ for schema_name in inspector.get_schema_names():
87
+ if schema_name in _EXCLUDED_SCHEMAS:
88
+ continue
89
+ for table_name in inspector.get_table_names(schema=schema_name):
90
+ try:
91
+ pk_cols = set(
92
+ inspector.get_pk_constraint(table_name, schema=schema_name).get("constrained_columns", [])
93
+ )
94
+ columns = [
95
+ (col["name"], str(col["type"]), col["name"] in pk_cols)
96
+ for col in inspector.get_columns(table_name, schema=schema_name)
97
+ ]
98
+ tables.append(TableSchema(name=table_name, schema=schema_name, columns=columns))
99
+ except Exception:
100
+ continue
101
+ return tables
102
+
103
+
104
+ # ============================================================
105
+ # Hybrid retrieval — embedded Qdrant (no separate server needed
106
+ # for a Space), dense (bge-small) + BM25, fused
107
+ # ============================================================
108
+ class SchemaRetriever:
109
+ def __init__(self, top_k_final=5):
110
+ self.client = QdrantClient(":memory:")
111
+ # CPU, not GPU -- this is a tiny 133M-param embedding model; keeping
112
+ # it off any accelerator leaves all compute for the actual LLM.
113
+ self.embedder = SentenceTransformer("BAAI/bge-small-en-v1.5", device="cpu")
114
+ self.collection = "schema_metadata"
115
+ self.top_k_final = top_k_final
116
+ self._tables_by_name = {}
117
+ self._bm25 = None
118
+ self._bm25_order = []
119
+
120
+ def index(self, tables):
121
+ self._tables_by_name = {f"{t.schema}.{t.name}": t for t in tables}
122
+ docs = [t.to_retrieval_document() for t in tables]
123
+ vectors = self.embedder.encode(docs, normalize_embeddings=True)
124
+
125
+ if self.client.collection_exists(self.collection):
126
+ self.client.delete_collection(self.collection)
127
+ self.client.create_collection(
128
+ collection_name=self.collection,
129
+ vectors_config=VectorParams(size=vectors.shape[1], distance=Distance.COSINE),
130
+ )
131
+ points = [
132
+ PointStruct(id=str(uuid.uuid4()), vector=vec.tolist(), payload={"table_name": f"{t.schema}.{t.name}"})
133
+ for t, vec in zip(tables, vectors)
134
+ ]
135
+ self.client.upsert(collection_name=self.collection, points=points)
136
+
137
+ tokenized = [d.lower().split() for d in docs]
138
+ self._bm25 = BM25Okapi(tokenized)
139
+ self._bm25_order = [f"{t.schema}.{t.name}" for t in tables]
140
+
141
+ def build_schema_context(self, query):
142
+ query_vec = self.embedder.encode(query, normalize_embeddings=True)
143
+ dense_hits = self.client.query_points(collection_name=self.collection, query=query_vec.tolist(), limit=8).points
144
+ dense_scores = {h.payload["table_name"]: h.score for h in dense_hits}
145
+
146
+ bm25_raw = self._bm25.get_scores(query.lower().split())
147
+ max_bm25 = max(bm25_raw) if len(bm25_raw) and max(bm25_raw) > 0 else 1.0
148
+ bm25_scores = {name: s / max_bm25 for name, s in zip(self._bm25_order, bm25_raw)}
149
+
150
+ all_names = set(dense_scores) | set(bm25_scores)
151
+ fused = sorted(
152
+ all_names,
153
+ key=lambda n: 0.6 * dense_scores.get(n, 0) + 0.4 * bm25_scores.get(n, 0),
154
+ reverse=True,
155
+ )[: self.top_k_final]
156
+ tables = [self._tables_by_name[n] for n in fused if n in self._tables_by_name]
157
+ return "\n\n".join(t.to_ddl() for t in tables)
158
+
159
+
160
+ # ============================================================
161
+ # AST validator — identical guardrails to the main project's
162
+ # validation/validator.py (verified there against 7 test cases:
163
+ # injection attempts, hallucinated tables, the aggregate/LIMIT
164
+ # edge case, etc.)
165
+ # ============================================================
166
+ _FORBIDDEN = (exp.Drop, exp.Delete, exp.Insert, exp.Update, exp.Alter, exp.Create, exp.TruncateTable, exp.Grant)
167
+
168
+
169
+ def _has_aggregate_without_group_by(select):
170
+ has_agg = any(select.find(cls) for cls in (exp.Sum, exp.Count, exp.Avg, exp.Max, exp.Min))
171
+ return has_agg and select.args.get("group") is None
172
+
173
+
174
+ def _known_tables(schema_context):
175
+ tables = set()
176
+ for line in schema_context.splitlines():
177
+ s = line.strip()
178
+ if s.upper().startswith("CREATE TABLE"):
179
+ name = s.split()[2].rstrip("(").strip()
180
+ tables.add(name.split(".")[-1].lower())
181
+ return tables
182
+
183
+
184
+ def validate_and_prepare(raw_sql, schema_context, default_limit=DEFAULT_ROW_LIMIT):
185
+ try:
186
+ statements = [s for s in sqlglot.parse(raw_sql, read="postgres") if s is not None]
187
+ except Exception as e:
188
+ return None, f"Parse error: {e}"
189
+ if len(statements) != 1:
190
+ return None, f"Expected one statement, found {len(statements)}."
191
+ tree = statements[0]
192
+ for forbidden in _FORBIDDEN:
193
+ if tree.find(forbidden):
194
+ return None, f"Rejected: forbidden operation ({forbidden.__name__})."
195
+ root_select = tree if isinstance(tree, exp.Select) else tree.find(exp.Select)
196
+ if root_select is None:
197
+ return None, "Rejected: no SELECT found."
198
+ known_tables = _known_tables(schema_context)
199
+ referenced = {t.name.lower() for t in tree.find_all(exp.Table)}
200
+ unknown = referenced - known_tables
201
+ if unknown:
202
+ return None, f"Rejected: references unknown table(s): {unknown}"
203
+ if isinstance(tree, exp.Select):
204
+ if tree.args.get("limit") is None and not _has_aggregate_without_group_by(tree):
205
+ tree.set("limit", exp.Limit(expression=exp.Literal.number(default_limit)))
206
+ try:
207
+ return tree.sql(dialect="postgres"), None
208
+ except Exception as e:
209
+ return None, f"Render error: {e}"
210
+
211
+
212
+ # ============================================================
213
+ # Safe executor — read-only transaction, statement timeout,
214
+ # always rolled back (same pattern as execution/executor.py)
215
+ # ============================================================
216
+ def execute_sql(engine, sql, timeout_ms=STATEMENT_TIMEOUT_MS):
217
+ try:
218
+ with engine.connect() as conn:
219
+ conn.execute(sqltext(f"SET statement_timeout = {timeout_ms}"))
220
+ conn.execute(sqltext("SET TRANSACTION READ ONLY"))
221
+ try:
222
+ result = conn.execute(sqltext(sql))
223
+ columns = list(result.keys())
224
+ rows = [dict(zip(columns, row)) for row in result.fetchall()]
225
+ return True, rows, columns, None
226
+ finally:
227
+ conn.rollback()
228
+ except Exception as e:
229
+ return False, [], [], str(e)
230
+
231
+
232
+ # ============================================================
233
+ # Model loading — ZeroGPU (Spaces free tier). ZeroGPU dynamically grants
234
+ # GPU access only inside functions decorated with @spaces.GPU; outside
235
+ # those functions (including at this module-level load time) no GPU is
236
+ # visible, so the model is loaded in its default location (CPU) here and
237
+ # explicitly moved to CUDA only inside the decorated inference call below.
238
+ # ============================================================
239
+ print(f"Loading {MODEL_ID} ...")
240
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
241
+ if tokenizer.pad_token is None:
242
+ tokenizer.pad_token = tokenizer.eos_token
243
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.bfloat16)
244
+ model.eval()
245
+ print("Model loaded.")
246
+
247
+
248
+ @spaces.GPU(duration=60)
249
+ def _generate_on_gpu(prompt: str) -> str:
250
+ # Runs only while ZeroGPU has actually granted this call a GPU. Moving
251
+ # the model to CUDA on every call (rather than once at startup) is the
252
+ # expected ZeroGPU pattern -- GPU access is per-call, not persistent,
253
+ # since the same physical GPU is dynamically shared across many
254
+ # different Spaces' requests.
255
+ model.to("cuda")
256
+ inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
257
+ with torch.no_grad():
258
+ output_ids = model.generate(
259
+ **inputs, max_new_tokens=256, do_sample=False, pad_token_id=tokenizer.eos_token_id
260
+ )
261
+ return tokenizer.decode(output_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
262
+
263
+
264
+ def generate_sql(question, schema_context, error_trace=None, previous_sql=None):
265
+ # Prompt shape follows the "Context / Question / SQL Query" convention
266
+ # common to Gretel-style synthetic text-to-SQL datasets (what this
267
+ # specific model was fine-tuned on). The model card doesn't document an
268
+ # exact retry-prompt format, so retry feedback is appended in plain
269
+ # language rather than a structure this model is confirmed to have
270
+ # seen during training -- a known limitation of using a pretrained
271
+ # stopgap model instead of one trained on this project's own data.
272
+ prompt = f"Context:\n{schema_context}\n\nQuestion: {question}\n\n"
273
+ if error_trace and previous_sql:
274
+ prompt += (
275
+ f"Your previous attempt failed with this error: {error_trace}\n"
276
+ f"Previous SQL: {previous_sql}\n"
277
+ "Fix the query.\n\n"
278
+ )
279
+ prompt += "SQL Query:\n"
280
+
281
+ raw = _generate_on_gpu(prompt)
282
+ text = raw.strip()
283
+ fence = re.search(r"```(?:sql)?\s*(.*?)```", text, re.DOTALL | re.IGNORECASE)
284
+ if fence:
285
+ text = fence.group(1).strip()
286
+ if ";" in text:
287
+ text = text[: text.find(";") + 1]
288
+ return text.strip()
289
+
290
+
291
+ # ============================================================
292
+ # Startup: connect + index schema once (not per-request)
293
+ # ============================================================
294
+ print(f"Connecting to {DB_HOST} ...")
295
+ _db_uri = f"postgresql+psycopg2://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
296
+ db_engine = create_engine(_db_uri, pool_pre_ping=True)
297
+ _tables = extract_schema(db_engine)
298
+ print(f"Found {len(_tables)} table(s): {[t.name for t in _tables]}")
299
+
300
+ retriever = SchemaRetriever()
301
+ retriever.index(_tables)
302
+ print("Schema indexed.")
303
+
304
+
305
+ # ============================================================
306
+ # Self-healing pipeline
307
+ # ============================================================
308
+ def answer_question(question):
309
+ if not question or not question.strip():
310
+ return "", "Please enter a question.", None
311
+
312
+ schema_context = retriever.build_schema_context(question)
313
+ error_trace, previous_sql = None, None
314
+ final_sql, success, rows, columns = None, False, [], []
315
+ raw_sql = None
316
+ log_lines = []
317
+
318
+ for attempt in range(MAX_RETRIES + 1):
319
+ raw_sql = generate_sql(question, schema_context, error_trace, previous_sql)
320
+ validated_sql, validation_error = validate_and_prepare(raw_sql, schema_context)
321
+
322
+ if validated_sql is None:
323
+ error_trace = validation_error
324
+ previous_sql = raw_sql
325
+ log_lines.append(f"Attempt {attempt + 1}: validation failed — {validation_error}")
326
+ continue
327
+
328
+ success, rows, columns, exec_error = execute_sql(db_engine, validated_sql)
329
+ if success:
330
+ final_sql = validated_sql
331
+ log_lines.append(f"Attempt {attempt + 1}: succeeded.")
332
+ break
333
+ error_trace = exec_error
334
+ previous_sql = validated_sql
335
+ log_lines.append(f"Attempt {attempt + 1}: execution failed — {exec_error}")
336
+
337
+ sql_display = final_sql or raw_sql or "(no SQL generated)"
338
+ df = pd.DataFrame(rows, columns=columns) if success and rows else None
339
+ status = (
340
+ f"✅ Success after {attempt + 1} attempt(s)."
341
+ if success
342
+ else f"❌ Failed after {MAX_RETRIES + 1} attempts. Last error: {error_trace}"
343
+ )
344
+ return sql_display, status, df
345
+
346
+
347
+ # ============================================================
348
+ # Gradio UI
349
+ # ============================================================
350
+ with gr.Blocks(title="Text-to-SQL Demo") as demo:
351
+ gr.Markdown(
352
+ "# Text-to-SQL Demo\n"
353
+ "Ask a question in plain English about the sample e-commerce database "
354
+ "(customers, products, orders, order_items) and get back real SQL and results.\n\n"
355
+ "**Note:** this demo currently runs a pretrained community model "
356
+ "(`Ellbendls/Qwen-2.5-3b-Text_to_SQL`) as a stopgap while a custom "
357
+ "fine-tuned model finishes training separately — expect imperfect "
358
+ "results. Safety guardrails (read-only execution, schema-validated "
359
+ "queries, bounded result size) are fully active regardless of "
360
+ "model quality; nothing but SELECT ever reaches the database."
361
+ )
362
+ question_input = gr.Textbox(
363
+ label="Your question", placeholder="e.g. What were our top 3 customer segments by revenue?"
364
+ )
365
+ submit_btn = gr.Button("Ask", variant="primary")
366
+ sql_output = gr.Code(label="Generated SQL", language="sql")
367
+ status_output = gr.Markdown()
368
+ results_output = gr.Dataframe(label="Results")
369
+
370
+ submit_btn.click(fn=answer_question, inputs=question_input, outputs=[sql_output, status_output, results_output])
371
+ question_input.submit(fn=answer_question, inputs=question_input, outputs=[sql_output, status_output, results_output])
372
+
373
+ gr.Examples(
374
+ examples=[
375
+ "What were our top 3 customer segments by revenue?",
376
+ "Which products have the highest profit margin?",
377
+ "How many orders were refunded?",
378
+ ],
379
+ inputs=question_input,
380
+ )
381
+
382
+ if __name__ == "__main__":
383
+ # server_name="0.0.0.0" is standard practice for HF Spaces deployments
384
+ # (binds to all interfaces so the Spaces proxy can reach it) -- gradio
385
+ # usually auto-detects the Spaces environment via env vars and does this
386
+ # itself, but setting it explicitly costs nothing and removes one more
387
+ # variable if the launch-time self-test misbehaves again.
388
+ # ssr_mode=False: gradio 5's server-side rendering is explicitly marked
389
+ # experimental, and its Node.js subprocess is a known, documented cause
390
+ # of silent crashes right after a clean "Running on local URL..."
391
+ # startup message on Spaces (confirmed by multiple reports on HF's own
392
+ # forums with this exact "Stopping Node.js server..." signature).
393
+ # Disabling it falls back to standard client-side rendering.
394
+ demo.launch(server_name="0.0.0.0", ssr_mode=False)
requirements.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gradio itself is NOT listed here -- for a Gradio-SDK Space, Hugging Face
2
+ # installs gradio at the version set by `sdk_version` in README.md, via its
3
+ # own build wrapper. Listing a different/looser gradio constraint here
4
+ # created a losing conflict with that wrapper's own pinned install command
5
+ # (confirmed in the build log: "gradio[oauth]==4.44.0" was being installed
6
+ # by HF's own wrapper regardless of what we put in this file). gradio 5.10+
7
+ # (set in README.md's sdk_version) also removed the HfFolder dependency
8
+ # that caused a "cannot import name 'HfFolder'" crash on gradio 4.44 with
9
+ # any modern huggingface_hub -- so the huggingface_hub and jinja2 pins that
10
+ # were needed to work around that on 4.44 are no longer needed either.
11
+ #
12
+ # spaces: required for @spaces.GPU -- the free tier for Gradio SDK Spaces
13
+ # is ZeroGPU-only (CPU basic requires a PRO subscription), and ZeroGPU
14
+ # requires at least one function decorated with @spaces.GPU or the Space
15
+ # fails at startup with "No @spaces.GPU function detected".
16
+ spaces>=0.30.0
17
+ transformers>=4.46.0
18
+ # accelerate is not strictly required now that model loading no longer
19
+ # uses device_map (ZeroGPU moves the model to CUDA explicitly inside the
20
+ # @spaces.GPU-decorated call instead) -- left in since other libraries in
21
+ # this stack may still expect it available.
22
+ accelerate>=0.33.0
23
+ torch>=2.3.0
24
+ sqlglot>=25.0.0
25
+ sqlalchemy>=2.0.0
26
+ psycopg2-binary>=2.9.9
27
+ qdrant-client>=1.9.0
28
+ sentence-transformers>=3.0.0
29
+ rank-bm25>=0.2.2
30
+ pandas>=2.0.0