# ingest.py — indicizzazione con progress, fix MemoryError e guard-rails su pagine grandi import os, re, json, time, math, traceback, argparse import numpy as np import fitz # PyMuPDF from dotenv import load_dotenv from openai import OpenAI from typing import List, Tuple # ====== CONFIG DI BASE (sovrascrivibili da CLI) ====== DOCS_DIR = "documents" RULES_DIR = "rules" OUT_VECS = "index.npz" OUT_META = "index_meta.json" EMBED_MODEL = os.getenv("EMBED_MODEL", "text-embedding-3-small") # chunking “collaudato” CHILD_CHARS_DEFAULT = 700 OVERLAP_DEFAULT = 120 PARENT_WIN_DEFAULT = 1 # 0 = più leggero MIN_CHARS = 80 BATCH_EMB_DEFAULT = 64 MAX_RETRY = 5 # guard-rails MAX_PAGE_CHARS_DEFAULT = 50000 # taglio testo pagina oltre questo limite # ====== REGEX ====== RE_CODE = re.compile(r'\b[A-Z0-9]{3,}(?:-[A-Z0-9]{1,}){2,}\b') RE_LEVEL = re.compile(r'\bMR[12]\b') RE_TASK = re.compile(r'\b(VT|VM|TC\d{0,3})\b', re.IGNORECASE) RE_FREQ = re.compile(r'(?:ogni|each)\s+[^\.]{0,60}?(?:km|chilometr|mesi|settimane|anni)', re.IGNORECASE) RE_TITLE = re.compile(r'^[A-Z0-9][A-Z0-9 \-_/]{8,}$') # titolo probabile (tutto maiuscolo) load_dotenv() client = OpenAI() def norm_space(s: str) -> str: return re.sub(r'\s+', ' ', (s or '').strip()) def page_text(doc, p, light=False): """Estrae testo pagina. Se light=True usa solo 'text' (più veloce).""" pg = doc[p] txt = pg.get_text("text") or "" if light: return txt if not txt.strip(): raw = pg.get_text("rawdict") lines = [] for b in (raw.get("blocks") or []): for l in (b.get("lines") or []): parts = [s.get("text","") for s in (l.get("spans") or [])] if parts: lines.append("".join(parts)) txt = "\n".join(lines) return txt def guess_titles(doc): titles = {} for p in range(len(doc)): raw = doc[p].get_text("rawdict") best = "" for b in (raw.get("blocks") or []): for l in (b.get("lines") or []): for s in (l.get("spans") or []): t = (s.get("text") or "").strip() if not t: continue if RE_TITLE.match(t) and len(t) > len(best): best = t if best: titles[p+1] = norm_space(best) return titles def chunker(text: str, size: int, overlap: int): """Chunker con progressione garantita (no loop) e rispetto MIN_CHARS.""" text = norm_space(text) chunks = [] if not text: return chunks L = len(text) i = 0 prev_i = -1 # per sicurezza, limite massimo iterazioni max_iters = 1 + (L // max(1, size // 2)) iters = 0 while i < L and iters < max_iters: iters += 1 end = min(L, i + size) # prova a spezzare su fine frase entro +100 char j = text.rfind(". ", i, min(L, end + 100)) if j == -1 or j < i + int(size * 0.3): j = end else: j = j + 1 # includi il punto segment = text[i:j].strip() if len(segment) >= MIN_CHARS: chunks.append(segment) # calcola prossimo indice garantendo avanzamento next_i = j - max(0, overlap) if next_i <= i: # forza avanzamento di almeno 1/4 chunk (min 50) next_i = min(L, i + max(50, size // 4)) prev_i, i = i, next_i if i == prev_i: # estrema difesa break return chunks def extract_meta(snippet: str): codes = list(set(RE_CODE.findall(snippet))) level_m = RE_LEVEL.search(snippet); level = level_m.group(0) if level_m else None task_m = RE_TASK.search(snippet); task = task_m.group(1).upper() if task_m else None freq = None; m = RE_FREQ.search(snippet) if m: freq = norm_space(m.group(0)) return codes, level, task, freq def embed_with_retry(texts: List[str], model: str) -> List[List[float]]: delay = 1.0 for attempt in range(1, MAX_RETRY+1): try: r = client.embeddings.create(model=model, input=texts) return [d.embedding for d in r.data] except Exception as e: if attempt == MAX_RETRY: raise print(f" ↳ retry embeddings (tentativo {attempt}/{MAX_RETRY}) in {delay:.1f}s — {type(e).__name__}: {e}", flush=True) time.sleep(delay); delay = min(delay*2, 30.0) return [] def collect_pdfs(): files = [] for base in (DOCS_DIR, RULES_DIR): if not os.path.isdir(base): continue for root, _, fs in os.walk(base): for f in fs: if f.lower().endswith(".pdf"): files.append((base, os.path.join(root, f))) return files def quick_estimate_total_chunks(files: List[Tuple[str,str]], child_chars, overlap, fast: bool): """Stima progressiva: stampa 1 riga per file. In fast-mode campiona max 2 pagine, solo get_text('text').""" total_pages = 0 total_chunks = 0 n = len(files) if n == 0: print("[Stima] Nessun PDF trovato.", flush=True); return 0, 0 print(f"[Stima] Scansiono {n} file PDF…", flush=True) for i, (base, full) in enumerate(files, 1): try: d = fitz.open(full) except Exception as e: print(f" [{i}/{n}] ✖ {os.path.relpath(full, base)} — errore apertura: {e}", flush=True) continue pages = len(d); total_pages += pages # campionamento leggero sample_idx = [0] if pages <= 1 else [0, pages//2] est_chunks = 0; seen = 0 for s in sample_idx: if s >= pages: continue txt = page_text(d, s, light=True if fast else False) est_chunks += len(chunker(txt, child_chars, overlap)); seen += 1 avg = (est_chunks / max(seen,1)) if seen else 0 total_chunks += int(avg * pages) print(f" [{i}/{n}] {os.path.relpath(full, base)} — pagine: {pages}, stima chunk: ~{int(avg)}×{pages} = ~{int(avg*pages)}", flush=True) d.close() print(f"[Stima] Pagine totali: {total_pages} — Chunk stimati: {total_chunks}", flush=True) return total_pages, total_chunks def process_folder(base_dir, category, child_chars, overlap, parent_win, fast, max_page_chars): items_meta, items_vecs = [], [] for root, _, files in os.walk(base_dir): files = [f for f in files if f.lower().endswith(".pdf")] files.sort() for fn in files: rel = os.path.relpath(os.path.join(root, fn), base_dir) full = os.path.join(root, fn) try: doc = fitz.open(full) except Exception as e: print(f"⚠️ Impossibile aprire {full}: {e}", flush=True) continue pages = len(doc) print(f"• Apro {fn} (pagine: {pages})", flush=True) titles = guess_titles(doc) for p in range(pages): txt = page_text(doc, p, light=fast) if not txt.strip(): print(f" - Pagina {p+1}/{pages}: (vuota)", flush=True) continue # taglio hard del testo pagina per risparmiare RAM if len(txt) > max_page_chars: txt = txt[:max_page_chars] cut = True else: cut = False # parent window (p-1..p+1) — in fast mode riduciamo automaticamente a 0 win = 0 if fast else parent_win parent = [] if win > 0: for d in range(-win, win+1): q = p + d if 0 <= q < pages: t2 = page_text(doc, q, light=True if fast else False) if t2.strip(): parent.append(t2) parent_text = "\n".join(parent) chs = chunker(txt, child_chars, overlap) print(f" - Pagina {p+1}/{pages}: {len(txt)} caratteri{' (tagliata)' if cut else ''} → {len(chs)} chunk", flush=True) for ch in chs: snippet = (titles.get(p+1, "") + " " + ch).strip() codes, level, task, freq = extract_meta(snippet) items_meta.append({ "cat": category, "doc": fn, "path": rel, "page": p+1, "title": titles.get(p+1, ""), "text": ch, "parent": parent_text[:2500], "codes": codes, "level": level, "task_type": task, "frequency": freq }) items_vecs.append(ch) doc.close() return items_meta, items_vecs def main(): parser = argparse.ArgumentParser(description="Indicizzazione PDF con progress e guard-rails.") parser.add_argument("--no-estimate", action="store_true", help="Salta la stima iniziale.") parser.add_argument("--fast", action="store_true", help="Modalità leggera (stima e parsing pagine più veloci).") parser.add_argument("--batch", type=int, default=None, help="Batch embeddings (default 64; in fast=16).") parser.add_argument("--parent-win", type=int, default=None, help="Parent window pagine ±N (default 1; in fast=0).") parser.add_argument("--child-chars", type=int, default=None, help="Dimensione chunk (default 700).") parser.add_argument("--overlap", type=int, default=None, help="Overlap chunk (default 120).") parser.add_argument("--max-page-chars", type=int, default=None, help="Taglio del testo per pagina (default 50000).") args = parser.parse_args() # parametri effettivi child_chars = args.child_chars or CHILD_CHARS_DEFAULT overlap = args.overlap or OVERLAP_DEFAULT parent_win = args.parent_win if args.parent_win is not None else PARENT_WIN_DEFAULT batch_emb = args.batch if args.batch is not None else BATCH_EMB_DEFAULT max_page_chars = args.max_page_chars or MAX_PAGE_CHARS_DEFAULT if args.fast: parent_win = 0 if args.parent_win is None else parent_win batch_emb = 16 if args.batch is None else batch_emb # fast: tieni comunque il cap di pagina max_page_chars = min(max_page_chars, 30000) # 1) raccolta PDF files = collect_pdfs() if not files: print("❗ Nessun PDF trovato in 'documents' o 'rules'.", flush=True) return # 2) stima (progressiva) if args.no_estimate: print("[Stima] Skippata per opzione --no-estimate.", flush=True) else: print("[Stima] Inizio… (puoi usare --no-estimate per saltarla)", flush=True) quick_estimate_total_chunks(files, child_chars, overlap, args.fast) # 3) indicizzazione all_meta, all_vecs = [], [] for base in (DOCS_DIR, RULES_DIR): if not os.path.isdir(base): continue print(f"\n=== Indicizzo cartella: {base} ===", flush=True) m, v = process_folder(base, "DOC" if base==DOCS_DIR else "RULE", child_chars, overlap, parent_win, args.fast, max_page_chars) all_meta.extend(m); all_vecs.extend(v) if not all_meta: print("❗ Nessun testo indicizzato.", flush=True); return # 4) embeddings con progress + ETA print(f"\n== Embeddings: {len(all_vecs)} chunk (batch={batch_emb}) ==", flush=True) start = time.time(); vecs = [] for i in range(0, len(all_vecs), batch_emb): batch = all_vecs[i:i+batch_emb] t0 = time.time() embs = embed_with_retry(batch, EMBED_MODEL) vecs.extend(embs) dt = time.time() - t0 done = i + len(batch) pct = (done / len(all_vecs)) * 100.0 speed = done / max(1e-9, (time.time() - start)) remain = len(all_vecs) - done eta = remain / max(1e-9, speed) print(f" ↳ embedding batch={len(batch)} ok in {dt:.1f}s — {done}/{len(all_vecs)} ({pct:.1f}%) ETA ~ {eta/60:.1f} min", flush=True) V = np.array(vecs, dtype=np.float32) np.savez_compressed(OUT_VECS, V=V) with open(OUT_META, "w", encoding="utf-8") as f: json.dump(all_meta, f, ensure_ascii=False) tot = time.time() - start print(f"\n✅ OK: {len(all_meta)} chunk indicizzati", flush=True) print(f" → salvati {OUT_VECS} / {OUT_META}", flush=True) print(f"⏱️ Tempo embeddings: {tot:.1f}s ({len(all_vecs)/max(1,tot):.1f} chunk/s)", flush=True) if __name__ == "__main__": try: main() except KeyboardInterrupt: print("\n⛔ Interrotto dall’utente.", flush=True) except Exception as e: print("❌ Errore:", e, flush=True) traceback.print_exc()