layout_scan.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """Scan the visual layout of a non-fillable PDF.
  2. Walks each page with pdfplumber and emits a JSON document containing:
  3. - ``pages``: page geometry (size in PDF points)
  4. - ``glyphs``: every text run with its bounding box
  5. - ``rules``: long horizontal lines (candidates for row separators)
  6. - ``ticks``: small square rectangles likely to be checkboxes
  7. - ``bands``: derived row boundaries (pairs of consecutive rule y-values)
  8. Run from the skill root::
  9. python -m scripts.pdf_inspect.layout_scan input.pdf out.json \\
  10. --min-checkbox-px 5 --max-checkbox-px 15
  11. """
  12. from __future__ import annotations
  13. import json
  14. import sys
  15. import pdfplumber
  16. from scripts.lib.cli_utils import emit, fail, make_parser
  17. def scan_layout(
  18. src_pdf: str,
  19. *,
  20. min_checkbox_px: float = 5.0,
  21. max_checkbox_px: float = 15.0,
  22. ) -> dict:
  23. layout: dict = {
  24. "pages": [],
  25. "glyphs": [],
  26. "rules": [],
  27. "ticks": [],
  28. "bands": [],
  29. }
  30. with pdfplumber.open(src_pdf) as pdf:
  31. for page_no, page in enumerate(pdf.pages, 1):
  32. layout["pages"].append(
  33. {
  34. "page_no": page_no,
  35. "pdf_w": float(page.width),
  36. "pdf_h": float(page.height),
  37. }
  38. )
  39. for word in page.extract_words():
  40. layout["glyphs"].append(
  41. {
  42. "page_no": page_no,
  43. "text": word["text"],
  44. "x0": round(float(word["x0"]), 1),
  45. "top": round(float(word["top"]), 1),
  46. "x1": round(float(word["x1"]), 1),
  47. "bottom": round(float(word["bottom"]), 1),
  48. }
  49. )
  50. for line in page.lines:
  51. if abs(float(line["x1"]) - float(line["x0"])) > page.width * 0.5:
  52. layout["rules"].append(
  53. {
  54. "page_no": page_no,
  55. "y": round(float(line["top"]), 1),
  56. "x0": round(float(line["x0"]), 1),
  57. "x1": round(float(line["x1"]), 1),
  58. }
  59. )
  60. for rect in page.rects:
  61. w = float(rect["x1"]) - float(rect["x0"])
  62. h = float(rect["bottom"]) - float(rect["top"])
  63. if (
  64. min_checkbox_px <= w <= max_checkbox_px
  65. and min_checkbox_px <= h <= max_checkbox_px
  66. and abs(w - h) < 2
  67. ):
  68. layout["ticks"].append(
  69. {
  70. "page_no": page_no,
  71. "x0": round(float(rect["x0"]), 1),
  72. "top": round(float(rect["top"]), 1),
  73. "x1": round(float(rect["x1"]), 1),
  74. "bottom": round(float(rect["bottom"]), 1),
  75. "center_x": round(
  76. (float(rect["x0"]) + float(rect["x1"])) / 2, 1
  77. ),
  78. "center_y": round(
  79. (float(rect["top"]) + float(rect["bottom"])) / 2, 1
  80. ),
  81. }
  82. )
  83. rules_by_page: dict[int, list[float]] = {}
  84. for rule in layout["rules"]:
  85. rules_by_page.setdefault(rule["page_no"], []).append(rule["y"])
  86. for page_no, rule_ys in rules_by_page.items():
  87. rule_ys = sorted(set(rule_ys))
  88. for i in range(len(rule_ys) - 1):
  89. layout["bands"].append(
  90. {
  91. "page_no": page_no,
  92. "row_top": rule_ys[i],
  93. "row_bottom": rule_ys[i + 1],
  94. "row_height": round(rule_ys[i + 1] - rule_ys[i], 1),
  95. }
  96. )
  97. return layout
  98. def main(argv: list[str] | None = None) -> int:
  99. parser = make_parser(
  100. "layout_scan",
  101. "Extract glyphs / rules / checkboxes from a non-fillable PDF.",
  102. )
  103. parser.add_argument("src_pdf", help="Input PDF without AcroForm fields.")
  104. parser.add_argument("dst_json", help="Output JSON path.")
  105. parser.add_argument(
  106. "--min-checkbox-px",
  107. type=float,
  108. default=5.0,
  109. help="Minimum side length (PDF points) for a rect to count as a checkbox.",
  110. )
  111. parser.add_argument(
  112. "--max-checkbox-px",
  113. type=float,
  114. default=15.0,
  115. help="Maximum side length (PDF points) for a rect to count as a checkbox.",
  116. )
  117. args = parser.parse_args(argv)
  118. try:
  119. emit(f"Scanning layout of {args.src_pdf}...", quiet=args.quiet)
  120. layout = scan_layout(
  121. args.src_pdf,
  122. min_checkbox_px=args.min_checkbox_px,
  123. max_checkbox_px=args.max_checkbox_px,
  124. )
  125. except FileNotFoundError:
  126. fail(f"PDF not found: {args.src_pdf}", code=2)
  127. except Exception as exc: # noqa: BLE001
  128. fail(f"Could not scan {args.src_pdf}: {exc}", code=2)
  129. with open(args.dst_json, "w") as handle:
  130. json.dump(layout, handle, indent=2)
  131. emit("Layout summary:", quiet=args.quiet)
  132. emit(f" pages : {len(layout['pages'])}", quiet=args.quiet)
  133. emit(f" glyphs: {len(layout['glyphs'])}", quiet=args.quiet)
  134. emit(f" rules : {len(layout['rules'])}", quiet=args.quiet)
  135. emit(f" ticks : {len(layout['ticks'])}", quiet=args.quiet)
  136. emit(f" bands : {len(layout['bands'])}", quiet=args.quiet)
  137. emit(f"Saved to {args.dst_json}", quiet=args.quiet)
  138. return 0
  139. if __name__ == "__main__":
  140. sys.exit(main())