Download demo/src/pdfio.py from AriaAICompany/dlp-lab: direct link, hf CLI and curl.
- Browser
- Download file 3.33 kB
-
https://huggingface.co/datasets/AriaAICompany/dlp-lab/resolve/main/demo/src/pdfio.py
- Command line
-
hf download hf://datasets/AriaAICompany/dlp-lab/demo/src/pdfio.py
-
curl -L -o pdfio.py https://huggingface.co/datasets/AriaAICompany/dlp-lab/resolve/main/demo/src/pdfio.py
3.33 kB
| from __future__ import annotations | |
| from io import BytesIO | |
| from typing import Any | |
| import fitz | |
| from src.domain import MAX_PAGES | |
| from src.normalize import fold_digits | |
| from src.schemas import ValidationReport | |
| def build_pdf(text: str, metadata: dict[str, str] | None = None) -> bytes: | |
| doc = fitz.open() | |
| page = doc.new_page() | |
| # Keep a single text block so search_for can locate laboratory values. | |
| page.insert_text((72, 72), text or " ", fontsize=11) | |
| if metadata: | |
| doc.set_metadata({key: value for key, value in metadata.items() if value}) | |
| payload = doc.tobytes() | |
| doc.close() | |
| return payload | |
| def inspect_pdf(data: bytes, report: ValidationReport | None = None) -> dict[str, Any]: | |
| issues = report or ValidationReport(ok=True) | |
| try: | |
| doc = fitz.open(stream=data, filetype="pdf") | |
| except Exception: | |
| issues.add("pdf_unreadable", "The PDF could not be opened.", "pdf") | |
| return {"text": "", "pages": 0, "metadata": {}, "scanned": False, "report": issues} | |
| pages = doc.page_count | |
| if pages > MAX_PAGES: | |
| issues.add("too_many_pages", f"PDFs are limited to {MAX_PAGES} text pages.", "pdf") | |
| texts = [] | |
| for page in doc: | |
| texts.append(page.get_text("text") or "") | |
| body = "\n".join(texts).strip() | |
| metadata = {key: str(value or "") for key, value in (doc.metadata or {}).items()} | |
| scanned = pages > 0 and len(body) < max(12, pages * 8) | |
| if scanned: | |
| issues.add( | |
| "scanned_pdf", | |
| "Image-only / scanned PDFs are out of scope. This MVP reads a text layer only.", | |
| "pdf", | |
| severity="warning", | |
| ) | |
| result = { | |
| "text": body, | |
| "pages": pages, | |
| "metadata": metadata, | |
| "scanned": scanned, | |
| "report": issues, | |
| } | |
| doc.close() | |
| return result | |
| def redact_pdf(data: bytes, values: list[str], extra_metadata_clear: bool = True) -> tuple[bytes, dict[str, Any]]: | |
| doc = fitz.open(stream=data, filetype="pdf") | |
| hits = 0 | |
| folded_needles = [fold_digits(value) for value in values if value and len(value) >= 4] | |
| for page in doc: | |
| for value in values: | |
| if not value or len(value) < 3: | |
| continue | |
| for rect in page.search_for(value): | |
| page.add_redact_annot(rect, fill=(0, 0, 0)) | |
| hits += 1 | |
| page.apply_redactions() | |
| if extra_metadata_clear: | |
| empty = {key: "" for key in (doc.metadata or {})} | |
| doc.set_metadata(empty) | |
| try: | |
| doc.del_xml_metadata() | |
| except Exception: | |
| pass | |
| payload = doc.tobytes() | |
| verify = inspect_pdf(payload) | |
| leftover = [] | |
| extracted = fold_digits(verify["text"]) | |
| meta_blob = fold_digits(" ".join(verify["metadata"].values())) | |
| for needle, original in zip(folded_needles, [v for v in values if v and len(v) >= 4]): | |
| if needle in extracted or needle in meta_blob: | |
| leftover.append(original) | |
| doc.close() | |
| return payload, {"hits": hits, "leftover": leftover, "pages": verify["pages"], "metadata": verify["metadata"], "text": verify["text"]} | |
| def write_pdf(path, data: bytes) -> None: | |
| path.write_bytes(data) | |
| def pdf_from_path(path) -> bytes: | |
| return path.read_bytes() | |
| def buffer(data: bytes) -> BytesIO: | |
| return BytesIO(data) | |