"""Archive cited sources whose publisher permits redistribution (build-time step; needs network). Usage: python scripts/fetch_permitted_documents.py Only sources with licence_category == "redistributable" in official_sources are fetched (EU institutions, US federal works, UK OGL, Canadian federal law, Australian legislation, Japanese e-Gov law data). Original PDFs are kept as published; HTML pages are printed to PDF with headless Microsoft Edge. Writes offline/permitted_documents/., offline/permitted_documents_text/.txt and the document_metadata table (data/, json/, jsonl/, csv/). Needs pymupdf and pandas. """ import concurrent.futures as cf import hashlib import json import queue import subprocess import sys import time import urllib.request from pathlib import Path import pandas as pd import pymupdf EDGE = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36" root, profile_root = Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve() docs_dir, text_dir = root / "offline" / "permitted_documents", root / "offline" / "permitted_documents_text" docs_dir.mkdir(parents=True, exist_ok=True) text_dir.mkdir(parents=True, exist_ok=True) sources = [s for s in json.loads((root / "json" / "official_sources.json").read_text("utf-8")) if s["redistributable"]] profiles = queue.Queue() for i in range(5): profiles.put(profile_root / f"p{i}") def text_of(path): try: return "\n".join(p.get_text() for p in pymupdf.open(path)).strip() except Exception: # noqa: BLE001 return "" def download(url, dest): req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "*/*"}) with urllib.request.urlopen(req, timeout=90) as r: data = r.read() if data[:4] != b"%PDF": return False dest.write_bytes(data) return True def render(url, dest): prof = profiles.get() try: subprocess.run([EDGE, "--headless=new", "--disable-gpu", "--no-pdf-header-footer", "--hide-scrollbars", f"--user-data-dir={prof}", "--virtual-time-budget=15000", f"--user-agent={UA}", f"--print-to-pdf={dest}", url], timeout=150, capture_output=True) deadline, last = time.time() + 120, -1 while time.time() < deadline: # msedge.exe returns before its child process writes the PDF size = dest.stat().st_size if dest.exists() else -1 if size > 0 and size == last: break last = size time.sleep(2) except subprocess.TimeoutExpired: pass finally: profiles.put(prof) return dest.exists() and dest.stat().st_size > 2000 def archive(s): doc_id = "DOC-" + s["source_id"][4:] dest = docs_dir / f"{doc_id}.pdf" method = None try: if download(s["url"], dest): method = "original_pdf" except Exception: # noqa: BLE001 pass if not method and render(s["url"], dest): method = "rendered_html_to_pdf" text = text_of(dest) if method else "" blocked = any(b in text.lower()[:2500] for b in ("access denied", "verify you are human", "just a moment", "403 forbidden", "page not found", "performing security verification")) if not method or len(text) < 300 or blocked: dest.unlink(missing_ok=True) return None, s["url"] (text_dir / f"{doc_id}.txt").write_text(text, "utf-8") data = dest.read_bytes() return {"doc_id": doc_id, "source_id": s["source_id"], "url": s["url"], "title": s.get("title", "unknown"), "local_path": f"offline/permitted_documents/{dest.name}", "format": "pdf", "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(), "licence_category": s["licence_category"], "licence_basis": s.get("licence_basis", ""), "retrieved_at": time.strftime("%Y-%m-%d"), "capture_method": method, "text_chars": len(text)}, s["url"] try: # licence basis text comes from the build script's rules sys.path.insert(0, str(Path(__file__).resolve().parent)) from build_dataset_from_records import licence_for for s in sources: s["licence_basis"] = licence_for(s["url"])[1] except Exception: # noqa: BLE001 pass docs, failed = [], [] with cf.ThreadPoolExecutor(max_workers=5) as ex: for meta, url in ex.map(archive, sources): (docs if meta else failed).append(meta or url) print(("ok " if meta else "failed ") + url[:110], flush=True) docs.sort(key=lambda d: d["doc_id"]) for sub in ("data", "json", "jsonl", "csv"): (root / sub).mkdir(exist_ok=True) pd.DataFrame(docs).to_parquet(root / "data" / "document_metadata.parquet", index=False) pd.DataFrame(docs).to_csv(root / "csv" / "document_metadata.csv", index=False, encoding="utf-8") (root / "json" / "document_metadata.json").write_text(json.dumps(docs, indent=1, ensure_ascii=False), "utf-8") (root / "jsonl" / "document_metadata.jsonl").write_text("".join(json.dumps(d, ensure_ascii=False) + "\n" for d in docs), "utf-8") (root / "offline" / "permitted_documents_failed.json").write_text(json.dumps(failed, indent=1), "utf-8") print(json.dumps({"archived": len(docs), "failed": len(failed)}))