Skillfarm / skills · skillfarm.ai / converted / pdf / scripts / check_bounding_boxes.py
| 1 | from dataclasses import dataclass |
| 2 | import json |
| 3 | import sys |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | @dataclass |
| 9 | class RectAndField: |
| 10 | rect: list[float] |
| 11 | rect_type: str |
| 12 | field: dict |
| 13 | |
| 14 | |
| 15 | def get_bounding_box_messages(fields_json_stream) -> list[str]: |
| 16 | messages = [] |
| 17 | fields = json.load(fields_json_stream) |
| 18 | messages.append(f"Read {len(fields['form_fields'])} fields") |
| 19 | |
| 20 | def rects_intersect(r1, r2): |
| 21 | disjoint_horizontal = r1[0] >= r2[2] or r1[2] <= r2[0] |
| 22 | disjoint_vertical = r1[1] >= r2[3] or r1[3] <= r2[1] |
| 23 | return not (disjoint_horizontal or disjoint_vertical) |
| 24 | |
| 25 | rects_and_fields = [] |
| 26 | for f in fields["form_fields"]: |
| 27 | rects_and_fields.append(RectAndField(f["label_bounding_box"], "label", f)) |
| 28 | rects_and_fields.append(RectAndField(f["entry_bounding_box"], "entry", f)) |
| 29 | |
| 30 | has_error = False |
| 31 | for i, ri in enumerate(rects_and_fields): |
| 32 | for j in range(i + 1, len(rects_and_fields)): |
| 33 | rj = rects_and_fields[j] |
| 34 | if ri.field["page_number"] == rj.field["page_number"] and rects_intersect(ri.rect, rj.rect): |
| 35 | has_error = True |
| 36 | if ri.field is rj.field: |
| 37 | messages.append(f"FAILURE: intersection between label and entry bounding boxes for `{ri.field['description']}` ({ri.rect}, {rj.rect})") |
| 38 | else: |
| 39 | messages.append(f"FAILURE: intersection between {ri.rect_type} bounding box for `{ri.field['description']}` ({ri.rect}) and {rj.rect_type} bounding box for `{rj.field['description']}` ({rj.rect})") |
| 40 | if len(messages) >= 20: |
| 41 | messages.append("Aborting further checks; fix bounding boxes and try again") |
| 42 | return messages |
| 43 | if ri.rect_type == "entry": |
| 44 | if "entry_text" in ri.field: |
| 45 | font_size = ri.field["entry_text"].get("font_size", 14) |
| 46 | entry_height = ri.rect[3] - ri.rect[1] |
| 47 | if entry_height < font_size: |
| 48 | has_error = True |
| 49 | messages.append(f"FAILURE: entry bounding box height ({entry_height}) for `{ri.field['description']}` is too short for the text content (font size: {font_size}). Increase the box height or decrease the font size.") |
| 50 | if len(messages) >= 20: |
| 51 | messages.append("Aborting further checks; fix bounding boxes and try again") |
| 52 | return messages |
| 53 | |
| 54 | if not has_error: |
| 55 | messages.append("SUCCESS: All bounding boxes are valid") |
| 56 | return messages |
| 57 | |
| 58 | if __name__ == "__main__": |
| 59 | if len(sys.argv) != 2: |
| 60 | print("Usage: check_bounding_boxes.py [fields.json]") |
| 61 | sys.exit(1) |
| 62 | with open(sys.argv[1]) as f: |
| 63 | messages = get_bounding_box_messages(f) |
| 64 | for msg in messages: |
| 65 | print(msg) |