mercury-agent 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +452 -451
  2. package/container/Dockerfile +127 -127
  3. package/container/Dockerfile.base +109 -109
  4. package/container/Dockerfile.power +17 -17
  5. package/container/agent-package.json +8 -8
  6. package/container/build.sh +54 -54
  7. package/docs/ROADMAP.md +3 -4
  8. package/docs/archive/summarization/2026-07-02-recent-dev-summary.md +71 -0
  9. package/docs/auth/dashboard.md +28 -28
  10. package/docs/auth/overview.md +109 -109
  11. package/docs/auth/whatsapp.md +173 -173
  12. package/docs/authoring-profiles.md +174 -174
  13. package/docs/configuration.md +54 -54
  14. package/docs/container-lifecycle.md +349 -349
  15. package/docs/{bugs/bwrap-privileged-linux-docker.md → debug/major/2026-07-02-bwrap-privileged-linux-docker.md} +21 -1
  16. package/docs/{bugs/e2big-prompt-delivery-fix.md → debug/major/2026-07-02-e2big-prompt-delivery-fix.md} +27 -1
  17. package/docs/{bugs/registry-pull-no-local-fallback.md → debug/major/2026-07-02-registry-pull-no-local-fallback.md} +27 -1
  18. package/docs/debug/summarization/2026-07-02-common-bug-patterns.md +72 -0
  19. package/docs/deployment.md +199 -199
  20. package/docs/extensions.md +375 -375
  21. package/docs/graceful-shutdown.md +62 -62
  22. package/docs/kb-distillation.md +77 -77
  23. package/docs/media/overview.md +140 -140
  24. package/docs/media/whatsapp.md +171 -171
  25. package/docs/memory.md +137 -137
  26. package/docs/permissions.md +217 -217
  27. package/docs/pipeline.md +228 -228
  28. package/docs/prd-chat-memory.md +76 -76
  29. package/docs/prd-config-load.md +82 -82
  30. package/docs/rate-limiting.md +229 -229
  31. package/docs/runbooks/publish-checklist.md +9 -1
  32. package/docs/scheduler.md +288 -288
  33. package/docs/setup-discord.md +100 -100
  34. package/docs/setup-slack.md +119 -119
  35. package/docs/setup-whatsapp.md +94 -94
  36. package/docs/subagents.md +166 -166
  37. package/docs/web-search.md +62 -62
  38. package/examples/extensions/README.md +12 -12
  39. package/examples/extensions/charts/index.ts +13 -13
  40. package/examples/extensions/charts/skill/SKILL.md +98 -98
  41. package/examples/extensions/gws/README.md +52 -52
  42. package/examples/extensions/gws/skill/SKILL.md +57 -57
  43. package/examples/extensions/gws/skill/references/calendar.md +101 -101
  44. package/examples/extensions/gws/skill/references/docs.md +65 -65
  45. package/examples/extensions/gws/skill/references/drive.md +79 -79
  46. package/examples/extensions/gws/skill/references/gmail.md +85 -85
  47. package/examples/extensions/gws/skill/references/sheets.md +60 -60
  48. package/examples/extensions/napkin/skill/SKILL.md +728 -728
  49. package/examples/extensions/pdf/skill/LICENSE.txt +30 -30
  50. package/examples/extensions/pdf/skill/SKILL.md +314 -314
  51. package/examples/extensions/pdf/skill/forms.md +294 -294
  52. package/examples/extensions/pdf/skill/reference.md +611 -611
  53. package/examples/extensions/pdf/skill/scripts/check_bounding_boxes.py +65 -65
  54. package/examples/extensions/pdf/skill/scripts/check_fillable_fields.py +11 -11
  55. package/examples/extensions/pdf/skill/scripts/convert_pdf_to_images.py +33 -33
  56. package/examples/extensions/pdf/skill/scripts/create_validation_image.py +37 -37
  57. package/examples/extensions/pdf/skill/scripts/extract_form_field_info.py +122 -122
  58. package/examples/extensions/pdf/skill/scripts/extract_form_structure.py +115 -115
  59. package/examples/extensions/pdf/skill/scripts/fill_fillable_fields.py +98 -98
  60. package/examples/extensions/pdf/skill/scripts/fill_pdf_form_with_annotations.py +107 -107
  61. package/examples/extensions/permission-guard/index.ts +65 -65
  62. package/examples/extensions/pinchtab/skill/SKILL.md +224 -224
  63. package/examples/extensions/pinchtab/skill/TRUST.md +69 -69
  64. package/examples/extensions/pinchtab/skill/references/api.md +297 -297
  65. package/examples/extensions/pinchtab/skill/references/env.md +45 -45
  66. package/examples/extensions/pinchtab/skill/references/profiles.md +107 -107
  67. package/examples/extensions/tradestation/host/refresh.ts +102 -102
  68. package/examples/extensions/tradestation/index.ts +153 -153
  69. package/examples/extensions/tradestation/skill/SKILL.md +67 -67
  70. package/examples/extensions/voice-synth/index.ts +94 -94
  71. package/examples/extensions/voice-synth/skill/SKILL.md +38 -38
  72. package/examples/extensions/voice-transcribe/requirements.txt +8 -8
  73. package/examples/extensions/voice-transcribe/scripts/transcribe.py +179 -179
  74. package/examples/extensions/voice-transcribe/skill/SKILL.md +53 -53
  75. package/examples/extensions/yahoo-mail/cli/package.json +13 -13
  76. package/examples/extensions/yahoo-mail/skill/SKILL.md +78 -78
  77. package/package.json +106 -106
  78. package/resources/agents/explore.md +50 -50
  79. package/resources/agents/worker.md +24 -24
  80. package/resources/connection-env-vars.json +25 -25
  81. package/resources/pi-extensions/subagent/agents.ts +126 -126
  82. package/resources/pi-extensions/subagent/index.ts +964 -964
  83. package/resources/profiles/coding/AGENTS.md +43 -43
  84. package/resources/profiles/coding/mercury-profile.yaml +15 -15
  85. package/resources/profiles/general/AGENTS.md +31 -31
  86. package/resources/profiles/general/mercury-profile.yaml +15 -15
  87. package/resources/profiles/research/AGENTS.md +40 -40
  88. package/resources/profiles/research/mercury-profile.yaml +15 -15
  89. package/resources/skills/config/SKILL.md +25 -25
  90. package/resources/skills/context/SKILL.md +33 -33
  91. package/resources/skills/conversation-recap/SKILL.md +19 -19
  92. package/resources/skills/mutes/SKILL.md +31 -31
  93. package/resources/skills/permissions/SKILL.md +19 -19
  94. package/resources/skills/preferences/SKILL.md +31 -31
  95. package/resources/skills/recall/SKILL.md +24 -24
  96. package/resources/skills/roles/SKILL.md +18 -18
  97. package/resources/skills/spaces/SKILL.md +18 -18
  98. package/resources/skills/tasks/SKILL.md +45 -45
  99. package/resources/templates/AGENTS.md +157 -157
  100. package/resources/templates/env.template +38 -38
  101. package/resources/templates/mercury.example.yaml +99 -99
  102. package/src/agent/container-entry.ts +1 -1
  103. package/src/agent/container-runner.ts +1345 -1346
  104. package/src/cli/mercury.ts +39 -7
  105. package/src/cli/mrctl.ts +636 -636
  106. package/src/config-file.ts +540 -540
  107. package/src/config.ts +339 -339
  108. package/src/core/api.ts +125 -125
  109. package/src/core/caller-token.ts +101 -101
  110. package/src/core/permissions.ts +228 -228
  111. package/src/core/profiles.ts +271 -271
  112. package/src/core/routes/capability.ts +70 -70
  113. package/src/core/routes/index.ts +15 -15
  114. package/src/core/runtime.ts +1530 -1530
  115. package/src/dashboard/index.html +729 -729
  116. package/src/extensions/api.ts +273 -273
  117. package/src/extensions/loader.ts +286 -286
  118. package/src/extensions/types.ts +517 -517
  119. package/src/main.ts +605 -605
  120. package/docs/pending-updates/applicative-profiles.md +0 -15
  121. package/docs/pending-updates/caller-bound-capability-token.md +0 -15
  122. package/docs/pending-updates/dm-auto-space.md +0 -15
  123. /package/docs/archive/{2026-07-01-applicative-profiles.md → applicative-profiles/2026-07-01-applicative-profiles.md} +0 -0
  124. /package/docs/archive/{2026-07-01-caller-bound-capability-token.md → applicative-profiles/2026-07-01-caller-bound-capability-token.md} +0 -0
  125. /package/docs/archive/{2026-07-01-dm-auto-space.md → applicative-profiles/2026-07-01-dm-auto-space.md} +0 -0
@@ -1,115 +1,115 @@
1
- """
2
- Extract form structure from a non-fillable PDF.
3
-
4
- This script analyzes the PDF to find:
5
- - Text labels with their exact coordinates
6
- - Horizontal lines (row boundaries)
7
- - Checkboxes (small rectangles)
8
-
9
- Output: A JSON file with the form structure that can be used to generate
10
- accurate field coordinates for filling.
11
-
12
- Usage: python extract_form_structure.py <input.pdf> <output.json>
13
- """
14
-
15
- import json
16
- import sys
17
- import pdfplumber
18
-
19
-
20
- def extract_form_structure(pdf_path):
21
- structure = {
22
- "pages": [],
23
- "labels": [],
24
- "lines": [],
25
- "checkboxes": [],
26
- "row_boundaries": []
27
- }
28
-
29
- with pdfplumber.open(pdf_path) as pdf:
30
- for page_num, page in enumerate(pdf.pages, 1):
31
- structure["pages"].append({
32
- "page_number": page_num,
33
- "width": float(page.width),
34
- "height": float(page.height)
35
- })
36
-
37
- words = page.extract_words()
38
- for word in words:
39
- structure["labels"].append({
40
- "page": page_num,
41
- "text": word["text"],
42
- "x0": round(float(word["x0"]), 1),
43
- "top": round(float(word["top"]), 1),
44
- "x1": round(float(word["x1"]), 1),
45
- "bottom": round(float(word["bottom"]), 1)
46
- })
47
-
48
- for line in page.lines:
49
- if abs(float(line["x1"]) - float(line["x0"])) > page.width * 0.5:
50
- structure["lines"].append({
51
- "page": page_num,
52
- "y": round(float(line["top"]), 1),
53
- "x0": round(float(line["x0"]), 1),
54
- "x1": round(float(line["x1"]), 1)
55
- })
56
-
57
- for rect in page.rects:
58
- width = float(rect["x1"]) - float(rect["x0"])
59
- height = float(rect["bottom"]) - float(rect["top"])
60
- if 5 <= width <= 15 and 5 <= height <= 15 and abs(width - height) < 2:
61
- structure["checkboxes"].append({
62
- "page": page_num,
63
- "x0": round(float(rect["x0"]), 1),
64
- "top": round(float(rect["top"]), 1),
65
- "x1": round(float(rect["x1"]), 1),
66
- "bottom": round(float(rect["bottom"]), 1),
67
- "center_x": round((float(rect["x0"]) + float(rect["x1"])) / 2, 1),
68
- "center_y": round((float(rect["top"]) + float(rect["bottom"])) / 2, 1)
69
- })
70
-
71
- lines_by_page = {}
72
- for line in structure["lines"]:
73
- page = line["page"]
74
- if page not in lines_by_page:
75
- lines_by_page[page] = []
76
- lines_by_page[page].append(line["y"])
77
-
78
- for page, y_coords in lines_by_page.items():
79
- y_coords = sorted(set(y_coords))
80
- for i in range(len(y_coords) - 1):
81
- structure["row_boundaries"].append({
82
- "page": page,
83
- "row_top": y_coords[i],
84
- "row_bottom": y_coords[i + 1],
85
- "row_height": round(y_coords[i + 1] - y_coords[i], 1)
86
- })
87
-
88
- return structure
89
-
90
-
91
- def main():
92
- if len(sys.argv) != 3:
93
- print("Usage: extract_form_structure.py <input.pdf> <output.json>")
94
- sys.exit(1)
95
-
96
- pdf_path = sys.argv[1]
97
- output_path = sys.argv[2]
98
-
99
- print(f"Extracting structure from {pdf_path}...")
100
- structure = extract_form_structure(pdf_path)
101
-
102
- with open(output_path, "w") as f:
103
- json.dump(structure, f, indent=2)
104
-
105
- print(f"Found:")
106
- print(f" - {len(structure['pages'])} pages")
107
- print(f" - {len(structure['labels'])} text labels")
108
- print(f" - {len(structure['lines'])} horizontal lines")
109
- print(f" - {len(structure['checkboxes'])} checkboxes")
110
- print(f" - {len(structure['row_boundaries'])} row boundaries")
111
- print(f"Saved to {output_path}")
112
-
113
-
114
- if __name__ == "__main__":
115
- main()
1
+ """
2
+ Extract form structure from a non-fillable PDF.
3
+
4
+ This script analyzes the PDF to find:
5
+ - Text labels with their exact coordinates
6
+ - Horizontal lines (row boundaries)
7
+ - Checkboxes (small rectangles)
8
+
9
+ Output: A JSON file with the form structure that can be used to generate
10
+ accurate field coordinates for filling.
11
+
12
+ Usage: python extract_form_structure.py <input.pdf> <output.json>
13
+ """
14
+
15
+ import json
16
+ import sys
17
+ import pdfplumber
18
+
19
+
20
+ def extract_form_structure(pdf_path):
21
+ structure = {
22
+ "pages": [],
23
+ "labels": [],
24
+ "lines": [],
25
+ "checkboxes": [],
26
+ "row_boundaries": []
27
+ }
28
+
29
+ with pdfplumber.open(pdf_path) as pdf:
30
+ for page_num, page in enumerate(pdf.pages, 1):
31
+ structure["pages"].append({
32
+ "page_number": page_num,
33
+ "width": float(page.width),
34
+ "height": float(page.height)
35
+ })
36
+
37
+ words = page.extract_words()
38
+ for word in words:
39
+ structure["labels"].append({
40
+ "page": page_num,
41
+ "text": word["text"],
42
+ "x0": round(float(word["x0"]), 1),
43
+ "top": round(float(word["top"]), 1),
44
+ "x1": round(float(word["x1"]), 1),
45
+ "bottom": round(float(word["bottom"]), 1)
46
+ })
47
+
48
+ for line in page.lines:
49
+ if abs(float(line["x1"]) - float(line["x0"])) > page.width * 0.5:
50
+ structure["lines"].append({
51
+ "page": page_num,
52
+ "y": round(float(line["top"]), 1),
53
+ "x0": round(float(line["x0"]), 1),
54
+ "x1": round(float(line["x1"]), 1)
55
+ })
56
+
57
+ for rect in page.rects:
58
+ width = float(rect["x1"]) - float(rect["x0"])
59
+ height = float(rect["bottom"]) - float(rect["top"])
60
+ if 5 <= width <= 15 and 5 <= height <= 15 and abs(width - height) < 2:
61
+ structure["checkboxes"].append({
62
+ "page": page_num,
63
+ "x0": round(float(rect["x0"]), 1),
64
+ "top": round(float(rect["top"]), 1),
65
+ "x1": round(float(rect["x1"]), 1),
66
+ "bottom": round(float(rect["bottom"]), 1),
67
+ "center_x": round((float(rect["x0"]) + float(rect["x1"])) / 2, 1),
68
+ "center_y": round((float(rect["top"]) + float(rect["bottom"])) / 2, 1)
69
+ })
70
+
71
+ lines_by_page = {}
72
+ for line in structure["lines"]:
73
+ page = line["page"]
74
+ if page not in lines_by_page:
75
+ lines_by_page[page] = []
76
+ lines_by_page[page].append(line["y"])
77
+
78
+ for page, y_coords in lines_by_page.items():
79
+ y_coords = sorted(set(y_coords))
80
+ for i in range(len(y_coords) - 1):
81
+ structure["row_boundaries"].append({
82
+ "page": page,
83
+ "row_top": y_coords[i],
84
+ "row_bottom": y_coords[i + 1],
85
+ "row_height": round(y_coords[i + 1] - y_coords[i], 1)
86
+ })
87
+
88
+ return structure
89
+
90
+
91
+ def main():
92
+ if len(sys.argv) != 3:
93
+ print("Usage: extract_form_structure.py <input.pdf> <output.json>")
94
+ sys.exit(1)
95
+
96
+ pdf_path = sys.argv[1]
97
+ output_path = sys.argv[2]
98
+
99
+ print(f"Extracting structure from {pdf_path}...")
100
+ structure = extract_form_structure(pdf_path)
101
+
102
+ with open(output_path, "w") as f:
103
+ json.dump(structure, f, indent=2)
104
+
105
+ print(f"Found:")
106
+ print(f" - {len(structure['pages'])} pages")
107
+ print(f" - {len(structure['labels'])} text labels")
108
+ print(f" - {len(structure['lines'])} horizontal lines")
109
+ print(f" - {len(structure['checkboxes'])} checkboxes")
110
+ print(f" - {len(structure['row_boundaries'])} row boundaries")
111
+ print(f"Saved to {output_path}")
112
+
113
+
114
+ if __name__ == "__main__":
115
+ main()
@@ -1,98 +1,98 @@
1
- import json
2
- import sys
3
-
4
- from pypdf import PdfReader, PdfWriter
5
-
6
- from extract_form_field_info import get_field_info
7
-
8
-
9
-
10
-
11
- def fill_pdf_fields(input_pdf_path: str, fields_json_path: str, output_pdf_path: str):
12
- with open(fields_json_path) as f:
13
- fields = json.load(f)
14
- fields_by_page = {}
15
- for field in fields:
16
- if "value" in field:
17
- field_id = field["field_id"]
18
- page = field["page"]
19
- if page not in fields_by_page:
20
- fields_by_page[page] = {}
21
- fields_by_page[page][field_id] = field["value"]
22
-
23
- reader = PdfReader(input_pdf_path)
24
-
25
- has_error = False
26
- field_info = get_field_info(reader)
27
- fields_by_ids = {f["field_id"]: f for f in field_info}
28
- for field in fields:
29
- existing_field = fields_by_ids.get(field["field_id"])
30
- if not existing_field:
31
- has_error = True
32
- print(f"ERROR: `{field['field_id']}` is not a valid field ID")
33
- elif field["page"] != existing_field["page"]:
34
- has_error = True
35
- print(f"ERROR: Incorrect page number for `{field['field_id']}` (got {field['page']}, expected {existing_field['page']})")
36
- else:
37
- if "value" in field:
38
- err = validation_error_for_field_value(existing_field, field["value"])
39
- if err:
40
- print(err)
41
- has_error = True
42
- if has_error:
43
- sys.exit(1)
44
-
45
- writer = PdfWriter(clone_from=reader)
46
- for page, field_values in fields_by_page.items():
47
- writer.update_page_form_field_values(writer.pages[page - 1], field_values, auto_regenerate=False)
48
-
49
- writer.set_need_appearances_writer(True)
50
-
51
- with open(output_pdf_path, "wb") as f:
52
- writer.write(f)
53
-
54
-
55
- def validation_error_for_field_value(field_info, field_value):
56
- field_type = field_info["type"]
57
- field_id = field_info["field_id"]
58
- if field_type == "checkbox":
59
- checked_val = field_info["checked_value"]
60
- unchecked_val = field_info["unchecked_value"]
61
- if field_value != checked_val and field_value != unchecked_val:
62
- return f'ERROR: Invalid value "{field_value}" for checkbox field "{field_id}". The checked value is "{checked_val}" and the unchecked value is "{unchecked_val}"'
63
- elif field_type == "radio_group":
64
- option_values = [opt["value"] for opt in field_info["radio_options"]]
65
- if field_value not in option_values:
66
- return f'ERROR: Invalid value "{field_value}" for radio group field "{field_id}". Valid values are: {option_values}'
67
- elif field_type == "choice":
68
- choice_values = [opt["value"] for opt in field_info["choice_options"]]
69
- if field_value not in choice_values:
70
- return f'ERROR: Invalid value "{field_value}" for choice field "{field_id}". Valid values are: {choice_values}'
71
- return None
72
-
73
-
74
- def monkeypatch_pydpf_method():
75
- from pypdf.generic import DictionaryObject
76
- from pypdf.constants import FieldDictionaryAttributes
77
-
78
- original_get_inherited = DictionaryObject.get_inherited
79
-
80
- def patched_get_inherited(self, key: str, default = None):
81
- result = original_get_inherited(self, key, default)
82
- if key == FieldDictionaryAttributes.Opt:
83
- if isinstance(result, list) and all(isinstance(v, list) and len(v) == 2 for v in result):
84
- result = [r[0] for r in result]
85
- return result
86
-
87
- DictionaryObject.get_inherited = patched_get_inherited
88
-
89
-
90
- if __name__ == "__main__":
91
- if len(sys.argv) != 4:
92
- print("Usage: fill_fillable_fields.py [input pdf] [field_values.json] [output pdf]")
93
- sys.exit(1)
94
- monkeypatch_pydpf_method()
95
- input_pdf = sys.argv[1]
96
- fields_json = sys.argv[2]
97
- output_pdf = sys.argv[3]
98
- fill_pdf_fields(input_pdf, fields_json, output_pdf)
1
+ import json
2
+ import sys
3
+
4
+ from pypdf import PdfReader, PdfWriter
5
+
6
+ from extract_form_field_info import get_field_info
7
+
8
+
9
+
10
+
11
+ def fill_pdf_fields(input_pdf_path: str, fields_json_path: str, output_pdf_path: str):
12
+ with open(fields_json_path) as f:
13
+ fields = json.load(f)
14
+ fields_by_page = {}
15
+ for field in fields:
16
+ if "value" in field:
17
+ field_id = field["field_id"]
18
+ page = field["page"]
19
+ if page not in fields_by_page:
20
+ fields_by_page[page] = {}
21
+ fields_by_page[page][field_id] = field["value"]
22
+
23
+ reader = PdfReader(input_pdf_path)
24
+
25
+ has_error = False
26
+ field_info = get_field_info(reader)
27
+ fields_by_ids = {f["field_id"]: f for f in field_info}
28
+ for field in fields:
29
+ existing_field = fields_by_ids.get(field["field_id"])
30
+ if not existing_field:
31
+ has_error = True
32
+ print(f"ERROR: `{field['field_id']}` is not a valid field ID")
33
+ elif field["page"] != existing_field["page"]:
34
+ has_error = True
35
+ print(f"ERROR: Incorrect page number for `{field['field_id']}` (got {field['page']}, expected {existing_field['page']})")
36
+ else:
37
+ if "value" in field:
38
+ err = validation_error_for_field_value(existing_field, field["value"])
39
+ if err:
40
+ print(err)
41
+ has_error = True
42
+ if has_error:
43
+ sys.exit(1)
44
+
45
+ writer = PdfWriter(clone_from=reader)
46
+ for page, field_values in fields_by_page.items():
47
+ writer.update_page_form_field_values(writer.pages[page - 1], field_values, auto_regenerate=False)
48
+
49
+ writer.set_need_appearances_writer(True)
50
+
51
+ with open(output_pdf_path, "wb") as f:
52
+ writer.write(f)
53
+
54
+
55
+ def validation_error_for_field_value(field_info, field_value):
56
+ field_type = field_info["type"]
57
+ field_id = field_info["field_id"]
58
+ if field_type == "checkbox":
59
+ checked_val = field_info["checked_value"]
60
+ unchecked_val = field_info["unchecked_value"]
61
+ if field_value != checked_val and field_value != unchecked_val:
62
+ return f'ERROR: Invalid value "{field_value}" for checkbox field "{field_id}". The checked value is "{checked_val}" and the unchecked value is "{unchecked_val}"'
63
+ elif field_type == "radio_group":
64
+ option_values = [opt["value"] for opt in field_info["radio_options"]]
65
+ if field_value not in option_values:
66
+ return f'ERROR: Invalid value "{field_value}" for radio group field "{field_id}". Valid values are: {option_values}'
67
+ elif field_type == "choice":
68
+ choice_values = [opt["value"] for opt in field_info["choice_options"]]
69
+ if field_value not in choice_values:
70
+ return f'ERROR: Invalid value "{field_value}" for choice field "{field_id}". Valid values are: {choice_values}'
71
+ return None
72
+
73
+
74
+ def monkeypatch_pydpf_method():
75
+ from pypdf.generic import DictionaryObject
76
+ from pypdf.constants import FieldDictionaryAttributes
77
+
78
+ original_get_inherited = DictionaryObject.get_inherited
79
+
80
+ def patched_get_inherited(self, key: str, default = None):
81
+ result = original_get_inherited(self, key, default)
82
+ if key == FieldDictionaryAttributes.Opt:
83
+ if isinstance(result, list) and all(isinstance(v, list) and len(v) == 2 for v in result):
84
+ result = [r[0] for r in result]
85
+ return result
86
+
87
+ DictionaryObject.get_inherited = patched_get_inherited
88
+
89
+
90
+ if __name__ == "__main__":
91
+ if len(sys.argv) != 4:
92
+ print("Usage: fill_fillable_fields.py [input pdf] [field_values.json] [output pdf]")
93
+ sys.exit(1)
94
+ monkeypatch_pydpf_method()
95
+ input_pdf = sys.argv[1]
96
+ fields_json = sys.argv[2]
97
+ output_pdf = sys.argv[3]
98
+ fill_pdf_fields(input_pdf, fields_json, output_pdf)
@@ -1,107 +1,107 @@
1
- import json
2
- import sys
3
-
4
- from pypdf import PdfReader, PdfWriter
5
- from pypdf.annotations import FreeText
6
-
7
-
8
-
9
-
10
- def transform_from_image_coords(bbox, image_width, image_height, pdf_width, pdf_height):
11
- x_scale = pdf_width / image_width
12
- y_scale = pdf_height / image_height
13
-
14
- left = bbox[0] * x_scale
15
- right = bbox[2] * x_scale
16
-
17
- top = pdf_height - (bbox[1] * y_scale)
18
- bottom = pdf_height - (bbox[3] * y_scale)
19
-
20
- return left, bottom, right, top
21
-
22
-
23
- def transform_from_pdf_coords(bbox, pdf_height):
24
- left = bbox[0]
25
- right = bbox[2]
26
-
27
- pypdf_top = pdf_height - bbox[1]
28
- pypdf_bottom = pdf_height - bbox[3]
29
-
30
- return left, pypdf_bottom, right, pypdf_top
31
-
32
-
33
- def fill_pdf_form(input_pdf_path, fields_json_path, output_pdf_path):
34
-
35
- with open(fields_json_path, "r") as f:
36
- fields_data = json.load(f)
37
-
38
- reader = PdfReader(input_pdf_path)
39
- writer = PdfWriter()
40
-
41
- writer.append(reader)
42
-
43
- pdf_dimensions = {}
44
- for i, page in enumerate(reader.pages):
45
- mediabox = page.mediabox
46
- pdf_dimensions[i + 1] = [mediabox.width, mediabox.height]
47
-
48
- annotations = []
49
- for field in fields_data["form_fields"]:
50
- page_num = field["page_number"]
51
-
52
- page_info = next(p for p in fields_data["pages"] if p["page_number"] == page_num)
53
- pdf_width, pdf_height = pdf_dimensions[page_num]
54
-
55
- if "pdf_width" in page_info:
56
- transformed_entry_box = transform_from_pdf_coords(
57
- field["entry_bounding_box"],
58
- float(pdf_height)
59
- )
60
- else:
61
- image_width = page_info["image_width"]
62
- image_height = page_info["image_height"]
63
- transformed_entry_box = transform_from_image_coords(
64
- field["entry_bounding_box"],
65
- image_width, image_height,
66
- float(pdf_width), float(pdf_height)
67
- )
68
-
69
- if "entry_text" not in field or "text" not in field["entry_text"]:
70
- continue
71
- entry_text = field["entry_text"]
72
- text = entry_text["text"]
73
- if not text:
74
- continue
75
-
76
- font_name = entry_text.get("font", "Arial")
77
- font_size = str(entry_text.get("font_size", 14)) + "pt"
78
- font_color = entry_text.get("font_color", "000000")
79
-
80
- annotation = FreeText(
81
- text=text,
82
- rect=transformed_entry_box,
83
- font=font_name,
84
- font_size=font_size,
85
- font_color=font_color,
86
- border_color=None,
87
- background_color=None,
88
- )
89
- annotations.append(annotation)
90
- writer.add_annotation(page_number=page_num - 1, annotation=annotation)
91
-
92
- with open(output_pdf_path, "wb") as output:
93
- writer.write(output)
94
-
95
- print(f"Successfully filled PDF form and saved to {output_pdf_path}")
96
- print(f"Added {len(annotations)} text annotations")
97
-
98
-
99
- if __name__ == "__main__":
100
- if len(sys.argv) != 4:
101
- print("Usage: fill_pdf_form_with_annotations.py [input pdf] [fields.json] [output pdf]")
102
- sys.exit(1)
103
- input_pdf = sys.argv[1]
104
- fields_json = sys.argv[2]
105
- output_pdf = sys.argv[3]
106
-
107
- fill_pdf_form(input_pdf, fields_json, output_pdf)
1
+ import json
2
+ import sys
3
+
4
+ from pypdf import PdfReader, PdfWriter
5
+ from pypdf.annotations import FreeText
6
+
7
+
8
+
9
+
10
+ def transform_from_image_coords(bbox, image_width, image_height, pdf_width, pdf_height):
11
+ x_scale = pdf_width / image_width
12
+ y_scale = pdf_height / image_height
13
+
14
+ left = bbox[0] * x_scale
15
+ right = bbox[2] * x_scale
16
+
17
+ top = pdf_height - (bbox[1] * y_scale)
18
+ bottom = pdf_height - (bbox[3] * y_scale)
19
+
20
+ return left, bottom, right, top
21
+
22
+
23
+ def transform_from_pdf_coords(bbox, pdf_height):
24
+ left = bbox[0]
25
+ right = bbox[2]
26
+
27
+ pypdf_top = pdf_height - bbox[1]
28
+ pypdf_bottom = pdf_height - bbox[3]
29
+
30
+ return left, pypdf_bottom, right, pypdf_top
31
+
32
+
33
+ def fill_pdf_form(input_pdf_path, fields_json_path, output_pdf_path):
34
+
35
+ with open(fields_json_path, "r") as f:
36
+ fields_data = json.load(f)
37
+
38
+ reader = PdfReader(input_pdf_path)
39
+ writer = PdfWriter()
40
+
41
+ writer.append(reader)
42
+
43
+ pdf_dimensions = {}
44
+ for i, page in enumerate(reader.pages):
45
+ mediabox = page.mediabox
46
+ pdf_dimensions[i + 1] = [mediabox.width, mediabox.height]
47
+
48
+ annotations = []
49
+ for field in fields_data["form_fields"]:
50
+ page_num = field["page_number"]
51
+
52
+ page_info = next(p for p in fields_data["pages"] if p["page_number"] == page_num)
53
+ pdf_width, pdf_height = pdf_dimensions[page_num]
54
+
55
+ if "pdf_width" in page_info:
56
+ transformed_entry_box = transform_from_pdf_coords(
57
+ field["entry_bounding_box"],
58
+ float(pdf_height)
59
+ )
60
+ else:
61
+ image_width = page_info["image_width"]
62
+ image_height = page_info["image_height"]
63
+ transformed_entry_box = transform_from_image_coords(
64
+ field["entry_bounding_box"],
65
+ image_width, image_height,
66
+ float(pdf_width), float(pdf_height)
67
+ )
68
+
69
+ if "entry_text" not in field or "text" not in field["entry_text"]:
70
+ continue
71
+ entry_text = field["entry_text"]
72
+ text = entry_text["text"]
73
+ if not text:
74
+ continue
75
+
76
+ font_name = entry_text.get("font", "Arial")
77
+ font_size = str(entry_text.get("font_size", 14)) + "pt"
78
+ font_color = entry_text.get("font_color", "000000")
79
+
80
+ annotation = FreeText(
81
+ text=text,
82
+ rect=transformed_entry_box,
83
+ font=font_name,
84
+ font_size=font_size,
85
+ font_color=font_color,
86
+ border_color=None,
87
+ background_color=None,
88
+ )
89
+ annotations.append(annotation)
90
+ writer.add_annotation(page_number=page_num - 1, annotation=annotation)
91
+
92
+ with open(output_pdf_path, "wb") as output:
93
+ writer.write(output)
94
+
95
+ print(f"Successfully filled PDF form and saved to {output_pdf_path}")
96
+ print(f"Added {len(annotations)} text annotations")
97
+
98
+
99
+ if __name__ == "__main__":
100
+ if len(sys.argv) != 4:
101
+ print("Usage: fill_pdf_form_with_annotations.py [input pdf] [fields.json] [output pdf]")
102
+ sys.exit(1)
103
+ input_pdf = sys.argv[1]
104
+ fields_json = sys.argv[2]
105
+ output_pdf = sys.argv[3]
106
+
107
+ fill_pdf_form(input_pdf, fields_json, output_pdf)