geometry_lint.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. """Lint bounding-box geometry inside a fields.json config.
  2. Catches the two mistakes operators make most often when hand-editing
  3. ``fields.json``:
  4. 1. **Overlapping rectangles** (slot vs. slot, slot vs. tag, tag vs.
  5. tag), which cause text to land on top of other text.
  6. 2. **Slot boxes that are too short** for the configured font size,
  7. which clips glyphs.
  8. The script returns exit code 0 only if no findings are produced.
  9. Run from the skill root::
  10. python -m scripts.validate.geometry_lint fields.json --max-findings 20
  11. """
  12. from __future__ import annotations
  13. import json
  14. import sys
  15. from dataclasses import dataclass
  16. from scripts.lib.cli_utils import make_parser
  17. from scripts.lib.geometry import boxes_overlap
  18. @dataclass
  19. class BoxRecord:
  20. bbox: list[float]
  21. kind: str # "slot" or "tag"
  22. owner: dict # the original slot dict
  23. def _label_for(slot: dict) -> str:
  24. return slot.get("description") or slot.get("tag_text") or "<unnamed>"
  25. def lint(cfg_path: str, max_findings: int = 20) -> tuple[bool, list[str]]:
  26. with open(cfg_path) as handle:
  27. cfg = json.load(handle)
  28. findings: list[str] = []
  29. findings.append(f"Read {len(cfg['slots'])} slots from {cfg_path}")
  30. boxes: list[BoxRecord] = []
  31. for slot in cfg["slots"]:
  32. if "tag_box" in slot:
  33. boxes.append(BoxRecord(slot["tag_box"], "tag", slot))
  34. if "slot_box" in slot:
  35. boxes.append(BoxRecord(slot["slot_box"], "slot", slot))
  36. failed = False
  37. # --- intersection scan ---
  38. for i, left in enumerate(boxes):
  39. for right in boxes[i + 1 :]:
  40. if left.owner["page_no"] != right.owner["page_no"]:
  41. continue
  42. if not boxes_overlap(left.bbox, right.bbox):
  43. continue
  44. failed = True
  45. if left.owner is right.owner:
  46. findings.append(
  47. f"FAILURE: slot/tag overlap inside `{_label_for(left.owner)}`: "
  48. f"{left.bbox} vs {right.bbox}"
  49. )
  50. else:
  51. findings.append(
  52. f"FAILURE: {left.kind} of `{_label_for(left.owner)}` "
  53. f"({left.bbox}) overlaps {right.kind} of "
  54. f"`{_label_for(right.owner)}` ({right.bbox})"
  55. )
  56. if len(findings) >= max_findings:
  57. findings.append("Too many findings; aborting further checks.")
  58. return True, findings
  59. # --- height check ---
  60. for record in boxes:
  61. if record.kind != "slot":
  62. continue
  63. glyph_spec = record.owner.get("value")
  64. if not glyph_spec:
  65. continue
  66. glyph_pt = glyph_spec.get("size", 14)
  67. slot_h = record.bbox[3] - record.bbox[1]
  68. if slot_h < glyph_pt:
  69. failed = True
  70. findings.append(
  71. f"FAILURE: slot height {slot_h} for `{_label_for(record.owner)}` "
  72. f"is shorter than glyph size {glyph_pt}; either grow the box or "
  73. "shrink value.size."
  74. )
  75. if len(findings) >= max_findings:
  76. findings.append("Too many findings; aborting further checks.")
  77. return True, findings
  78. if not failed:
  79. findings.append("SUCCESS: all bounding boxes look sane.")
  80. return failed, findings
  81. def main(argv: list[str] | None = None) -> int:
  82. parser = make_parser(
  83. "geometry_lint",
  84. "Validate bounding-box geometry inside a fields.json file.",
  85. )
  86. parser.add_argument("cfg_path", help="Path to fields.json.")
  87. parser.add_argument(
  88. "--max-findings",
  89. type=int,
  90. default=20,
  91. help="Stop reporting after this many findings (default 20).",
  92. )
  93. args = parser.parse_args(argv)
  94. failed, findings = lint(args.cfg_path, max_findings=args.max_findings)
  95. for line in findings:
  96. print(line)
  97. return 1 if failed else 0
  98. if __name__ == "__main__":
  99. sys.exit(main())