Spaces:
Running
Running
App creada
Browse files
app.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from deep_translator import GoogleTranslator
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
from transformers import TapexTokenizer, BartForConditionalGeneration
|
| 7 |
+
import pandas as pd, torch, os
|
| 8 |
+
|
| 9 |
+
# === Config ===
|
| 10 |
+
HF_MODEL_ID = os.getenv("HF_MODEL_ID", "stvnnnnnn/tapex-wikisql-best")
|
| 11 |
+
TABLE_SPLIT = os.getenv("TABLE_SPLIT", "validation")
|
| 12 |
+
TABLE_INDEX = int(os.getenv("TABLE_INDEX", "10"))
|
| 13 |
+
MAX_ROWS = int(os.getenv("MAX_ROWS", "12"))
|
| 14 |
+
|
| 15 |
+
torch.set_num_threads(1)
|
| 16 |
+
|
| 17 |
+
app = FastAPI(title="NL→SQL – TAPEX + WikiSQL (HF Space)")
|
| 18 |
+
|
| 19 |
+
# CORS: permite que Vercel (o cualquier origen) consuma la API
|
| 20 |
+
app.add_middleware(
|
| 21 |
+
CORSMiddleware,
|
| 22 |
+
allow_origins=["*"], allow_credentials=False,
|
| 23 |
+
allow_methods=["*"], allow_headers=["*"],
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# Carga modelo/tokenizer con bajo pico de RAM (CPU)
|
| 27 |
+
tok = TapexTokenizer.from_pretrained(HF_MODEL_ID)
|
| 28 |
+
model = BartForConditionalGeneration.from_pretrained(
|
| 29 |
+
HF_MODEL_ID, low_cpu_mem_usage=True
|
| 30 |
+
).to("cpu")
|
| 31 |
+
|
| 32 |
+
class NLQuery(BaseModel):
|
| 33 |
+
nl_query: str
|
| 34 |
+
|
| 35 |
+
def get_example(split, index):
|
| 36 |
+
# streaming para no cargar todo WikiSQL en RAM
|
| 37 |
+
ds = load_dataset("Salesforce/wikisql", split=split, streaming=True)
|
| 38 |
+
for i, ex in enumerate(ds):
|
| 39 |
+
if i == index:
|
| 40 |
+
return ex
|
| 41 |
+
raise IndexError("Index fuera de rango")
|
| 42 |
+
|
| 43 |
+
def load_table(split=TABLE_SPLIT, index=TABLE_INDEX, max_rows=MAX_ROWS):
|
| 44 |
+
ex = get_example(split, index)
|
| 45 |
+
header = [str(h) for h in ex["table"]["header"]]
|
| 46 |
+
rows = ex["table"]["rows"][:max_rows]
|
| 47 |
+
return pd.DataFrame(rows, columns=header)
|
| 48 |
+
|
| 49 |
+
@app.get("/api/health")
|
| 50 |
+
def health():
|
| 51 |
+
return {"ok": True, "model": HF_MODEL_ID, "split": TABLE_SPLIT, "index": TABLE_INDEX}
|
| 52 |
+
|
| 53 |
+
@app.get("/api/preview")
|
| 54 |
+
def preview():
|
| 55 |
+
df = load_table()
|
| 56 |
+
return {"columns": df.columns.tolist(), "rows": df.head(8).to_dict(orient="records")}
|
| 57 |
+
|
| 58 |
+
@app.post("/api/nl2sql")
|
| 59 |
+
def nl2sql(q: NLQuery):
|
| 60 |
+
try:
|
| 61 |
+
text = (q.nl_query or "").strip()
|
| 62 |
+
if not text:
|
| 63 |
+
raise ValueError("Consulta vacía.")
|
| 64 |
+
|
| 65 |
+
is_ascii = all(ord(c) < 128 for c in text)
|
| 66 |
+
query_en = text if is_ascii else GoogleTranslator(source="auto", target="en").translate(text)
|
| 67 |
+
|
| 68 |
+
df = load_table()
|
| 69 |
+
enc = tok(table=df, query=query_en, return_tensors="pt", truncation=True)
|
| 70 |
+
out = model.generate(**enc, max_length=160, num_beams=1)
|
| 71 |
+
sql = tok.batch_decode(out, skip_special_tokens=True)[0]
|
| 72 |
+
|
| 73 |
+
return {"consulta_original": text, "consulta_traducida": query_en, "sql_generado": sql}
|
| 74 |
+
except Exception as e:
|
| 75 |
+
raise HTTPException(status_code=500, detail=str(e))
|