|
| 1 | +"""Pre-render small WebP thumbnails for every gallery figure/table. |
| 2 | +
|
| 3 | +The web UI's figure thumbnails were CSS-crops of the *full* page PNG (~0.5 MB |
| 4 | +each), so opening a paper with many figures pulled megabytes before anything |
| 5 | +showed. This renders a small thumbnail per gallery item once, served statically |
| 6 | +from the existing ``/pages`` mount — the thumbnail becomes a plain ``<img>``. |
| 7 | +
|
| 8 | +Source per item: |
| 9 | + - figure: downscale the Docling crop already on disk (``data/figures/<paper>/ |
| 10 | + <id>.png``; ``id`` is the chunk_id with ``:`` → ``_``). |
| 11 | + - table (no crop) or a figure whose crop is missing: crop the bbox region out |
| 12 | + of the page render (``data/pages/<paper>/<paper>_p<N>.png``) — pages render |
| 13 | + at 150 DPI, bbox is in PDF points (1/72"), so px = pt * 150/72. |
| 14 | +
|
| 15 | +Output: ``<pages_dir>/<paper>/thumbs/<id>.webp`` (committed with the page PNGs so |
| 16 | +the self-contained prod image bundles them). Items are read from a running |
| 17 | +server's ``/figures`` so the set matches exactly what the gallery shows |
| 18 | +(decoration noise already filtered). |
| 19 | +
|
| 20 | +Run (server up): ``uv run python -m scripts.render_figure_thumbs`` |
| 21 | +""" |
| 22 | + |
| 23 | +from __future__ import annotations |
| 24 | + |
| 25 | +import argparse |
| 26 | +import json |
| 27 | +import sys |
| 28 | +import urllib.request |
| 29 | +from pathlib import Path |
| 30 | + |
| 31 | +from PIL import Image |
| 32 | + |
| 33 | +_DPI = 150 # render_pages default; bbox points → px is pt * _DPI/72 |
| 34 | +_PT_TO_PX = _DPI / 72.0 |
| 35 | + |
| 36 | + |
| 37 | +def _safe_id(chunk_id: str) -> str: |
| 38 | + # Mirror docling_parser._safe_filename so the crop file / thumb name match. |
| 39 | + return chunk_id.replace(":", "_") |
| 40 | + |
| 41 | + |
| 42 | +def _fetch_items(base_url: str) -> list[dict[str, object]]: |
| 43 | + with urllib.request.urlopen(f"{base_url}/figures?limit=1000", timeout=30) as resp: |
| 44 | + items: list[dict[str, object]] = json.load(resp) |
| 45 | + return items |
| 46 | + |
| 47 | + |
| 48 | +def _thumb_from_crop(crop_path: Path, max_px: int) -> Image.Image: |
| 49 | + img = Image.open(crop_path).convert("RGB") |
| 50 | + img.thumbnail((max_px, max_px)) |
| 51 | + return img |
| 52 | + |
| 53 | + |
| 54 | +def _thumb_from_page(page_path: Path, bbox: list[float], max_px: int) -> Image.Image: |
| 55 | + img = Image.open(page_path).convert("RGB") |
| 56 | + x0, y0, x1, y1 = (v * _PT_TO_PX for v in bbox) |
| 57 | + # Clamp to the page so a slightly-oversized bbox can't error. |
| 58 | + x0, y0 = max(0, x0), max(0, y0) |
| 59 | + x1, y1 = min(img.width, x1), min(img.height, y1) |
| 60 | + crop = img.crop((round(x0), round(y0), round(x1), round(y1))) |
| 61 | + crop.thumbnail((max_px, max_px)) |
| 62 | + return crop |
| 63 | + |
| 64 | + |
| 65 | +def main() -> None: |
| 66 | + if hasattr(sys.stdout, "reconfigure"): |
| 67 | + sys.stdout.reconfigure(encoding="utf-8") |
| 68 | + p = argparse.ArgumentParser(description=__doc__) |
| 69 | + p.add_argument("--base-url", default="http://127.0.0.1:8000", help="Running server.") |
| 70 | + p.add_argument("--pages-dir", type=Path, default=Path("data/pages")) |
| 71 | + p.add_argument("--figures-dir", type=Path, default=Path("data/figures")) |
| 72 | + p.add_argument("--max-px", type=int, default=512, help="Longest thumbnail edge.") |
| 73 | + p.add_argument("--quality", type=int, default=80, help="WebP quality.") |
| 74 | + args = p.parse_args() |
| 75 | + |
| 76 | + items = _fetch_items(args.base_url) |
| 77 | + print(f"Rendering thumbnails for {len(items)} gallery items...") |
| 78 | + written = page_fallback = skipped = 0 |
| 79 | + for it in items: |
| 80 | + paper, page = str(it["paper_id"]), it["page_number"] |
| 81 | + bbox_raw = it.get("bbox") |
| 82 | + bbox = bbox_raw if isinstance(bbox_raw, list) else None |
| 83 | + sid = _safe_id(str(it["chunk_id"])) |
| 84 | + out_dir = args.pages_dir / paper / "thumbs" |
| 85 | + out_dir.mkdir(parents=True, exist_ok=True) |
| 86 | + out = out_dir / f"{sid}.webp" |
| 87 | + |
| 88 | + crop_path = args.figures_dir / paper / f"{sid}.png" |
| 89 | + try: |
| 90 | + if crop_path.exists(): |
| 91 | + thumb = _thumb_from_crop(crop_path, args.max_px) |
| 92 | + elif bbox: |
| 93 | + page_path = args.pages_dir / paper / f"{paper}_p{page}.png" |
| 94 | + if not page_path.exists(): |
| 95 | + skipped += 1 |
| 96 | + continue |
| 97 | + thumb = _thumb_from_page(page_path, bbox, args.max_px) |
| 98 | + page_fallback += 1 |
| 99 | + else: |
| 100 | + skipped += 1 |
| 101 | + continue |
| 102 | + thumb.save(out, "WEBP", quality=args.quality, method=6) |
| 103 | + written += 1 |
| 104 | + except Exception as exc: # one bad item shouldn't abort the whole run |
| 105 | + print(f" WARN {it['chunk_id']}: {exc}") |
| 106 | + skipped += 1 |
| 107 | + |
| 108 | + print(f"Wrote {written} thumbnails ({page_fallback} cropped from page), {skipped} skipped.") |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + main() |
0 commit comments