acroform_io.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """AcroForm metadata enumeration for the MiniMax PDF skill.
  2. The functions here produce the JSON-shaped records that the
  3. ``inspect`` and ``fill`` script groups consume. The schema is:
  4. [
  5. {
  6. "qname": str, # fully qualified field name
  7. "page_no": int, # 1-based page number
  8. "box": [l, b, r, t], # rectangle in PDF user space
  9. "type": "text" | "checkbox" | "radio_group" | "choice" | "unknown (...)",
  10. # type-specific extras:
  11. "on_value": str, # checkbox: the value that ticks the box
  12. "off_value": str, # checkbox: the value that unticks it
  13. "radio_choices": [...], # radio: [{"set_to": str, "box": [...]}]
  14. "choice_options": [...] # choice: [{"set_to": str, "label": str}]
  15. }
  16. ]
  17. The qname is the dotted path of every ``/T`` from the leaf annotation
  18. up to the root, joined with "." (so "address.line2" stays distinct
  19. from "shipping.line2"). When pypdf cannot resolve the parent chain we
  20. return ``None``.
  21. """
  22. from __future__ import annotations
  23. from typing import Any
  24. def resolve_full_qualified_name(annot: Any) -> str | None:
  25. """Walk the ``/Parent`` chain of an annotation/field and join names."""
  26. parts: list[str] = []
  27. cursor = annot
  28. while cursor is not None:
  29. leaf = cursor.get("/T")
  30. if leaf:
  31. parts.append(leaf)
  32. cursor = cursor.get("/Parent")
  33. if not parts:
  34. return None
  35. return ".".join(reversed(parts))
  36. def build_field_record(raw_field: Any, qname: str) -> dict:
  37. """Turn a pypdf field object into our JSON record (without box/page)."""
  38. record: dict = {"qname": qname}
  39. ft = raw_field.get("/FT")
  40. if ft == "/Tx":
  41. record["type"] = "text"
  42. elif ft == "/Btn":
  43. record["type"] = "checkbox"
  44. states = raw_field.get("/_States_", [])
  45. if len(states) == 2:
  46. if "/Off" in states:
  47. on = states[0] if states[0] != "/Off" else states[1]
  48. record["on_value"] = on
  49. record["off_value"] = "/Off"
  50. else:
  51. # Unusual two-state checkbox without an explicit /Off.
  52. # Fall back to positional guess and warn the caller.
  53. print(
  54. f"WARN: checkbox `{qname}` has non-standard states "
  55. f"{states}; verify the rendered PDF before relying on it."
  56. )
  57. record["on_value"] = states[0]
  58. record["off_value"] = states[1]
  59. elif ft == "/Ch":
  60. record["type"] = "choice"
  61. states = raw_field.get("/_States_", [])
  62. record["choice_options"] = [
  63. {"set_to": pair[0], "label": pair[1]} for pair in states
  64. ]
  65. else:
  66. record["type"] = f"unknown ({ft})"
  67. return record
  68. def enumerate_acroform_fields(pdf_doc) -> list[dict]:
  69. """Return every fillable field in reading order, with location info.
  70. ``pdf_doc`` is a ``pypdf.PdfReader``. Fields without a resolvable
  71. page/box are skipped with a printed warning so a caller scanning the
  72. JSON output never sees half-populated records.
  73. """
  74. raw_fields = pdf_doc.get_fields() or {}
  75. record_by_qname: dict[str, dict] = {}
  76. candidate_radio_qnames: set[str] = set()
  77. for qname, field in raw_fields.items():
  78. if field.get("/Kids"):
  79. if field.get("/FT") == "/Btn":
  80. candidate_radio_qnames.add(qname)
  81. continue
  82. record_by_qname[qname] = build_field_record(field, qname)
  83. radio_groups_by_qname: dict[str, dict] = {}
  84. for page_index, pg in enumerate(pdf_doc.pages):
  85. for ann in pg.get("/Annots", []):
  86. qname = resolve_full_qualified_name(ann)
  87. if qname in record_by_qname:
  88. record_by_qname[qname]["page_no"] = page_index + 1
  89. record_by_qname[qname]["box"] = ann.get("/Rect")
  90. elif qname in candidate_radio_qnames:
  91. try:
  92. on_states = [v for v in ann["/AP"]["/N"] if v != "/Off"]
  93. except KeyError:
  94. continue
  95. if len(on_states) != 1:
  96. continue
  97. box = ann.get("/Rect")
  98. if qname not in radio_groups_by_qname:
  99. radio_groups_by_qname[qname] = {
  100. "qname": qname,
  101. "type": "radio_group",
  102. "page_no": page_index + 1,
  103. "radio_choices": [],
  104. }
  105. radio_groups_by_qname[qname]["radio_choices"].append(
  106. {"set_to": on_states[0], "box": box}
  107. )
  108. placed_records: list[dict] = []
  109. for record in record_by_qname.values():
  110. if "page_no" in record:
  111. placed_records.append(record)
  112. else:
  113. print(
  114. f"WARN: cannot place field `{record.get('qname')}`, "
  115. "skipping it in the output."
  116. )
  117. def reading_order_key(rec: dict):
  118. if "radio_choices" in rec:
  119. box = rec["radio_choices"][0]["box"] or [0, 0, 0, 0]
  120. else:
  121. box = rec.get("box") or [0, 0, 0, 0]
  122. # sort top-to-bottom (negative y so larger y first), then left-to-right
  123. return [rec.get("page_no"), [-box[1], box[0]]]
  124. ordered_records = placed_records + list(radio_groups_by_qname.values())
  125. ordered_records.sort(key=reading_order_key)
  126. return ordered_records
  127. def patch_pypdf_inheritance() -> None:
  128. """Smooth over a pypdf quirk for choice fields.
  129. pypdf's ``DictionaryObject.get_inherited`` returns the raw ``/Opt``
  130. list which, for choice widgets that store ``[value, display]`` pairs,
  131. breaks downstream value validation. We unwrap the pair so callers see
  132. a flat list of valid values.
  133. """
  134. from pypdf.generic import DictionaryObject
  135. from pypdf.constants import FieldDictionaryAttributes
  136. original = DictionaryObject.get_inherited
  137. def patched(self, key: str, default=None):
  138. result = original(self, key, default)
  139. if key == FieldDictionaryAttributes.Opt:
  140. if isinstance(result, list) and all(
  141. isinstance(v, list) and len(v) == 2 for v in result
  142. ):
  143. result = [r[0] for r in result]
  144. return result
  145. DictionaryObject.get_inherited = patched