Spaces:
Paused
Paused
File size: 18,984 Bytes
939ac95 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | # app.py — Chatbot manutenzione: retrieval ibrido + code-aware + citazioni pulite + fallback filtri
import os, re, json, math, numpy as np
from collections import Counter
from fastapi import FastAPI, Request, UploadFile, File, Form
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from jinja2 import Environment, FileSystemLoader, select_autoescape
from dotenv import load_dotenv
from openai import OpenAI
import fitz
from urllib.parse import quote
# ===== Config =====
DOCS_DIR = "documents"
RULES_DIR = "rules"
INDEX_PATH = "index.npz"
META_PATH = "index_meta.json"
MODEL_EMB = os.getenv("EMBED_MODEL", "text-embedding-3-small")
MODEL_CHAT = os.getenv("CHAT_MODEL", "gpt-4o-mini") # o gpt-5-nano (no temperature)
TOP_K_CANDIDATES = 40
TOP_K_FINAL = 10
COSINE_MIN = 0.28
MMR_LAMBDA = 0.65
CACHE_DIR = "cache_images"
TMP_DIR = "tmp"
# ===== Init =====
load_dotenv()
client = OpenAI()
for d in ("static","templates",DOCS_DIR,RULES_DIR,CACHE_DIR,TMP_DIR):
os.makedirs(d, exist_ok=True)
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/docs", StaticFiles(directory=DOCS_DIR), name="docs")
app.mount("/rules", StaticFiles(directory=RULES_DIR), name="rules")
app.mount("/static-cache", StaticFiles(directory=CACHE_DIR), name="static-cache")
env = Environment(loader=FileSystemLoader("templates"), autoescape=select_autoescape(["html","xml"]))
# ===== Load index =====
def _load_index():
if not (os.path.exists(INDEX_PATH) and os.path.exists(META_PATH)):
raise RuntimeError("Indice mancante. Esegui: python ingest.py")
V = np.load(INDEX_PATH)["V"].astype(np.float32)
with open(META_PATH,"r",encoding="utf-8") as f:
meta = json.load(f)
VN = V / (np.linalg.norm(V, axis=1, keepdims=True) + 1e-8)
return V, VN, meta
V, VN, META = _load_index()
# ===== BM25 semplice per ibrido =====
TOKEN = re.compile(r"[A-Za-z0-9_/.-]+")
def _tok(s): return [t.lower() for t in TOKEN.findall(s or "") if len(t)>2]
DOC_TOKS, DF, N = [], Counter(), len(META)
def build_bm25_index():
global DOC_TOKS, DF, N
DOC_TOKS, DF = [], Counter()
N = len(META)
for m in META:
t = " ".join([m.get("text",""), m.get("doc",""), m.get("title","")])
toks = _tok(t)
DOC_TOKS.append(Counter(toks))
for w in set(toks): DF[w]+=1
build_bm25_index()
def bm25(query, i, k1=1.2, b=0.75):
toks = _tok(query)
c = DOC_TOKS[i]
if not c: return 0.0
dl = sum(c.values()) + 1e-9
avgdl = (sum(sum(x.values()) for x in DOC_TOKS)/max(len(DOC_TOKS),1)) or 1.0
score = 0.0
for w in toks:
if DF[w]==0: continue
idf = math.log((N - DF[w] + 0.5)/(DF[w] + 0.5) + 1.0)
tf = c[w]
score += idf * (tf*(k1+1)) / (tf + k1*(1 - b + b*dl/avgdl))
return score
def deep_link(m):
mount = "docs" if m["cat"]=="DOC" else "rules"
return f"/{mount}/{quote(m['path'])}#page={m['page']}&zoom=page-width"
# ===== Helpers =====
STOP = set("di a da in con su per tra fra il lo la i gli le ed che del della delle degli dei un una uno e o al allo alla agli alle ai nel nella negli nelle sul sulla sugli sulle".split())
def keywords(q):
toks = _tok(q.lower()); return [t for t in toks if t not in STOP]
ALIAS = {
"vt": ["visita tecnica","controllo periodico"],
"vm": ["visita mensile","manutenzione programmata"],
"pantografo": ["panto","dispositivo captazione"],
"freno": ["impianto frenante","pneumatico"],
}
def expand(q):
low=q.lower(); extra=[]
for k,vals in ALIAS.items():
if k in low: extra += vals
return q + " " + " ".join(sorted(set(extra)))
def embed_query(q: str):
e = client.embeddings.create(model=MODEL_EMB, input=[q])
v = np.array(e.data[0].embedding, dtype=np.float32)
return v / (np.linalg.norm(v) + 1e-8)
def mmr(qvec, cand_vecs, k, lam):
selected=[]; cand_idx=list(range(len(cand_vecs)))
sims_q = cand_vecs @ qvec
sims_cc= cand_vecs @ cand_vecs.T
i0 = int(np.argmax(sims_q)); selected.append(i0); cand_idx.remove(i0)
while len(selected)<min(k,len(cand_idx)+1) and cand_idx:
best_i,best=-1,-1e9
for i in cand_idx:
rel = sims_q[i]; div = max(sims_cc[i,selected]) if selected else 0.0
score = lam*rel - (1-lam)*div
if score>best: best, best_i = score, i
selected.append(best_i); cand_idx.remove(best_i)
return selected
def reload_index():
global V, VN, META, DOC_TOKS, DF, N
V, VN, META = _load_index()
build_bm25_index()
# --- parsing codici da domanda (gestisce anche varianti parziali) ---
CODE_FULL = re.compile(r'\bETR\d{3,4}-MR\d-\d{2}[A-Z]-(?:TC\d{1,3}|SR\d{2,3}|SB\d{2})\b', re.IGNORECASE)
CODE_PART = re.compile(r'\b(\d{2}[A-Z])-(TC\d{1,3}|SR\d{2,3}|SB\d{2})\b', re.IGNORECASE)
def extract_codes_from_question(q: str):
ql = q.upper()
full = [m.group(0).upper() for m in CODE_FULL.finditer(ql)]
parts = [m.group(0).upper() for m in CODE_PART.finditer(ql)]
norm = lambda s: re.sub(r'\s+', '', s.replace('–','-'))
return list({norm(c) for c in (full + parts)})
def has_code_hard(m, code: str):
"""Match robusto: completo (ETR...-MR...-XXA-TCnnn) o parziale (XXA-TCnnn) con entrambi i pezzi presenti."""
codeU = code.upper()
blob = " ".join([m.get("text",""), m.get("parent",""), m.get("doc",""), m.get("path","")]).upper()
if (codeU in blob) or any(codeU in c.upper() for c in (m.get("codes") or [])):
return True
mp = CODE_PART.fullmatch(codeU)
if mp:
a, b = mp.group(1), mp.group(2)
return (a in blob) and (b in blob)
return False
# ===== Filtro documento (PATCH SMART) =====
def match_filter(m, substr: str):
"""Filtro documento elastico. Supporta '04C-TC001', solo 'TC001', ecc."""
if not substr:
return True
s = substr.strip().upper()
blob = " ".join([
m.get("doc",""), m.get("path",""), m.get("title",""),
m.get("text",""), m.get("parent","")
]).upper()
# match diretto
if s in blob:
return True
# pattern '04C-TC001' (o simili)
part = re.findall(r'\b\d{2}[A-Z]-TC\d{1,3}\b', s)
if part:
sect, tc = part[0].split("-")
return (sect in blob) and (tc in blob)
# solo 'TC001'
only_tc = re.findall(r'\bTC\d{1,3}\b', s)
if only_tc:
return only_tc[0] in blob
# fallback contains
s_low = s.lower()
return (
s_low in (m.get("doc","").lower()) or
s_low in (m.get("path","").lower()) or
s_low in (m.get("text","").lower())
)
# ===== Retrieval =====
def retrieve(question: str, hint: str|None, filter_cat: str|None, filter_doc: str|None, debug: bool):
q0 = expand(question)
q = f"[VEICOLO:{hint}] {q0}" if hint else q0
qvec = embed_query(q)
NEEDS_FREQ = any(k in question.lower() for k in ["frequenza","scadenza","periodicità","vt"])
NEEDS_PROC = any(k in question.lower() for k in ["procedura","come","eseguire","passaggi","tc0","tc00","tc001","prova","controllo"])
sims = VN @ qvec
idx = np.argsort(-sims)[:max(TOP_K_CANDIDATES, 80)]
bm25_scores = {i: bm25(q, int(i)) for i in idx}
bm25_max = max(bm25_scores.values()) if bm25_scores else 1.0
asked_codes = extract_codes_from_question(question)
# pool iniziale
pool = list(idx)
# candidati con filtro (se presente)
cand = []
for i in pool:
m = META[int(i)]
if filter_cat and m["cat"]!=filter_cat:
continue
if filter_doc and not match_filter(m, filter_doc):
continue
cos = float(sims[int(i)])
if cos < COSINE_MIN:
continue
hscore = 0.55*cos + 0.45*(bm25_scores.get(i,0.0)/(bm25_max+1e-9))
if asked_codes and any(has_code_hard(m, c) for c in asked_codes):
hscore += 0.30
if any(c for c in (m.get("codes") or []) if c.lower() in question.lower()): hscore += 0.08
if m.get("task_type") and m["task_type"].lower() in question.lower(): hscore += 0.05
if m.get("level") and m["level"].lower() in question.lower(): hscore += 0.05
doc_low = (m.get("doc","")+m.get("title","")).lower()
if NEEDS_FREQ and any(k in doc_low for k in ["piano","scadenze","livello","programma"]): hscore += 0.06
if NEEDS_PROC and any(k in doc_low for k in ["tc","scheda","procedura","prova","controllo"]): hscore += 0.06
cand.append((int(i), hscore))
# ===== Fallback se il filtro azzera tutto (PATCH) =====
if not cand:
pool = list(idx) # senza filter_doc
for i in pool:
m = META[int(i)]
if filter_cat and m["cat"] != filter_cat:
continue
cos = float(sims[int(i)])
if cos < COSINE_MIN:
continue
hscore = 0.55*cos + 0.45*(bm25_scores.get(i,0.0)/(bm25_max+1e-9))
if asked_codes and any(has_code_hard(m, c) for c in asked_codes):
hscore += 0.30
cand.append((int(i), hscore))
if not cand:
return [], {"note": "0 candidati anche senza filtro_doc."}
cand.sort(key=lambda x: -x[1])
cand_idx = [i for i,_ in cand[:TOP_K_CANDIDATES]]
# MMR per diversità
cand_vecs = VN[cand_idx]
order = mmr(qvec, cand_vecs, k=min(TOP_K_FINAL*2, len(cand_idx)), lam=MMR_LAMBDA)
mmr_idx = [cand_idx[i] for i in order]
# gate parole chiave
K = set(keywords(question))
def passes_kw(text: str):
if not K: return True
L = text.lower(); return sum(1 for k in K if k in L) >= 1
final_idx = [i for i in mmr_idx if passes_kw(META[int(i)].get("text",""))][:TOP_K_FINAL]
dbg = {}
if debug:
dbg = {"asked_codes": asked_codes, "cand_count": len(cand), "final": final_idx[:10]}
return final_idx, dbg
def build_context(question, hint, filter_cat, filter_doc, debug):
idxs, dbg = retrieve(question, hint, filter_cat, filter_doc, debug)
if not idxs:
return "", [], dbg
# parent window ±1
idx_set = set(idxs)
for i in list(idxs):
m = META[int(i)]
doc = m["doc"]; page = m["page"]; cat = m["cat"]
for p in range(page-1, page+2):
for j, mm in enumerate(META):
if mm["cat"]==cat and mm["doc"]==doc and mm["page"]==p:
idx_set.add(j)
final = [i for i in idx_set][:TOP_K_FINAL+5]
blocks, cites_raw = [], []
for ii in final[:TOP_K_FINAL]:
m = META[int(ii)]
blocks.append(f"[{m['path']} p.{m['page']}] {m.get('text','')}\n(PARENT) {m.get('parent','')}")
cites_raw.append(m)
# citazioni uniche e ordinate
cit_map = {}
for m in cites_raw:
key = (m.get("path"), m.get("page"))
if not key[0] or not key[1] or key in cit_map:
continue
cit_map[key] = {
"cat": m["cat"], "doc": m["doc"], "path": m["path"],
"page": int(m["page"]), "url": deep_link(m),
"rev": m.get("rev",""), "mod": m.get("mod",""),
"title": (m.get("title","") or "").strip()
}
cites = [v for _,v in sorted(cit_map.items(), key=lambda kv: (kv[0][0], kv[0][1]))]
context = "\n---\n".join(blocks)
return context, cites, dbg
def answer_with_context(question, hint, filter_cat, filter_doc, debug):
context, cites, dbg = build_context(question, hint, filter_cat, filter_doc, debug)
if not context:
return "Non ho trovato estratti sufficientemente pertinenti nella base indicizzata rispetto alla domanda.", cites, dbg
sys = ("Sei un assistente di manutenzione ferroviaria. "
"Rispondi SOLO usando il CONTEXT fornito. "
"Se una parte della domanda non è coperta dal CONTEXT, dillo e NON indovinare. "
"Cita doc/percorso/pagina. Se presenti frequenze, riporta tempo e chilometraggio.")
usr = f"DOMANDA: {question}\n\nCONTEXT:\n{context}\n\nDai una risposta estrattiva, con citazioni, sintetica ma completa."
kwargs = {"model": MODEL_CHAT, "messages":[{"role":"system","content":sys},{"role":"user","content":usr}]}
if MODEL_CHAT != "gpt-5-nano":
kwargs["temperature"] = 0
r1 = client.chat.completions.create(**kwargs)
draft = r1.choices[0].message.content
ver_sys = ("Sei un verificatore. Togli tutto ciò che non è chiaramente supportato dal CONTEXT. "
"Mantieni solo frasi giustificate dagli estratti. Non introdurre nulla di nuovo.")
ver_usr = f"CONTEXT:\n{context}\n\nDRAFT:\n{draft}\n\nRestituisci versione pulita e aderente agli estratti."
kwargs2 = {"model": MODEL_CHAT, "messages":[{"role":"system","content":ver_sys},{"role":"user","content":ver_usr}]}
if MODEL_CHAT != "gpt-5-nano":
kwargs2["temperature"] = 0
r2 = client.chat.completions.create(**kwargs2)
final = r2.choices[0].message.content
return final, cites, dbg
# ===== Routes =====
@app.get("/", response_class=HTMLResponse)
def index():
tpl = env.get_template("index.html")
return tpl.render()
@app.post("/ask")
async def ask(req: Request):
try:
data = await req.json()
q = (data.get("question") or "").strip()
hint = (data.get("hint") or "").strip() or None
fcat = (data.get("filter_cat") or "").strip().upper() or None
fdoc = (data.get("filter_doc") or "").strip() or None
debug = bool(data.get("debug", False))
if not q:
return JSONResponse({"ok":False,"error":"Domanda vuota."}, status_code=400)
ans, cites, dbg = answer_with_context(q, hint, fcat, fdoc, debug)
payload = {"ok":True, "answer": ans, "cites": cites}
if debug: payload["debug"] = dbg
return JSONResponse(payload)
except Exception as e:
return JSONResponse({"ok":False,"error":f"{type(e).__name__}: {e}"}, status_code=500)
@app.post("/upload")
async def upload_pdf(file: UploadFile = File(...), category: str = Form("DOC")):
try:
category = category.upper()
if category not in ("DOC","RULE"):
return JSONResponse({"ok":False,"error":"Categoria non valida (DOC|RULE)."}, status_code=400)
base = DOCS_DIR if category=="DOC" else RULES_DIR
dst = os.path.join(base, file.filename)
with open(dst, "wb") as f: f.write(await file.read())
return JSONResponse({"ok":True,"message":"Upload ok. Esegui ingest.py e poi 'Ricarica indice'."})
except Exception as e:
return JSONResponse({"ok":False,"error":str(e)}, status_code=500)
@app.post("/reload")
def reload():
try:
reload_index()
return JSONResponse({"ok":True,"message":"Indice ricaricato."})
except Exception as e:
return JSONResponse({"ok":False,"error":str(e)}, status_code=500)
@app.get("/catalog")
def catalog():
try:
items={}
for m in META:
k=(m["cat"], m["path"])
if k not in items:
items[k]={"cat":m["cat"],"path":m["path"],"doc":m["doc"],
"title":m.get("title",""),"rev":m.get("rev",""),
"mod":m.get("mod",""),"pages":set()}
items[k]["pages"].add(int(m["page"]))
out=[]
for v in items.values():
v["pages"]=len(v["pages"])
mount="docs" if v["cat"]=="DOC" else "rules"
v["url"]=f"/{mount}/{quote(v['path'])}#page=1&zoom=page-width"
out.append(v)
out.sort(key=lambda x:(x["cat"], x["doc"]))
return JSONResponse({"ok":True, "docs": out})
except Exception as e:
return JSONResponse({"ok":False,"error":str(e)}, status_code=500)
@app.post("/compare-files")
async def compare_files(files: list[UploadFile] = File(...)):
try:
results=[]
for uf in files:
b = await uf.read()
tmp = os.path.join(TMP_DIR, uf.filename)
with open(tmp,"wb") as f: f.write(b)
doc = fitz.open(tmp)
full=[]
for p in doc:
t = p.get_text("text") or ""
if t.strip(): full.append(t)
merged="\n".join(full)
if not merged.strip():
results.append({"file":uf.filename,"analysis":"PDF senza testo estraibile."})
continue
snippet = merged[:8000]
ctx, cites, _ = build_context("Confronta con: "+snippet, None, None, None, False)
sys = ("Valuta la conformità del TESTO rispetto al CONTEXT (documentazione indicizzata). "
"Indica: (1) allineamenti, (2) difformità puntuali, (3) suggerimenti. Cita doc/pagina.")
usr = f"CONTEXT:\n{ctx}\n\nTESTO:\n{snippet}"
kwargs = {"model": MODEL_CHAT, "messages":[{"role":"system","content":sys},{"role":"user","content":usr}]}
if MODEL_CHAT != "gpt-5-nano": kwargs["temperature"]=0
r = client.chat.completions.create(**kwargs)
results.append({"file": uf.filename, "analysis": r.choices[0].message.content, "cites": cites})
return JSONResponse({"ok":True, "results": results})
except Exception as e:
return JSONResponse({"ok":False,"error":str(e)}, status_code=500)
@app.get("/page-images")
def page_images(path: str, page: int, cat: str = "DOC"):
try:
base = DOCS_DIR if cat.upper()=="DOC" else RULES_DIR
full = os.path.join(base, path)
if not os.path.exists(full):
return JSONResponse({"ok":False,"error":"File non trovato"}, status_code=404)
doc = fitz.open(full)
if page<1 or page>len(doc):
return JSONResponse({"ok":False,"error":"Pagina non valida"}, status_code=400)
p = doc[page-1]
urls=[]
for img in p.get_images(full=True):
xref = img[0]; pix = fitz.Pixmap(doc, xref)
if pix.n>4: pix = fitz.Pixmap(fitz.csRGB, pix)
png = pix.tobytes("png")
import hashlib
h = hashlib.md5(png).hexdigest()
out=os.path.join(CACHE_DIR, h+".png")
if not os.path.exists(out):
with open(out,"wb") as f: f.write(png)
urls.append(f"/static-cache/{h}.png")
return JSONResponse({"ok":True,"images":urls})
except Exception as e:
return JSONResponse({"ok":False,"error":str(e)}, status_code=500)
|