geometry.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Geometry helpers for the MiniMax PDF skill.
  2. This module concentrates the coordinate-system bridges that the
  3. form-fill scripts share:
  4. - ``image_box_to_pdf_rect``: rasterised page pixel coords -> pypdf rect
  5. (origin at the bottom-left of the page).
  6. - ``pdf_box_to_pypdf_rect``: pdfplumber-style PDF coords (origin at
  7. the top-left) -> pypdf rect (origin at the bottom-left).
  8. - ``boxes_overlap``: boolean intersection check used by the geometry
  9. linter.
  10. All functions are intentionally side-effect free so the module can be
  11. imported at unit-test time without touching disk or pulling in heavy
  12. PDF dependencies.
  13. """
  14. from __future__ import annotations
  15. from typing import Sequence
  16. # Type aliases (Python 3.9+ accepts these in annotations because
  17. # ``from __future__ import annotations`` defers evaluation).
  18. Box = Sequence[float]
  19. def image_box_to_pdf_rect(
  20. bbox: Box,
  21. img_w: float,
  22. img_h: float,
  23. pdf_w: float,
  24. pdf_h: float,
  25. ) -> tuple[float, float, float, float]:
  26. """Convert a pixel-space bbox into a pypdf rectangle.
  27. ``bbox`` is ``[left, top, right, bottom]`` in raster pixels. The
  28. output is ``(left, bottom, right, top)`` in PDF user-space points,
  29. with the origin at the bottom-left of the page (which is what
  30. ``pypdf.annotations.FreeText`` expects).
  31. """
  32. sx = pdf_w / img_w
  33. sy = pdf_h / img_h
  34. left = bbox[0] * sx
  35. right = bbox[2] * sx
  36. top = pdf_h - (bbox[1] * sy)
  37. bottom = pdf_h - (bbox[3] * sy)
  38. return left, bottom, right, top
  39. def pdf_box_to_pypdf_rect(
  40. bbox: Box,
  41. pdf_h: float,
  42. ) -> tuple[float, float, float, float]:
  43. """Flip a pdfplumber-style bbox to pypdf orientation.
  44. pdfplumber reports ``[x0, top, x1, bottom]`` with the origin at the
  45. top-left; pypdf expects the origin at the bottom-left.
  46. """
  47. left = bbox[0]
  48. right = bbox[2]
  49. pypdf_top = pdf_h - bbox[1]
  50. pypdf_bottom = pdf_h - bbox[3]
  51. return left, pypdf_bottom, right, pypdf_top
  52. def boxes_overlap(box_a: Box, box_b: Box) -> bool:
  53. """True iff two axis-aligned boxes have a non-empty intersection.
  54. Both inputs are ``[left, top, right, bottom]`` (the convention used
  55. in the ``fields.json`` schema). Edge contact is treated as
  56. *non-overlapping* so the linter does not complain about boxes that
  57. happen to share a border.
  58. """
  59. apart_x = box_a[0] >= box_b[2] or box_a[2] <= box_b[0]
  60. apart_y = box_a[1] >= box_b[3] or box_a[3] <= box_b[1]
  61. return not (apart_x or apart_y)