overlay_preview.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """Draw bounding-box previews on top of a rasterised page.
  2. Reads the new-style ``fields.json`` config (see docs/forms-guide.md
  3. for the schema) and overlays each entry/tag rectangle onto a single
  4. page image so the operator can eyeball the geometry before running
  5. ``scripts.fill.overlay_apply``.
  6. Run from the skill root::
  7. python -m scripts.render.overlay_preview \\
  8. 1 fields.json out_dir/page_1.png out_dir/page_1_overlay.png
  9. """
  10. from __future__ import annotations
  11. import json
  12. import sys
  13. from PIL import Image, ImageDraw
  14. from scripts.lib.cli_utils import emit, fail, make_parser
  15. def render_overlay_preview(
  16. page_no: int,
  17. cfg_path: str,
  18. base_img: str,
  19. out_img: str,
  20. *,
  21. quiet: bool = False,
  22. ) -> int:
  23. with open(cfg_path, "r") as handle:
  24. cfg = json.load(handle)
  25. canvas = Image.open(base_img)
  26. painter = ImageDraw.Draw(canvas)
  27. drawn_boxes = 0
  28. for slot in cfg.get("slots", []):
  29. if slot.get("page_no") != page_no:
  30. continue
  31. slot_box = slot.get("slot_box")
  32. tag_box = slot.get("tag_box")
  33. if slot_box:
  34. painter.rectangle(slot_box, outline="red", width=2)
  35. drawn_boxes += 1
  36. if tag_box:
  37. painter.rectangle(tag_box, outline="blue", width=2)
  38. drawn_boxes += 1
  39. canvas.save(out_img)
  40. emit(
  41. f"Rendered overlay preview to {out_img} ({drawn_boxes} boxes drawn)",
  42. quiet=quiet,
  43. )
  44. return drawn_boxes
  45. def main(argv: list[str] | None = None) -> int:
  46. parser = make_parser(
  47. "overlay_preview",
  48. "Draw slot/tag bounding boxes on top of a rasterised page image.",
  49. )
  50. parser.add_argument("page_no", type=int, help="1-based page number.")
  51. parser.add_argument("cfg_path", help="Path to fields.json (new schema).")
  52. parser.add_argument("base_img", help="Input page PNG.")
  53. parser.add_argument("out_img", help="Output PNG with overlay drawn.")
  54. args = parser.parse_args(argv)
  55. try:
  56. render_overlay_preview(
  57. args.page_no,
  58. args.cfg_path,
  59. args.base_img,
  60. args.out_img,
  61. quiet=args.quiet,
  62. )
  63. except FileNotFoundError as exc:
  64. fail(f"File not found: {exc.filename}", code=2)
  65. except Exception as exc: # noqa: BLE001
  66. fail(f"Overlay preview failed: {exc}", code=2)
  67. return 0
  68. if __name__ == "__main__":
  69. sys.exit(main())