Spaces:
Running on Zero
Running on Zero
Download scripts/gemini_tree.py from denizkaya2022/IPARD-Vectorless-RAG: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/spaces/denizkaya2022/IPARD-Vectorless-RAG/resolve/main/scripts/gemini_tree.py
- Command line
-
hf download hf://spaces/denizkaya2022/IPARD-Vectorless-RAG/scripts/gemini_tree.py
-
curl -L -o gemini_tree.py https://huggingface.co/spaces/denizkaya2022/IPARD-Vectorless-RAG/resolve/main/scripts/gemini_tree.py
18.6 kB
| #!/usr/bin/env python3 | |
| """ | |
| gemini_tree.py — IPARD PDF'lerinden hızlı ağaç yapısı çıkarır. | |
| Katmanlı strateji (belge başına LLM çağrısını minimuma indirir): | |
| 1) Gömülü TOC (PDF bookmark'ları) -> doc.get_toc(), 0 LLM çağrısı, anında | |
| 2) Basılı içindekiler sayfası -> Gemini'ye 1 çağrı (yapı+sayfa), sonra | |
| fiziksel sayfa offset'i deterministik çözülür | |
| 3) TOC yok -> font/başlık tabanlı fallback (LLM yok) | |
| Çıktı: tree_index.json ({docs:[{source_file, doc_id, measure, doc_type, method, | |
| page_count, nodes:[{title, level, start_page, end_page, nodes}]}]}) | |
| Kullanım: | |
| set GEMINI_API_KEY=... (Windows: $env:GEMINI_API_KEY="...") | |
| python gemini_tree.py # data/pdfs -> tree_index.json | |
| python gemini_tree.py --pdf-dir data/pdfs --limit 5 | |
| python gemini_tree.py --no-llm # sadece gömülü TOC + font (Gemini kullanma) | |
| Gerekli: pymupdf, openai (pip install pymupdf openai) | |
| """ | |
| from __future__ import annotations | |
| import argparse, hashlib, json, os, re, sys, time, uuid | |
| from collections import Counter | |
| from pathlib import Path | |
| import fitz # pymupdf | |
| # ---- Gemini (OpenAI-uyumlu endpoint; temiz JSON için response_format) ---- | |
| GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai/" | |
| MODEL = os.environ.get("GEMINI_TREE_MODEL", "gemini-2.5-flash") | |
| _client = None | |
| def gclient(): | |
| global _client | |
| if _client is None: | |
| from openai import OpenAI | |
| key = os.environ.get("GEMINI_API_KEY") | |
| if not key: | |
| sys.exit("GEMINI_API_KEY tanımlı değil.") | |
| _client = OpenAI(api_key=key, base_url=GEMINI_BASE) | |
| return _client | |
| # ============================ yardımcılar ============================ | |
| TOC_KEYWORDS = ("içindekiler", "icindekiler", "ıçındekıler", "contents", "içerik") | |
| HEADING_NUM = re.compile(r"^\s*(?:madde|bölüm|bolum|ek|kriter|tedbir)\b|^\s*\d+(?:\.\d+)*[\.\)]?\s+\S", re.IGNORECASE) | |
| def nest_flat(flat, page_count): | |
| """flat: [(level, title, page)] -> nested; end_page = sonraki düğümün başlangıcı - 1.""" | |
| root, stack, lin = [], [(0, None)], [] | |
| for level, title, page in flat: | |
| node = {"title": (title or "").strip(), "level": int(level), | |
| "start_page": page, "end_page": None, "nodes": []} | |
| while len(stack) > 1 and stack[-1][0] >= level: | |
| stack.pop() | |
| parent = stack[-1][1] | |
| (parent["nodes"] if parent else root).append(node) | |
| stack.append((level, node)); lin.append(node) | |
| for i, n in enumerate(lin): | |
| if n["start_page"] is None: | |
| continue | |
| nxt = None | |
| for j in range(i + 1, len(lin)): | |
| if lin[j]["start_page"] is not None: | |
| nxt = lin[j]["start_page"]; break | |
| n["end_page"] = max(n["start_page"], (nxt - 1) if nxt else page_count) | |
| return root | |
| def embedded_tree(doc): | |
| toc = doc.get_toc(simple=True) # [[level, title, page], ...] (1-based fiziksel) | |
| if not toc or len(toc) < 3: | |
| return None | |
| flat = [(lvl, title, pg if pg > 0 else None) for lvl, title, pg in toc] | |
| return nest_flat(flat, len(doc)) | |
| def find_toc_pages(doc, max_scan=25): | |
| """İçindekiler sayfalarını bul: 'İÇİNDEKİLER' anahtar kelimesi veya nokta-lider yoğunluğu.""" | |
| pages = [] | |
| for i in range(min(len(doc), max_scan)): | |
| txt = doc[i].get_text() | |
| low = txt.lower() | |
| dotted = len(re.findall(r"\.{4,}\s*\d{1,4}", txt)) # "....... 12" | |
| if any(k in low for k in TOC_KEYWORDS) or dotted >= 5: | |
| pages.append(i) | |
| elif pages and dotted >= 3: # içindekiler birden fazla sayfaya taşabilir | |
| pages.append(i) | |
| elif pages: | |
| break | |
| return pages | |
| def gemini_toc_tree(doc, toc_pages): | |
| text = "\n".join(f"--- sayfa {p+1} ---\n{doc[p].get_text()}" for p in toc_pages) | |
| text = text[:12000] | |
| prompt = ( | |
| "Aşağıda bir belgenin İÇİNDEKİLER (içerik) sayfası var. Bölüm/başlık hiyerarşisini çıkar.\n" | |
| "SADECE şu formatta JSON döndür, başka hiçbir şey yazma:\n" | |
| '{"entries":[{"title":"...","level":1,"page":5}]}\n' | |
| "Kurallar: level 1=ana başlık, 2=alt, 3=alt-alt. page=içindekilerde yazan sayfa no " | |
| "(tamsayı; yoksa null). Başlıkları AYNEN koru (çevirme, kısaltma, açıklama YOK). " | |
| "Nokta-lider ve sayfa numaralarını başlığa dahil etme.\n\n" + text | |
| ) | |
| for attempt in range(4): | |
| try: | |
| r = gclient().chat.completions.create( | |
| model=MODEL, temperature=0, | |
| response_format={"type": "json_object"}, | |
| messages=[{"role": "user", "content": prompt}], | |
| ) | |
| raw = r.choices[0].message.content | |
| data = json.loads(raw) | |
| entries = data.get("entries", data if isinstance(data, list) else []) | |
| flat = [(int(e.get("level", 1)), e.get("title", ""), | |
| e.get("page") if isinstance(e.get("page"), int) else None) | |
| for e in entries if e.get("title")] | |
| if not flat: | |
| return None | |
| off = resolve_offset(doc, flat, set(toc_pages)) | |
| pc = len(doc) | |
| flat = [(l, t, (min(max(p + off, 1), pc) if p else None)) for l, t, p in flat] | |
| return nest_flat(flat, pc) | |
| except Exception as e: # noqa: BLE001 | |
| if "429" in str(e) or "rate" in str(e).lower(): | |
| time.sleep(5 * (attempt + 1)); continue | |
| if attempt < 3: | |
| time.sleep(2); continue | |
| print(f" [gemini hata] {type(e).__name__}: {str(e)[:100]}") | |
| return None | |
| return None | |
| def _norm_line(t): | |
| return " ".join((t or "").lower().split()) | |
| def _heading_page(doc, title, toc_pages): | |
| """Basligin BASLIK OLARAK gectigi ilk fiziksel sayfa (1-based). | |
| Icindekiler sayfalarini ve nokta-lider satirlarini ('BASLIK ..... 32') reddeder.""" | |
| t = _norm_line(title)[:45] | |
| if len(t) < 6: | |
| return None | |
| dotted = re.compile(r"\.{3,}\s*\d{1,4}\s*$") | |
| for pno in range(1, len(doc) + 1): | |
| if (pno - 1) in toc_pages: # find_toc_pages 0-based dondurur | |
| continue | |
| for line in doc[pno - 1].get_text().splitlines(): | |
| ln = _norm_line(line) | |
| if t in ln and not dotted.search(line.strip()) and len(ln) <= len(t) + 25: | |
| return pno | |
| return None | |
| def resolve_offset(doc, flat, toc_pages=()): | |
| """Basili sayfa -> fiziksel sayfa offset'i. | |
| Basliklari icindekiler DISINDA, baslik-satiri olarak arar; en sik (mode) offset'i secer.""" | |
| offs = [] | |
| for level, title, printed in flat[:25]: | |
| if not printed: | |
| continue | |
| pg = _heading_page(doc, title, toc_pages) | |
| if pg: | |
| offs.append(pg - printed) | |
| if not offs: | |
| return 0 | |
| return Counter(offs).most_common(1)[0][0] | |
| def font_tree(doc, max_pages_per_node=6): | |
| """TOC yok: font/başlık sezgisiyle ağaç; başlık az ise sayfa-chunk'a düş.""" | |
| sizes = Counter() | |
| lines = [] # (page, size, bold, text) | |
| for pno in range(len(doc)): | |
| for blk in doc[pno].get_text("dict").get("blocks", []): | |
| for ln in blk.get("lines", []): | |
| spans = ln.get("spans", []) | |
| if not spans: | |
| continue | |
| text = "".join(s["text"] for s in spans).strip() | |
| if not text or len(text) > 160: | |
| continue | |
| size = round(max(s["size"] for s in spans), 1) | |
| bold = any("bold" in (s.get("font", "").lower()) for s in spans) | |
| sizes[size] += 1 | |
| lines.append((pno + 1, size, bold, text)) | |
| if not lines: | |
| return page_chunks(doc, max_pages_per_node) | |
| body = sizes.most_common(1)[0][0] | |
| heads = [] | |
| for page, size, bold, text in lines: | |
| is_num = bool(HEADING_NUM.match(text)) | |
| is_big = size >= body + 1.0 | |
| is_caps = text == text.upper() and len(text) > 3 and any(c.isalpha() for c in text) | |
| if (is_big or (bold and is_caps) or is_num) and not re.match(r"^[\d\.\,\s]+$", text): | |
| level = 1 if size >= body + 3 else (2 if size >= body + 1.0 else 3) | |
| heads.append((level, text, page)) | |
| # gürültü: aynı sayfada 8+ "başlık" varsa muhtemelen gövde -> at | |
| if len(heads) < 2: | |
| return page_chunks(doc, max_pages_per_node) | |
| def is_noise_head(text): | |
| text = (text or "").strip() | |
| return (len(text) <= 2 or re.match(r"^(?:TKDK|POZ\s*NO|TANIMI|BİRİMİ|GRUP)$", text, re.I) | |
| or re.match(r"^X\s+", text, re.I) | |
| or re.match(r"^\d+\s*/\s*\d+$", text)) | |
| noise = sum(1 for _, text, _ in heads if is_noise_head(text)) | |
| density = len(heads) / max(1, len(doc)) | |
| # Tablo/satir gürültüsü varsa sahte başlık ağacı yerine güvenilir sayfa | |
| # pencereleri kullan; retrieval gövde metni sayfa indeksinden devam eder. | |
| if len(heads) > 1000 or (density > 6 and noise / len(heads) >= 0.20) \ | |
| or noise / len(heads) >= 0.25: | |
| return page_chunks(doc, max_pages_per_node) | |
| return nest_flat(heads, len(doc)) | |
| def page_chunks(doc, n=6): | |
| out, pc = [], len(doc) | |
| for start in range(1, pc + 1, n): | |
| end = min(start + n - 1, pc) | |
| out.append({"title": f"Sayfa {start}-{end}", "level": 1, | |
| "start_page": start, "end_page": end, "nodes": []}) | |
| return out | |
| def count_nodes(nodes): | |
| return sum(1 + count_nodes(n["nodes"]) for n in nodes) | |
| def sha256_of(path: Path) -> str: | |
| """PDF icerik ozeti; ayni adli ama degismis belge eski agacla kullanilmasin.""" | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(1 << 16), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def noisy_existing_tree(d) -> bool: | |
| """Eski indekslerdeki belirgin font/tablo gürültüsünü tespit eder.""" | |
| titles = [] | |
| def walk(nodes): | |
| for n in nodes: | |
| titles.append((n.get("title") or "").strip()) | |
| walk(n.get("nodes", [])) | |
| walk(d.get("nodes", [])) | |
| if not titles: | |
| return True | |
| def is_noise(t): | |
| return bool(len(t) <= 2 or re.match(r"^(?:TKDK|POZ\s*NO|TANIMI|BİRİMİ|GRUP)$", t, re.I) | |
| or re.match(r"^X\s+", t, re.I) | |
| or re.match(r"^\d+\s*/\s*\d+$", t)) | |
| ratio = sum(is_noise(t) for t in titles) / len(titles) | |
| density = len(titles) / max(1, d.get("page_count") or 1) | |
| return len(titles) > 1000 or (density > 6 and ratio >= 0.20) or ratio >= 0.25 | |
| # ============================ metadata ============================ | |
| def infer_measure(name): | |
| m = re.search(r"(?<!\d)(101|103|201|202|302)(?!\d)", name) | |
| return m.group(1) if m else "" | |
| def infer_doc_type(name): | |
| """Manifest kaydi olmayan yerel PDF'ler icin temel belge turu tahmini.""" | |
| u = name.lower().translate(str.maketrans({"ç": "c", "ğ": "g", "ı": "i", "ö": "o", | |
| "ş": "s", "ü": "u"})) | |
| if "rehber" in u or "kilavuz" in u: | |
| return "rehber" | |
| if "cagri-ilani" in u or "cagriilani" in u or "cagriilan" in u: | |
| return "cagri-ilani" | |
| if any(k in u for k in ("kanun", "yonetmel", "antlasma", "kararname", | |
| "programi", "mevzuat", "cetveli", "etik")): | |
| return "mevzuat" | |
| if any(k in u for k in ("kontrol", "ikame", "poz", "maliyet", "on-kontrol")): | |
| return "operasyon" | |
| if "ukks" in u or "politika" in u or "gorunurluk" in u: | |
| return "politika" | |
| if "odeme" in u: | |
| return "odeme" | |
| return "diger" | |
| def infer_version(name): | |
| """Dosya adinda acikca bulunan surum numarasini (ornegin 8.0) dondurur.""" | |
| m = re.search(r"(?:__|[-_])v?(\d+\.\d+)(?:__|[-_.])", name, re.IGNORECASE) | |
| return m.group(1) if m else "" | |
| def build_one(pdf_path, use_llm=True): | |
| doc = fitz.open(pdf_path) | |
| method, tree = "embedded_toc", embedded_tree(doc) | |
| if tree is None and use_llm: | |
| tp = find_toc_pages(doc) | |
| if tp: | |
| tree = gemini_toc_tree(doc, tp) | |
| method = "gemini_toc" | |
| if tree is None: | |
| tree = font_tree(doc); method = "font_fallback" | |
| pc = len(doc) | |
| text_pages = sum(1 for p in doc if p.get_text().strip()) | |
| doc.close() | |
| return tree, method, pc, text_pages | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--pdf-dir", default="data/pdfs") | |
| ap.add_argument("--out", default="tree_index.json") | |
| ap.add_argument("--manifest", default="data/manifest.json") | |
| ap.add_argument("--limit", type=int, default=None) | |
| ap.add_argument("--no-llm", action="store_true", help="Gemini kullanma (sadece gömülü TOC + font)") | |
| ap.add_argument("--stamp-existing", action="store_true", | |
| help="Mevcut agaci yeniden kurmadan PDF hash/metadata/OCR alanlarini guncelle") | |
| args = ap.parse_args() | |
| pdfs = sorted(Path(args.pdf_dir).glob("*.pdf")) | |
| if args.limit: | |
| pdfs = pdfs[:args.limit] | |
| if not pdfs: | |
| sys.exit(f"PDF yok: {args.pdf_dir}") | |
| meta_map = {} | |
| mf = Path(args.manifest) | |
| if mf.exists(): | |
| for e in json.loads(mf.read_text(encoding="utf-8")).values(): | |
| if e.get("filename"): | |
| meta_map[e["filename"]] = e | |
| # resumable | |
| out_path = Path(args.out) | |
| existing = {} | |
| existing_ordered = [] | |
| if out_path.exists(): | |
| existing_ordered = json.loads(out_path.read_text(encoding="utf-8")).get("docs", []) | |
| for d in existing_ordered: | |
| existing[d["source_file"]] = d | |
| if args.stamp_existing: | |
| if not existing_ordered: | |
| sys.exit(f"Mevcut agac bulunamadi: {out_path}") | |
| stamped = 0 | |
| refreshed = 0 | |
| for d in existing_ordered: | |
| p = Path(args.pdf_dir) / d.get("source_file", "") | |
| if not p.exists(): | |
| continue | |
| meta = meta_map.get(p.name, {}) | |
| d["file_sha256"] = sha256_of(p) | |
| d["measure"] = meta.get("measure") or d.get("measure") or infer_measure(p.name) | |
| d["doc_type"] = meta.get("doc_type") or d.get("doc_type") or infer_doc_type(p.name) | |
| d["url"] = meta.get("url") or d.get("url", "") | |
| d["last_modified"] = meta.get("last_modified") or d.get("last_modified", "") | |
| d["version"] = d.get("version") or infer_version(p.name) | |
| d["source_kind"] = "remote" if d.get("url") else "manual" | |
| try: | |
| with fitz.open(p) as pdf: | |
| d["text_pages"] = sum(1 for page in pdf if page.get_text().strip()) | |
| d["ocr_required"] = d["text_pages"] < len(pdf) | |
| if d.get("method") == "font_fallback" and noisy_existing_tree(d): | |
| # Mevcut bozuk agaci Gemini'ye tekrar gondermeden sayfa | |
| # pencereleriyle degistir; body retrieval page index'ten surer. | |
| d["nodes"] = font_tree(pdf) | |
| refreshed += 1 | |
| except Exception: | |
| d["text_pages"] = 0 | |
| d["ocr_required"] = True | |
| stamped += 1 | |
| out_path.write_text(json.dumps({"docs": existing_ordered}, ensure_ascii=False, indent=2), encoding="utf-8") | |
| print(f"Stamp tamamlandi: {stamped} belge, gürültülü yenilenen={refreshed} -> {out_path}") | |
| return | |
| docs, t_all = [], time.time() | |
| by_method = Counter() | |
| for i, p in enumerate(pdfs, 1): | |
| file_sha256 = sha256_of(p) | |
| prior = existing.get(p.name) | |
| meta = meta_map.get(p.name, {}) | |
| # Eski indekslerde hash yoksa bir kez yeniden isle; boylece gecmis cache | |
| # kayitlari sessizce guvenilir kabul edilmez. | |
| if prior and prior.get("file_sha256") == file_sha256: | |
| # PDF degismese bile manifest metadata'si degisebilir; cache hit'te de | |
| # tur/measure/url/surum alanlarini tazele. | |
| prior["measure"] = meta.get("measure") or prior.get("measure") or infer_measure(p.name) | |
| prior["doc_type"] = meta.get("doc_type") or prior.get("doc_type") or infer_doc_type(p.name) | |
| prior["url"] = meta.get("url") or prior.get("url", "") | |
| prior["last_modified"] = meta.get("last_modified") or prior.get("last_modified", "") | |
| prior["version"] = prior.get("version") or infer_version(p.name) | |
| prior["source_kind"] = "remote" if prior.get("url") else "manual" | |
| docs.append(prior); by_method[prior.get("method", "?")] += 1 | |
| print(f"[{i}/{len(pdfs)}] cache: {p.name[:55]}") | |
| continue | |
| t0 = time.time() | |
| try: | |
| tree, method, pc, text_pages = build_one(str(p), use_llm=not args.no_llm) | |
| except Exception as e: # noqa: BLE001 | |
| print(f"[{i}/{len(pdfs)}] HATA {p.name[:50]} -> {type(e).__name__}: {str(e)[:80]}") | |
| continue | |
| entry = { | |
| "source_file": p.name, | |
| "doc_id": str(uuid.uuid4()), | |
| "measure": meta.get("measure") or infer_measure(p.name), | |
| "doc_type": meta.get("doc_type") or infer_doc_type(p.name), | |
| "url": meta.get("url", ""), | |
| "file_sha256": file_sha256, | |
| "last_modified": meta.get("last_modified", ""), | |
| "version": infer_version(p.name), | |
| "source_kind": "remote" if meta.get("url") else "manual", | |
| "method": method, | |
| "page_count": pc, | |
| "text_pages": text_pages, | |
| "ocr_required": text_pages < pc, | |
| "nodes": tree, | |
| } | |
| docs.append(entry); by_method[method] += 1 | |
| # her belgeden sonra kaydet (resumable) | |
| out_path.write_text(json.dumps({"docs": docs}, ensure_ascii=False, indent=2), encoding="utf-8") | |
| print(f"[{i}/{len(pdfs)}] {method:>13} | düğüm={count_nodes(tree):>3} | {p.name[:48]} ({time.time()-t0:.1f}s)") | |
| # BUG FIX: dongu icinde yalnizca YENI belge islendiginde diske yaziliyordu; | |
| # son yeni belgeden sonra gelen cache kayitlari dosyaya dusmuyordu. | |
| # Son bir kez daha yaz ki nihai liste (cache dahil) eksiksiz kaydedilsin. | |
| out_path.write_text(json.dumps({"docs": docs}, ensure_ascii=False, indent=2), encoding="utf-8") | |
| print(f"\nBitti: {len(docs)} belge toplam {(time.time()-t_all)/60:.1f} dk") | |
| print("Yöntem dağılımı:", dict(by_method)) | |
| print(f"Kaydedildi: {out_path}") | |
| if __name__ == "__main__": | |
| main() | |