"""Prepare a document-stratified prospective orientation evaluation from DocLayNet PDFs.""" import argparse from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor from contextlib import closing import hashlib import json from pathlib import Path from tempfile import TemporaryDirectory from urllib.request import urlopen from time import sleep import shutil import math import pypdfium2 as pdfium import pyarrow.parquet as pq REV = "0daf93102e2efce76c3e11a274a5e0d0969391d3" BASE = ( f"https://huggingface.co/datasets/docling-project/DocLayNet-v1.2/resolve/{REV}/data" ) SEED = "folio-pdf-orientation-2026-11-a" def order(value): return hashlib.sha256((SEED + "|" + value).encode()).hexdigest() def get_shard(task): i, folder = task name = f"test-{i:05d}-of-00006.parquet" path = folder / name for attempt in range(4): try: with urlopen(f"{BASE}/{name}", timeout=120) as response, path.open( "wb" ) as file: shutil.copyfileobj(response, file, length=1024 * 1024) pq.ParquetFile(path) return path except OSError: if attempt == 3: raise sleep(2**attempt) def render_if_horizontal(pdf_bytes, dest): with pdfium.PdfDocument(pdf_bytes) as doc: if len(doc) != 1: return {"reason": "multi-page source"} with closing(doc[0]) as page, closing(page.get_textpage()) as text: n = 0 horizontal = 0 for index in range(text.count_chars()): char = pdfium.raw.FPDFText_GetUnicode(text, index) if not char or char > 0x10FFFF or not chr(char).isalpha(): continue n += 1 angle = pdfium.raw.FPDFText_GetCharAngle(text, index) if angle >= 0 and abs((math.degrees(angle) + 180) % 360 - 180) <= 8: horizontal += 1 stats = dict( alphabetic_characters=n, horizontal_characters=horizontal, page_rotation=page.get_rotation(), ) if n < 80 or horizontal < 0.9 * n or page.get_rotation() != 0: return {**stats, "reason": "insufficient dominant upright PDF text"} with closing(page.render(scale=1600 / max(page.get_size()))) as bitmap: bitmap.to_pil().convert("RGB").save(dest) return {**stats, "reason": "eligible"} def prepare(out): out.mkdir(exist_ok=True, parents=True) with TemporaryDirectory() as folder: with ThreadPoolExecutor(3) as pool: files = list(pool.map(get_shard, ((i, Path(folder)) for i in range(6)))) docs = defaultdict(lambda: defaultdict(list)) for shard, path in enumerate(files): pf = pq.ParquetFile(path) for group in range(pf.num_row_groups): for j, row in enumerate( pf.read_row_group(group, columns=["metadata"]).column(0).to_pylist() ): docs[row["doc_category"]][row["original_filename"]].append( (row["page_hash"], shard, group, j) ) selected = defaultdict(list) for cat, category_docs in sorted(docs.items()): # Hash ordering chooses documents and a single page before checking text direction. for document in sorted(category_docs, key=lambda f: order(cat + "|" + f))[ :32 ]: page, shard, group, j = min( category_docs[document], key=lambda v: order(v[0]) ) selected[shard, group].append( (j, dict(category=cat, document=document, page_hash=page)) ) manifest = [] for (shard, group), items in sorted(selected.items()): table = pq.ParquetFile(files[shard]).read_row_group(group, columns=["pdf"]) for j, row in items: dest = out / (row["page_hash"] + ".png") pdf = table.column(0)[j].as_py() if pdf: result = render_if_horizontal(pdf, dest) else: result = {"reason": "missing PDF"} manifest.append({**row, **result}) (out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") print(Counter((r["category"], r["reason"]) for r in manifest), flush=True) if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("out", type=Path) prepare(p.parse_args().out)