"""Fetch document bodies from ``link`` and write PDFs (fallback: ``full_text``).""" from __future__ import annotations import io import sys import time from pathlib import Path import openpyxl import requests from bs4 import BeautifulSoup from pypdf import PdfReader from legex.pdf_export.core import safe_slug, write_one_pdf from legex.pdf_export.font_keys import font_key_for_workbook from legex.pdf_export.workbook import cell, discover_goldensets, header_map UA = "Mozilla/5.0 (compatible; LegexPDFExport/1.0)" def is_hf_dataset_stub_url(url: str) -> bool: u = url.lower() return "huggingface.co" in u and "/datasets/" in u def effective_timeout(url: str, configured: float) -> float: u = url.lower() if "hcourt.gov.au" in u: return min(configured, 10.0) if "openlegaldata.io" in u: return min(configured, 12.0) return configured def fetch_document_text(url: str, timeout: float = 28.0) -> str: url = (url or "").strip() if not url or not url.startswith("http"): return "" last_err: str | None = None for attempt in range(2): try: r = requests.get( url, timeout=timeout, headers={"User-Agent": UA, "Accept": "text/html,application/pdf;q=0.9,*/*;q=0.8"}, allow_redirects=True, ) r.raise_for_status() data = r.content if len(data) >= 4 and data[:4] == b"%PDF": reader = PdfReader(io.BytesIO(data)) return "\n\n".join((p.extract_text() or "") for p in reader.pages) enc = r.encoding or "utf-8" try: html = data.decode(enc, errors="replace") except LookupError: html = data.decode("utf-8", errors="replace") soup = BeautifulSoup(html, "lxml") for tag in soup(["script", "style", "noscript"]): tag.decompose() text = soup.get_text("\n") lines = [ln.strip() for ln in text.splitlines()] return "\n".join(ln for ln in lines if ln) except Exception as e: last_err = str(e) if attempt < 1: time.sleep(1.2 * (attempt + 1)) if last_err: return f"[Abruf fehlgeschlagen: {last_err}]\n" return "" def pick_body( link_val: str, sheet_full: str | None, pause_s: float, req_timeout: float, ) -> tuple[str, str]: time.sleep(pause_s) link_val = (link_val or "").strip() sheet = (sheet_full or "").strip() if link_val and is_hf_dataset_stub_url(link_val): if sheet: return sheet, "full_text (HF-Dataset-Link)" return "(kein Volltext in der Zeile trotz HF-Link)", "leer" fetched = ( fetch_document_text(link_val, timeout=effective_timeout(link_val, req_timeout)) if link_val else "" ) if fetched and not fetched.startswith("[Abruf fehlgeschlagen"): return fetched.strip(), "URL" if sheet: return sheet, "full_text (Fallback)" if fetched: return fetched.strip(), "URL (Fehlermeldung)" return "(kein Volltext — weder URL noch Tabellenfeld)", "leer" def export_workbook( xlsx: Path, out_root: Path, *, pause_s: float, limit: int | None, req_timeout: float, resume: bool, ) -> int: label = xlsx.parent.name out_dir = out_root / label font_key = font_key_for_workbook(xlsx) wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) if "GOLDENSET" not in wb.sheetnames: wb.close() print(f" skip {xlsx.name}: kein Sheet GOLDENSET", flush=True) return 0 ws = wb["GOLDENSET"] rows = ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True) header_row = next(rows, None) if not header_row: wb.close() return 0 h = header_map(header_row) idx_case = h.get("case_id") idx_link = h.get("link") idx_text = h.get("full_text") if idx_link is None: wb.close() print(f" skip {xlsx.name}: keine Spalte 'link'", flush=True) return 0 used_names: dict[str, int] = {} count = 0 row_idx = 1 for row in rows: row_idx += 1 if not row: continue link_val = cell(row, idx_link) or "" case_id = cell(row, idx_case) sheet_full = cell(row, idx_text) if idx_text is not None else None if ( not str(case_id or "").strip() and not link_val.strip() and not (sheet_full or "").strip() ): continue base = safe_slug(case_id, link_val or None, row_idx) used_names[base] = used_names.get(base, 0) + 1 fname = f"{base}_{used_names[base]}.pdf" if used_names[base] > 1 else f"{base}.pdf" out_path = out_dir / fname if resume and out_path.exists() and out_path.stat().st_size > 80: count += 1 if count % 25 == 0: print(f" {label}: {count} (Bestand übersprungen) …", flush=True) if limit is not None and count >= limit: break continue body, prov = pick_body(link_val, sheet_full, pause_s, req_timeout) write_one_pdf(out_path, str(case_id or ""), link_val, body, font_key, text_source=prov) count += 1 if count % 10 == 0: print(f" {label}: {count} …", flush=True) if limit is not None and count >= limit: break wb.close() print(f" {label}: fertig, {count} PDFs", flush=True) return count def collect_workbooks(data_dir: Path, input_dirs: list[Path] | None) -> list[Path]: if input_dirs: files: list[Path] = [] for d in input_dirs: if not d.is_dir(): print("Ordner fehlt:", d, file=sys.stderr) continue files.extend(sorted(d.glob("Goldenset_*.xlsx"))) return sorted(files, key=lambda p: (p.stem.lower(), str(p))) return discover_goldensets(data_dir)