stvnnnnnn commited on
Commit
349e4b9
·
verified ·
1 Parent(s): c335b18

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -79
app.py CHANGED
@@ -1,113 +1,154 @@
1
- # app.py — NL→SQL (TAPEX + WikiSQL) backend (solo API)
2
-
3
  from fastapi import FastAPI, HTTPException
4
  from fastapi.middleware.cors import CORSMiddleware
5
- from fastapi.responses import JSONResponse
6
  from pydantic import BaseModel
7
-
8
- import os
9
- import torch
10
- import pandas as pd
11
  from functools import lru_cache
12
-
13
- from datasets import load_dataset
14
- from deep_translator import GoogleTranslator
15
  from transformers import TapexTokenizer, BartForConditionalGeneration
 
 
16
 
17
- # ------------ Config ------------
 
 
18
  HF_MODEL_ID = os.getenv("HF_MODEL_ID", "stvnnnnnn/tapex-wikisql-best")
19
- TABLE_SPLIT = os.getenv("TABLE_SPLIT", "validation")
20
- TABLE_INDEX = int(os.getenv("TABLE_INDEX", "10"))
21
- MAX_ROWS = int(os.getenv("MAX_ROWS", "100"))
22
-
23
- # Caché HF escribible en Spaces
24
- os.environ["HF_HOME"] = "/app/.cache/huggingface"
25
- os.makedirs(os.environ["HF_HOME"], exist_ok=True)
26
-
27
- # ------------ App & CORS ------------
28
  app = FastAPI(title="NL→SQL – TAPEX + WikiSQL (API)")
29
  app.add_middleware(
30
  CORSMiddleware,
31
- allow_origins=["*"], # cámbialo al dominio de Vercel cuando lo tengas
32
- allow_credentials=True,
33
- allow_methods=["*"],
34
- allow_headers=["*"],
35
  )
36
 
37
- # ------------ Carga perezosa ------------
38
- @lru_cache(maxsize=1)
39
- def get_model_and_tokenizer():
40
- tok = TapexTokenizer.from_pretrained(HF_MODEL_ID)
41
- model = BartForConditionalGeneration.from_pretrained(HF_MODEL_ID)
42
- model.eval()
43
- return tok, model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  @lru_cache(maxsize=32)
46
- def get_table(split: str, index: int, max_rows: int) -> pd.DataFrame:
47
  """
48
- Carga tabla de WikiSQL usando archivos parquet (sin script local).
49
- Compatible con Spaces free (CPU).
 
 
50
  """
51
- import pyarrow.parquet as pq
52
- import tempfile
53
- from huggingface_hub import hf_hub_download
54
-
55
- # Descarga directa del dataset en parquet
56
- parquet_path = hf_hub_download(
57
- repo_id="Salesforce/wikisql",
58
- filename=f"data/{split}-00000-of-00001.parquet",
59
- repo_type="dataset"
60
- )
61
-
62
- # Lee parquet con pyarrow/pandas
63
- table = pq.read_table(parquet_path)
64
- df_full = table.to_pandas()
65
-
66
- # Cada registro tiene una columna "table" con estructura compleja → parseamos
67
- example = df_full.iloc[index]
68
- header = [str(h) for h in example["table"]["header"]]
69
- rows = example["table"]["rows"][:max_rows]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  df = pd.DataFrame(rows, columns=header)
71
  df.columns = [str(c) for c in df.columns]
72
  return df
73
 
74
- # ------------ Schemas ------------
75
- class NLQuery(BaseModel):
76
- nl_query: str
77
-
78
- # ------------ Endpoints ------------
79
  @app.get("/api/health")
80
  def health():
81
- return {"ok": True, "model": HF_MODEL_ID, "split": TABLE_SPLIT, "index": TABLE_INDEX}
82
 
83
  @app.get("/api/preview")
84
  def preview():
85
  try:
86
- df = get_table(TABLE_SPLIT, TABLE_INDEX, MAX_ROWS)
87
- return {"columns": list(df.columns), "rows": df.head(8).to_dict(orient="records")}
88
  except Exception as e:
89
- return JSONResponse(status_code=500, content={"error": str(e)})
90
 
91
  @app.post("/api/nl2sql")
92
  def nl2sql(q: NLQuery):
93
- nl = (q.nl_query or "").strip()
94
- if not nl:
95
- raise HTTPException(status_code=400, detail="Consulta vacía.")
96
-
97
- # Traducción ES→EN si no-ASCII
98
- try:
99
- is_ascii = all(ord(c) < 128 for c in nl)
100
- nl_en = nl if is_ascii else GoogleTranslator(source="auto", target="en").translate(nl)
101
- except Exception:
102
- nl_en = nl
103
-
104
  try:
105
- df = get_table(TABLE_SPLIT, TABLE_INDEX, MAX_ROWS)
106
- tok, model = get_model_and_tokenizer()
107
- enc = tok(table=df, query=nl_en, return_tensors="pt", truncation=True, max_length=512)
108
- with torch.inference_mode():
109
- out = model.generate(**enc, max_length=160, num_beams=1)
 
 
 
 
 
 
 
 
110
  sql = tok.batch_decode(out, skip_special_tokens=True)[0]
111
- return {"consulta_original": nl, "consulta_traducida": nl_en, "sql_generado": sql}
 
 
 
 
 
112
  except Exception as e:
113
  raise HTTPException(status_code=500, detail=str(e))
 
 
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
 
3
  from pydantic import BaseModel
 
 
 
 
4
  from functools import lru_cache
5
+ from huggingface_hub import hf_hub_download
 
 
6
  from transformers import TapexTokenizer, BartForConditionalGeneration
7
+ from deep_translator import GoogleTranslator
8
+ import os, json, pandas as pd, torch
9
 
10
+ # ------------------------
11
+ # Config
12
+ # ------------------------
13
  HF_MODEL_ID = os.getenv("HF_MODEL_ID", "stvnnnnnn/tapex-wikisql-best")
14
+ WIKISQL_REPO = os.getenv("WIKISQL_REPO", "Salesforce/wikisql") # dataset oficial
15
+ SPLIT = os.getenv("TABLE_SPLIT", "validation") # "validation" == dev en WikiSQL
16
+ INDEX = int(os.getenv("TABLE_INDEX", "10"))
17
+ MAX_ROWS = int(os.getenv("MAX_ROWS", "12"))
18
+
19
+ # ------------------------
20
+ # App
21
+ # ------------------------
 
22
  app = FastAPI(title="NL→SQL – TAPEX + WikiSQL (API)")
23
  app.add_middleware(
24
  CORSMiddleware,
25
+ allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], allow_credentials=True,
 
 
 
26
  )
27
 
28
+ class NLQuery(BaseModel):
29
+ nl_query: str
30
+
31
+ # ------------------------
32
+ # Modelo
33
+ # ------------------------
34
+ tok = TapexTokenizer.from_pretrained(HF_MODEL_ID)
35
+ model = BartForConditionalGeneration.from_pretrained(HF_MODEL_ID)
36
+ if torch.cuda.is_available():
37
+ model = model.to("cuda")
38
+
39
+ # ------------------------
40
+ # Util: carga WikiSQL (JSONL)
41
+ # ------------------------
42
+ def _read_jsonl(path):
43
+ with open(path, "r", encoding="utf-8") as f:
44
+ for line in f:
45
+ if line.strip():
46
+ yield json.loads(line)
47
+
48
+ def _download_file(filename: str) -> str:
49
+ # descarga desde el dataset hug
50
+ return hf_hub_download(repo_id=WIKISQL_REPO, filename=filename, repo_type="dataset")
51
 
52
  @lru_cache(maxsize=32)
53
+ def get_table_from_wikisql(split: str, index: int, max_rows: int) -> pd.DataFrame:
54
  """
55
+ Carga la tabla de WikiSQL sin scripts, usando directamente los JSONL del repo:
56
+ - dev.jsonl (validation = 'dev' en terminología original)
57
+ - dev.tables.jsonl
58
+ Si cambias split a 'train' o 'test', intenta los nombres equivalentes.
59
  """
60
+ # Mapeo simple: validation->dev, train->train, test->test
61
+ split_map = {"validation": "dev", "dev": "dev", "train": "train", "test": "test"}
62
+ base = split_map.get(split.lower(), "dev")
63
+
64
+ # Posibles nombres de archivo en el repo (algunos mirrors usan variantes)
65
+ qa_candidates = [f"data/{base}.jsonl", f"data/{base}.json", f"{base}.jsonl"]
66
+ tbl_candidates = [f"data/{base}.tables.jsonl", f"{base}.tables.jsonl"]
67
+
68
+ qa_path = None
69
+ tbl_path = None
70
+
71
+ # Descarga QA
72
+ for cand in qa_candidates:
73
+ try:
74
+ qa_path = _download_file(cand)
75
+ break
76
+ except Exception:
77
+ continue
78
+ if qa_path is None:
79
+ raise RuntimeError(f"No se encontró el archivo QA para split={split}. Intentos: {qa_candidates}")
80
+
81
+ # Descarga tablas
82
+ for cand in tbl_candidates:
83
+ try:
84
+ tbl_path = _download_file(cand)
85
+ break
86
+ except Exception:
87
+ continue
88
+ if tbl_path is None:
89
+ raise RuntimeError(f"No se encontró el archivo de tablas para split={split}. Intentos: {tbl_candidates}")
90
+
91
+ # Leemos la pregunta N (para tomar su table_id) — si no necesitas la pregunta, puedes omitir esto
92
+ qa_list = list(_read_jsonl(qa_path))
93
+ if not (0 <= index < len(qa_list)):
94
+ raise IndexError(f"index={index} fuera de rango (0..{len(qa_list)-1}) para split={split}")
95
+ table_id = qa_list[index].get("table_id") or qa_list[index].get("table", {}).get("id")
96
+ if table_id is None:
97
+ raise RuntimeError("No se pudo extraer 'table_id' del registro de QA.")
98
+
99
+ # Buscamos esa tabla en dev.tables.jsonl
100
+ header, rows = None, None
101
+ for obj in _read_jsonl(tbl_path):
102
+ if obj.get("id") == table_id:
103
+ header = [str(h) for h in obj["header"]]
104
+ rows = obj["rows"]
105
+ break
106
+ if header is None or rows is None:
107
+ raise RuntimeError(f"No se encontró la tabla con id={table_id} en {os.path.basename(tbl_path)}")
108
+
109
+ # recortamos filas
110
+ rows = rows[:max_rows]
111
  df = pd.DataFrame(rows, columns=header)
112
  df.columns = [str(c) for c in df.columns]
113
  return df
114
 
115
+ # ------------------------
116
+ # Endpoints
117
+ # ------------------------
 
 
118
  @app.get("/api/health")
119
  def health():
120
+ return {"ok": True, "model": HF_MODEL_ID, "split": SPLIT, "index": INDEX}
121
 
122
  @app.get("/api/preview")
123
  def preview():
124
  try:
125
+ df = get_table_from_wikisql(SPLIT, INDEX, MAX_ROWS)
126
+ return {"columns": df.columns.tolist(), "rows": df.head(8).to_dict(orient="records")}
127
  except Exception as e:
128
+ return {"error": str(e)}
129
 
130
  @app.post("/api/nl2sql")
131
  def nl2sql(q: NLQuery):
 
 
 
 
 
 
 
 
 
 
 
132
  try:
133
+ text = (q.nl_query or "").strip()
134
+ if not text:
135
+ raise ValueError("Consulta vacía.")
136
+
137
+ # Traducción ES->EN si detectamos acentos u otros
138
+ is_ascii = all(ord(c) < 128 for c in text)
139
+ query_en = text if is_ascii else GoogleTranslator(source="auto", target="en").translate(text)
140
+
141
+ df = get_table_from_wikisql(SPLIT, INDEX, MAX_ROWS)
142
+ enc = tok(table=df, query=query_en, return_tensors="pt", truncation=True)
143
+ if torch.cuda.is_available():
144
+ enc = {k: v.to("cuda") for k, v in enc.items()}
145
+ out = model.generate(**enc, max_length=160, num_beams=1)
146
  sql = tok.batch_decode(out, skip_special_tokens=True)[0]
147
+
148
+ return {
149
+ "consulta_original": text,
150
+ "consulta_traducida": query_en,
151
+ "sql_generado": sql
152
+ }
153
  except Exception as e:
154
  raise HTTPException(status_code=500, detail=str(e))