#!/usr/bin/env python3 """Classify PDFs as vector or scanned using Poppler command-line tools. The classifier does not inspect producer metadata or filenames. It measures the physical coverage of embedded raster images and combines that with extractable text/font evidence. This also detects OCR'd scans: a page-sized image wins over an invisible OCR text layer. """ from __future__ import annotations import argparse import csv import json import re import shutil import subprocess import sys from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict, dataclass from pathlib import Path from typing import Iterable, Sequence REQUIRED_TOOLS = ("pdfinfo", "pdfimages", "pdftotext", "pdffonts") DEFAULT_DIRECTORIES = (Path("DDR_Templates"), Path("DDR templates")) PAGE_SIZE_RE = re.compile( r"^Page\s+(\d+)\s+size:\s+([0-9.]+)\s+x\s+([0-9.]+)\s+pts", re.MULTILINE ) PAGE_COUNT_RE = re.compile(r"^Pages:\s+(\d+)", re.MULTILINE) class ClassificationError(RuntimeError): """Raised when a PDF cannot be inspected.""" @dataclass(frozen=True) class PageEvidence: page: int text_characters: int max_image_coverage: float classification: str @dataclass(frozen=True) class PDFResult: path: str classification: str confidence: float pages: int scanned_pages: int vector_pages: int font_count: int text_characters: int max_image_coverage: float reason: str error: str | None = None def _run(command: Sequence[str], timeout: int = 60) -> str: try: completed = subprocess.run( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="replace", timeout=timeout, check=False, ) except subprocess.TimeoutExpired as exc: raise ClassificationError(f"command timed out: {command[0]}") from exc except OSError as exc: raise ClassificationError(f"could not run {command[0]}: {exc}") from exc if completed.returncode: detail = completed.stderr.strip() or "unknown error" raise ClassificationError(f"{command[0]} failed: {detail}") return completed.stdout def _page_geometry(pdf: Path) -> tuple[int, dict[int, float]]: output = _run(["pdfinfo", "-box", str(pdf)]) count_match = PAGE_COUNT_RE.search(output) if not count_match: raise ClassificationError("pdfinfo did not report a page count") page_count = int(count_match.group(1)) # Some pdfinfo versions only print every page size when -f/-l is explicit. output = _run(["pdfinfo", "-f", "1", "-l", str(page_count), "-box", str(pdf)]) areas = { int(page): float(width) * float(height) for page, width, height in PAGE_SIZE_RE.findall(output) } if len(areas) != page_count: # Fall back to the generic page size for PDFs whose pages are uniform. generic = re.search( r"^Page size:\s+([0-9.]+)\s+x\s+([0-9.]+)\s+pts", output, re.MULTILINE ) if generic: area = float(generic.group(1)) * float(generic.group(2)) areas = {page: area for page in range(1, page_count + 1)} if len(areas) != page_count: raise ClassificationError("pdfinfo did not report every page size") return page_count, areas def _image_coverage(pdf: Path, page_areas: dict[int, float]) -> dict[int, float]: """Return the largest image's displayed-area ratio for each page. pdfimages reports image dimensions and effective x/y DPI. Those values let us recover the image's displayed size in PDF points without parsing streams. """ output = _run(["pdfimages", "-list", str(pdf)]) coverage = {page: 0.0 for page in page_areas} for line in output.splitlines()[2:]: columns = line.split() if len(columns) < 14 or columns[2] not in {"image", "mask", "smask"}: continue try: page = int(columns[0]) width_px = int(columns[3]) height_px = int(columns[4]) x_dpi = float(columns[12]) y_dpi = float(columns[13]) except (ValueError, IndexError): continue if page not in page_areas or x_dpi <= 0 or y_dpi <= 0: continue displayed_area = (width_px * 72.0 / x_dpi) * (height_px * 72.0 / y_dpi) ratio = min(displayed_area / page_areas[page], 1.0) coverage[page] = max(coverage[page], ratio) return coverage def _text_by_page(pdf: Path, page_count: int) -> list[int]: output = _run(["pdftotext", "-enc", "UTF-8", str(pdf), "-"]) pages = output.split("\f") if pages and not pages[-1].strip(): pages.pop() pages.extend([""] * max(0, page_count - len(pages))) return [sum(not char.isspace() for char in text) for text in pages[:page_count]] def _font_count(pdf: Path) -> int: output = _run(["pdffonts", str(pdf)]) lines = output.splitlines() return sum(bool(line.strip()) for line in lines[2:]) def _classify_pages( text_counts: Sequence[int], image_coverage: dict[int, float], font_count: int ) -> list[PageEvidence]: evidence: list[PageEvidence] = [] for page, text_count in enumerate(text_counts, start=1): coverage = image_coverage.get(page, 0.0) if coverage >= 0.72: page_class = "scanned" elif text_count >= 20: page_class = "vector" elif coverage >= 0.25 and text_count < 20: page_class = "scanned" elif font_count and text_count: page_class = "vector" else: page_class = "unknown" evidence.append(PageEvidence(page, text_count, coverage, page_class)) return evidence def classify_pdf(pdf: str | Path) -> PDFResult: """Classify one PDF and return its evidence summary.""" path = Path(pdf) try: page_count, page_areas = _page_geometry(path) coverage = _image_coverage(path, page_areas) text_counts = _text_by_page(path, page_count) fonts = _font_count(path) page_evidence = _classify_pages(text_counts, coverage, fonts) scanned = sum(item.classification == "scanned" for item in page_evidence) vector = sum(item.classification == "vector" for item in page_evidence) informative = scanned + vector if informative == 0: # Empty/blank PDFs have no scan evidence, so vector is the safer class. classification = "vector" confidence = 0.5 reason = "no page-sized raster images or extractable text found" else: scan_ratio = scanned / informative classification = "scanned" if scan_ratio >= 0.5 else "vector" confidence = 0.5 + abs(scan_ratio - 0.5) if classification == "scanned": reason = f"{scanned}/{informative} informative pages are raster-dominant" else: reason = f"{vector}/{informative} informative pages contain native text/vector content" return PDFResult( path=str(path), classification=classification, confidence=round(confidence, 3), pages=page_count, scanned_pages=scanned, vector_pages=vector, font_count=fonts, text_characters=sum(text_counts), max_image_coverage=round(max(coverage.values(), default=0.0), 3), reason=reason, ) except ClassificationError as exc: return PDFResult( path=str(path), classification="error", confidence=0.0, pages=0, scanned_pages=0, vector_pages=0, font_count=0, text_characters=0, max_image_coverage=0.0, reason="classification failed", error=str(exc), ) def _find_default_directory() -> Path: for directory in DEFAULT_DIRECTORIES: if directory.is_dir(): return directory names = " or ".join(str(path) for path in DEFAULT_DIRECTORIES) raise ClassificationError(f"default input directory not found ({names})") def _pdf_paths(inputs: Iterable[str]) -> list[Path]: paths: list[Path] = [] for raw_path in inputs: path = Path(raw_path) if path.is_file() and path.suffix.lower() == ".pdf": paths.append(path) elif path.is_dir(): paths.extend(candidate for candidate in path.rglob("*") if candidate.suffix.lower() == ".pdf") else: raise ClassificationError(f"not a PDF file or directory: {path}") return sorted(set(paths), key=lambda item: str(item).lower()) def _write_results(results: Sequence[PDFResult], output_format: str, stream: object) -> None: rows = [asdict(result) for result in results] if output_format == "json": json.dump(rows, stream, indent=2, ensure_ascii=False) stream.write("\n") elif output_format == "csv": writer = csv.DictWriter(stream, fieldnames=list(PDFResult.__dataclass_fields__)) writer.writeheader() writer.writerows(rows) else: headers = ("CLASS", "CONF", "PAGES", "MAX IMAGE", "TEXT", "PATH") display_rows = [ ( result.classification, f"{result.confidence:.0%}", str(result.pages), f"{result.max_image_coverage:.0%}", str(result.text_characters), result.path, ) for result in results ] widths = [ max(len(headers[index]), *(len(row[index]) for row in display_rows)) for index in range(len(headers)) ] if display_rows else [len(header) for header in headers] stream.write(" ".join(value.ljust(width) for value, width in zip(headers, widths)) + "\n") stream.write(" ".join("-" * width for width in widths) + "\n") for row in display_rows: stream.write(" ".join(value.ljust(width) for value, width in zip(row, widths)) + "\n") def _check_tools() -> None: missing = [tool for tool in REQUIRED_TOOLS if shutil.which(tool) is None] if missing: raise ClassificationError( "missing Poppler tools: " + ", ".join(missing) + ". Install poppler first." ) def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "inputs", nargs="*", help="PDF file(s) or directories (default: DDR_Templates/DDR templates)" ) parser.add_argument("--format", choices=("table", "json", "csv"), default="table") parser.add_argument("--output", type=Path, help="write results to this file instead of stdout") parser.add_argument("--workers", type=int, default=4, help="parallel PDF inspections (default: 4)") return parser.parse_args(argv) def main(argv: Sequence[str] | None = None) -> int: args = parse_args(argv) try: _check_tools() inputs = args.inputs or [str(_find_default_directory())] pdfs = _pdf_paths(inputs) if not pdfs: raise ClassificationError("no PDF files found") workers = max(1, min(args.workers, len(pdfs))) with ThreadPoolExecutor(max_workers=workers) as executor: results = list(executor.map(classify_pdf, pdfs)) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) with args.output.open("w", encoding="utf-8", newline="") as stream: _write_results(results, args.format, stream) else: _write_results(results, args.format, sys.stdout) return int(any(result.error for result in results)) except ClassificationError as exc: print(f"error: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())