@arnilo/prism-tools 0.0.0-stage → 0.13.1
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.
- package/CHANGELOG.md +418 -0
- package/LICENSE +21 -0
- package/README.md +44 -2
- package/browser/README.md +98 -0
- package/browser/skills/browser-automation/SKILL.md +14 -0
- package/browser/src/actions/cdp.ts +131 -0
- package/browser/src/actions/dialog.ts +25 -0
- package/browser/src/actions/download_release.ts +22 -0
- package/browser/src/actions/index.ts +37 -0
- package/browser/src/actions/locator.ts +70 -0
- package/browser/src/actions/navigate.ts +23 -0
- package/browser/src/actions/screenshot.ts +27 -0
- package/browser/src/actions/scroll.ts +24 -0
- package/browser/src/actions/select_page.ts +21 -0
- package/browser/src/actions/types.ts +114 -0
- package/browser/src/actions/upload.ts +44 -0
- package/browser/src/actions/wait.ts +45 -0
- package/browser/src/browser.ts +197 -0
- package/browser/src/cdp.ts +178 -0
- package/browser/src/checkpoint.ts +189 -0
- package/browser/src/config.ts +72 -0
- package/browser/src/downloads.ts +253 -0
- package/browser/src/errors.ts +31 -0
- package/browser/src/evaluate.ts +101 -0
- package/browser/src/index.ts +129 -0
- package/browser/src/limits.ts +271 -0
- package/browser/src/manager.ts +730 -0
- package/browser/src/network.ts +263 -0
- package/browser/src/observe.ts +178 -0
- package/browser/src/policy.ts +133 -0
- package/browser/src/screenshot.ts +107 -0
- package/browser/src/shared-sandbox.ts +53 -0
- package/browser/src/snapshot.ts +99 -0
- package/browser/src/targets.ts +165 -0
- package/browser/src/tools.ts +480 -0
- package/browser/src/types.ts +316 -0
- package/browser/src/uploads.ts +174 -0
- package/coding/README.md +337 -0
- package/coding/src/agent/acp-operations.ts +146 -0
- package/coding/src/agent/artifacts.ts +38 -0
- package/coding/src/agent/ask-user-decision.ts +623 -0
- package/coding/src/agent/atomic-write.ts +23 -0
- package/coding/src/agent/bounded-file.ts +21 -0
- package/coding/src/agent/checks.ts +301 -0
- package/coding/src/agent/coding-checkpoint.ts +828 -0
- package/coding/src/agent/delete.ts +237 -0
- package/coding/src/agent/diagnostics-tool.ts +163 -0
- package/coding/src/agent/diagnostics.ts +262 -0
- package/coding/src/agent/edit-diff.ts +382 -0
- package/coding/src/agent/edit.ts +322 -0
- package/coding/src/agent/effects.ts +102 -0
- package/coding/src/agent/env.ts +28 -0
- package/coding/src/agent/execution-policy.ts +89 -0
- package/coding/src/agent/file-mutation-queue.ts +72 -0
- package/coding/src/agent/forge/github.ts +603 -0
- package/coding/src/agent/forge/index.ts +16 -0
- package/coding/src/agent/forge/types.ts +185 -0
- package/coding/src/agent/git-aware-repository.ts +305 -0
- package/coding/src/agent/git-exec.ts +326 -0
- package/coding/src/agent/git-status.ts +177 -0
- package/coding/src/agent/git-tools.ts +360 -0
- package/coding/src/agent/git.ts +1074 -0
- package/coding/src/agent/glob-match.ts +146 -0
- package/coding/src/agent/glob.ts +182 -0
- package/coding/src/agent/goal-verify.ts +385 -0
- package/coding/src/agent/grep-worker.ts +74 -0
- package/coding/src/agent/grep.ts +459 -0
- package/coding/src/agent/identity.ts +48 -0
- package/coding/src/agent/index.ts +676 -0
- package/coding/src/agent/language/client.ts +429 -0
- package/coding/src/agent/language/framing.ts +190 -0
- package/coding/src/agent/language/index.ts +23 -0
- package/coding/src/agent/language/intelligence.ts +682 -0
- package/coding/src/agent/language/types.ts +187 -0
- package/coding/src/agent/lifecycle-events.ts +121 -0
- package/coding/src/agent/lifecycle.ts +166 -0
- package/coding/src/agent/limits.ts +214 -0
- package/coding/src/agent/move.ts +178 -0
- package/coding/src/agent/mutation-path.ts +52 -0
- package/coding/src/agent/output-accumulator.ts +304 -0
- package/coding/src/agent/path-utils.ts +120 -0
- package/coding/src/agent/process/index.ts +58 -0
- package/coding/src/agent/process/recovery.ts +508 -0
- package/coding/src/agent/process/sessions-host.ts +222 -0
- package/coding/src/agent/process/sessions-monitor.ts +141 -0
- package/coding/src/agent/process/sessions-recovery.ts +241 -0
- package/coding/src/agent/process/sessions-spawn.ts +613 -0
- package/coding/src/agent/process/sessions-teardown.ts +281 -0
- package/coding/src/agent/process/sessions.ts +30 -0
- package/coding/src/agent/process/types.ts +358 -0
- package/coding/src/agent/read-path-set.ts +126 -0
- package/coding/src/agent/read.ts +713 -0
- package/coding/src/agent/repository/glob.ts +147 -0
- package/coding/src/agent/repository/indexed-search.ts +480 -0
- package/coding/src/agent/repository/list.ts +131 -0
- package/coding/src/agent/repository/operations.ts +22 -0
- package/coding/src/agent/repository/path.ts +98 -0
- package/coding/src/agent/repository/search.ts +277 -0
- package/coding/src/agent/repository/types.ts +243 -0
- package/coding/src/agent/repository/walk.ts +126 -0
- package/coding/src/agent/repository.ts +12 -0
- package/coding/src/agent/shell-background.ts +264 -0
- package/coding/src/agent/shell-output.ts +75 -0
- package/coding/src/agent/shell.ts +526 -0
- package/coding/src/agent/todo.ts +399 -0
- package/coding/src/agent/truncate.ts +251 -0
- package/coding/src/agent/write.ts +170 -0
- package/coding/src/ask-user-host.ts +48 -0
- package/coding/src/config.ts +278 -0
- package/coding/src/hard-deny.ts +97 -0
- package/coding/src/index.ts +318 -0
- package/coding/src/principal-guard.ts +84 -0
- package/coding/src/sandbox.ts +92 -0
- package/coding/src/security/approval.ts +144 -0
- package/coding/src/security/command-rules.ts +57 -0
- package/coding/src/security/docker-cli.ts +222 -0
- package/coding/src/security/docker-sandbox.ts +1205 -0
- package/coding/src/security/e2b-sandbox.ts +853 -0
- package/coding/src/security/egress/dns-pin.ts +88 -0
- package/coding/src/security/egress/index.ts +32 -0
- package/coding/src/security/egress/limits.ts +57 -0
- package/coding/src/security/egress/policy.ts +137 -0
- package/coding/src/security/egress/proxy.ts +599 -0
- package/coding/src/security/egress/types.ts +30 -0
- package/coding/src/security/index.ts +199 -0
- package/coding/src/security/native-sandbox.ts +639 -0
- package/coding/src/security/path-containment.ts +55 -0
- package/coding/src/security/sandbox-coding-operations.ts +392 -0
- package/coding/src/security/sandbox-fs-operations.ts +644 -0
- package/coding/src/security/sandbox-limits.ts +147 -0
- package/coding/src/security/sandbox-tar.ts +308 -0
- package/coding/src/security/sandbox.ts +179 -0
- package/coding/src/security/semaphore.ts +55 -0
- package/coding/src/targets.ts +110 -0
- package/coding/src/workspace/diff.ts +78 -0
- package/coding/src/workspace/errors.ts +29 -0
- package/coding/src/workspace/index.ts +5 -0
- package/coding/src/workspace/merge.ts +151 -0
- package/coding/src/workspace/routing.ts +76 -0
- package/coding/src/workspace/service.ts +584 -0
- package/computer-use/README.md +105 -0
- package/computer-use/skills/computer-use-linux/SKILL.md +17 -0
- package/computer-use/src/classify.ts +53 -0
- package/computer-use/src/command.ts +29 -0
- package/computer-use/src/config.ts +69 -0
- package/computer-use/src/create.ts +170 -0
- package/computer-use/src/devices.ts +247 -0
- package/computer-use/src/env.ts +28 -0
- package/computer-use/src/index.ts +157 -0
- package/computer-use/src/skill.ts +21 -0
- package/openapi/README.md +97 -0
- package/openapi/src/compile.ts +386 -0
- package/openapi/src/config.ts +73 -0
- package/openapi/src/errors.ts +16 -0
- package/openapi/src/execute.ts +241 -0
- package/openapi/src/index.ts +124 -0
- package/openapi/src/limits.ts +63 -0
- package/openapi/src/specs.ts +86 -0
- package/openapi/src/tools.ts +60 -0
- package/openapi/src/types.ts +61 -0
- package/package.json +171 -4
- package/research/README.md +72 -0
- package/research/skills/research-report/SKILL.md +12 -0
- package/research/skills/research-scoping/SKILL.md +10 -0
- package/research/skills/research-synthesis/SKILL.md +10 -0
- package/research/skills/source-triage/SKILL.md +10 -0
- package/research/src/check.ts +71 -0
- package/research/src/config.ts +41 -0
- package/research/src/index.ts +147 -0
- package/research/src/ledger.ts +157 -0
- package/research/src/urls.ts +21 -0
- package/web/README.md +287 -0
- package/web/skills/web-research/SKILL.md +17 -0
- package/web/src/brave.ts +66 -0
- package/web/src/cache.ts +151 -0
- package/web/src/config.ts +210 -0
- package/web/src/controls.ts +128 -0
- package/web/src/domains.ts +114 -0
- package/web/src/exa.ts +60 -0
- package/web/src/firecrawl.ts +160 -0
- package/web/src/index.ts +387 -0
- package/web/src/kagi.ts +73 -0
- package/web/src/limits.ts +55 -0
- package/web/src/native/convert.ts +84 -0
- package/web/src/native/fetch.ts +226 -0
- package/web/src/normalize.ts +131 -0
- package/web/src/obscura/cdp.ts +201 -0
- package/web/src/obscura/classify.ts +35 -0
- package/web/src/obscura/cli.ts +254 -0
- package/web/src/obscura/errors.ts +8 -0
- package/web/src/obscura/index.ts +59 -0
- package/web/src/obscura/limits.ts +92 -0
- package/web/src/obscura/mcp.ts +104 -0
- package/web/src/obscura/playwright.ts +133 -0
- package/web/src/obscura/process.ts +235 -0
- package/web/src/obscura/search-profile.ts +73 -0
- package/web/src/obscura/types.ts +48 -0
- package/web/src/obscura/web.ts +419 -0
- package/web/src/prompt-fetch.ts +88 -0
- package/web/src/render.ts +75 -0
- package/web/src/searxng.ts +78 -0
- package/web/src/slice.ts +139 -0
- package/web/src/tavily.ts +77 -0
- package/web/src/tools.ts +182 -0
- package/web/src/transport.ts +310 -0
- package/web/src/types.ts +199 -0
- package/work/README.md +77 -0
- package/work/THIRD_PARTY_NOTICES +24 -0
- package/work/docling/ocr.py +150 -0
- package/work/sandbox/Dockerfile +36 -0
- package/work/sandbox/soffice.sh +12 -0
- package/work/src/command.ts +29 -0
- package/work/src/config.ts +138 -0
- package/work/src/connectors/cli.ts +343 -0
- package/work/src/connectors/drafts.ts +647 -0
- package/work/src/connectors/errors.ts +8 -0
- package/work/src/connectors/file-bytes.ts +149 -0
- package/work/src/connectors/google-workspace-http.ts +399 -0
- package/work/src/connectors/google-workspace.ts +465 -0
- package/work/src/connectors/gws-tools.ts +378 -0
- package/work/src/connectors/http.ts +123 -0
- package/work/src/connectors/idempotency.ts +235 -0
- package/work/src/connectors/identity.ts +34 -0
- package/work/src/connectors/index.ts +93 -0
- package/work/src/connectors/limits.ts +50 -0
- package/work/src/connectors/m365-tools.ts +308 -0
- package/work/src/connectors/microsoft365-http.ts +428 -0
- package/work/src/connectors/microsoft365.ts +402 -0
- package/work/src/connectors/normalize.ts +120 -0
- package/work/src/connectors/tool-helpers.ts +398 -0
- package/work/src/connectors/tools.ts +42 -0
- package/work/src/connectors/types.ts +399 -0
- package/work/src/diagrams/canonicalize.ts +166 -0
- package/work/src/diagrams/caps.ts +52 -0
- package/work/src/diagrams/embed.ts +340 -0
- package/work/src/diagrams/errors.ts +76 -0
- package/work/src/diagrams/index.ts +81 -0
- package/work/src/diagrams/messages.ts +150 -0
- package/work/src/diagrams/origin.ts +52 -0
- package/work/src/diagrams/telemetry.ts +34 -0
- package/work/src/diagrams/xml.ts +267 -0
- package/work/src/document-extraction/index.ts +563 -0
- package/work/src/document-reader/ambient.d.ts +2 -0
- package/work/src/document-reader/errors.ts +7 -0
- package/work/src/document-reader/index.ts +181 -0
- package/work/src/document-reader/mistral-ocr.ts +318 -0
- package/work/src/document-reader/parsers.ts +171 -0
- package/work/src/documents/caps.ts +135 -0
- package/work/src/documents/diff.ts +269 -0
- package/work/src/documents/errors.ts +44 -0
- package/work/src/documents/fidelity.ts +98 -0
- package/work/src/documents/generate.ts +96 -0
- package/work/src/documents/hash.ts +8 -0
- package/work/src/documents/index.ts +14 -0
- package/work/src/documents/model-schema.ts +639 -0
- package/work/src/documents/parse.ts +252 -0
- package/work/src/documents/patch-history.ts +81 -0
- package/work/src/documents/patch.ts +476 -0
- package/work/src/documents/preview-html.ts +245 -0
- package/work/src/documents/preview.ts +227 -0
- package/work/src/documents/telemetry.ts +36 -0
- package/work/src/documents/translate/docx.ts +292 -0
- package/work/src/documents/translate/pptx.ts +304 -0
- package/work/src/documents/translate/xlsx.ts +137 -0
- package/work/src/documents/types.ts +188 -0
- package/work/src/index.ts +311 -0
- package/work/src/runtime/worker-pool-entry.ts +102 -0
- package/work/src/runtime/worker-pool.ts +267 -0
- package/work/src/sandbox/composition.ts +212 -0
- package/work/src/sandbox/image.ts +6 -0
- package/work/src/sandbox/index.ts +14 -0
- package/work/src/sheets/caps.ts +68 -0
- package/work/src/sheets/csv.ts +351 -0
- package/work/src/sheets/decimal.ts +388 -0
- package/work/src/sheets/errors.ts +52 -0
- package/work/src/sheets/index.ts +62 -0
- package/work/src/sheets/inference.ts +378 -0
- package/work/src/sheets/telemetry.ts +34 -0
- package/work/src/sheets/types.ts +162 -0
- package/work/src/sheets/xlsx.ts +388 -0
- package/work/src/skills/index.ts +8 -0
- package/work/src/skills/load.ts +43 -0
- package/work/src/tools/filesystem.ts +21 -0
- package/work/src/tools/index.ts +1 -0
- package/work/src/tools/local-filesystem.ts +33 -0
- package/work/src/tools/office.ts +311 -0
- package/work/vendor/hermes-agent/LICENSE +21 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/LICENSE +21 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/SKILL.md +196 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_comments.py +289 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_common.py +94 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_create.py +177 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_edit.py +250 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_read.py +149 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_revisions.py +147 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_template.py +70 -0
- package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_validate.py +156 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/LICENSE +21 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/SKILL.md +125 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/_raster.py +76 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/extract_marker.py +88 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/extract_pymupdf.py +101 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_create.py +130 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_fill_form.py +97 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_form_layout.py +168 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_make_form.py +145 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_merge.py +50 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_meta.py +115 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_page_image.py +99 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_read.py +153 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_secure.py +71 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_split.py +84 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_stamp.py +143 -0
- package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_watermark.py +51 -0
- package/work/vendor/hermes-agent/skills/productivity/powerpoint/LICENSE +21 -0
- package/work/vendor/hermes-agent/skills/productivity/powerpoint/SKILL.md +220 -0
- package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_create.py +214 -0
- package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_edit.py +436 -0
- package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_from_template.py +88 -0
- package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_read.py +131 -0
- package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_render.py +93 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/LICENSE +21 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/SKILL.md +196 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/csv_to_xlsx.py +104 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_create.py +259 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_edit.py +263 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_read.py +160 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_recalc.py +111 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_restructure.py +337 -0
- package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_to_csv.py +69 -0
- package/work/vendor-lock.json +11 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# MIT License. Part of the Hermes docx skill.
|
|
3
|
+
"""Health-check a .docx package and report issues as JSON.
|
|
4
|
+
|
|
5
|
+
Usage: docx_validate.py file.docx
|
|
6
|
+
|
|
7
|
+
Checks (health-check tier, NOT full XSD schema validation):
|
|
8
|
+
- the file is a readable zip and python-docx can open it
|
|
9
|
+
- required package parts exist ([Content_Types].xml, document.xml)
|
|
10
|
+
- every relationship in every .rels file resolves to a part in the
|
|
11
|
+
package (dangling image/hyperlink/etc. rels are reported; external
|
|
12
|
+
targets such as hyperlinks are skipped)
|
|
13
|
+
- r:embed / r:id references in document.xml resolve to relationships
|
|
14
|
+
- embedded images are non-empty and start with known magic bytes
|
|
15
|
+
(PNG/JPEG/GIF/BMP/TIFF/EMF/WMF/SVG); no PIL required
|
|
16
|
+
- paragraph and run style ids referenced by the document exist in
|
|
17
|
+
styles.xml
|
|
18
|
+
|
|
19
|
+
Output: {"ok": bool, "issues": [{"severity": "error"|"warning", ...}]}
|
|
20
|
+
Exit code 1 when any error-severity issue is found (warnings exit 0).
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import json
|
|
26
|
+
import posixpath
|
|
27
|
+
import sys
|
|
28
|
+
import zipfile
|
|
29
|
+
|
|
30
|
+
from lxml import etree
|
|
31
|
+
|
|
32
|
+
W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
|
33
|
+
R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
|
|
34
|
+
PR = "http://schemas.openxmlformats.org/package/2006/relationships"
|
|
35
|
+
|
|
36
|
+
IMAGE_MAGIC = (
|
|
37
|
+
b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a",
|
|
38
|
+
b"BM", b"II*\x00", b"MM\x00*",
|
|
39
|
+
b"\x01\x00\x00\x00", # EMF
|
|
40
|
+
b"\xd7\xcd\xc6\x9a", b"\x01\x00\x09\x00", # WMF variants
|
|
41
|
+
b"<?xml", b"<svg",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _issue(issues, severity, code, detail):
|
|
46
|
+
issues.append({"severity": severity, "code": code, "detail": detail})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _rel_target(base_part: str, target: str) -> str:
|
|
50
|
+
base_dir = posixpath.dirname(base_part)
|
|
51
|
+
return posixpath.normpath(posixpath.join(base_dir, target)).lstrip("/")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def validate(path: str) -> dict:
|
|
55
|
+
issues: list[dict] = []
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
zf = zipfile.ZipFile(path)
|
|
59
|
+
except (OSError, zipfile.BadZipFile) as exc:
|
|
60
|
+
_issue(issues, "error", "not-a-zip", str(exc))
|
|
61
|
+
return {"ok": False, "issues": issues}
|
|
62
|
+
|
|
63
|
+
names = set(zf.namelist())
|
|
64
|
+
bad = zf.testzip()
|
|
65
|
+
if bad is not None:
|
|
66
|
+
_issue(issues, "error", "corrupt-member", f"CRC check failed: {bad}")
|
|
67
|
+
|
|
68
|
+
for required in ("[Content_Types].xml", "word/document.xml"):
|
|
69
|
+
if required not in names:
|
|
70
|
+
_issue(issues, "error", "missing-part",
|
|
71
|
+
f"required part absent: {required}")
|
|
72
|
+
if issues and any(i["severity"] == "error" for i in issues):
|
|
73
|
+
return {"ok": False, "issues": issues}
|
|
74
|
+
|
|
75
|
+
# --- relationships resolve ------------------------------------------
|
|
76
|
+
rel_ids_by_source: dict[str, dict] = {}
|
|
77
|
+
for rels_name in [n for n in names if n.endswith(".rels")]:
|
|
78
|
+
try:
|
|
79
|
+
root = etree.fromstring(zf.read(rels_name))
|
|
80
|
+
except etree.XMLSyntaxError as exc:
|
|
81
|
+
_issue(issues, "error", "bad-rels-xml", f"{rels_name}: {exc}")
|
|
82
|
+
continue
|
|
83
|
+
source_part = posixpath.normpath(
|
|
84
|
+
posixpath.join(posixpath.dirname(rels_name), ".."))
|
|
85
|
+
source_part = "" if source_part == "." else source_part
|
|
86
|
+
ids = {}
|
|
87
|
+
for rel in root.iter(f"{{{PR}}}Relationship"):
|
|
88
|
+
rid, target = rel.get("Id"), rel.get("Target", "")
|
|
89
|
+
mode = rel.get("TargetMode", "Internal")
|
|
90
|
+
ids[rid] = target
|
|
91
|
+
if mode == "External":
|
|
92
|
+
continue
|
|
93
|
+
resolved = _rel_target(source_part + "/x" if source_part
|
|
94
|
+
else "x", target)
|
|
95
|
+
if resolved not in names:
|
|
96
|
+
_issue(issues, "error", "dangling-rel",
|
|
97
|
+
f"{rels_name}: {rid} -> {target} (missing part)")
|
|
98
|
+
rel_ids_by_source[source_part or "_package"] = ids
|
|
99
|
+
|
|
100
|
+
# --- r:id / r:embed references in document.xml -----------------------
|
|
101
|
+
doc_root = etree.fromstring(zf.read("word/document.xml"))
|
|
102
|
+
doc_rels = rel_ids_by_source.get("word", {})
|
|
103
|
+
for el in doc_root.iter():
|
|
104
|
+
for attr in (f"{{{R}}}id", f"{{{R}}}embed", f"{{{R}}}link"):
|
|
105
|
+
rid = el.get(attr)
|
|
106
|
+
if rid and rid not in doc_rels:
|
|
107
|
+
_issue(issues, "error", "unresolved-reference",
|
|
108
|
+
f"document.xml references {rid} with no relationship")
|
|
109
|
+
|
|
110
|
+
# --- embedded images decode ------------------------------------------
|
|
111
|
+
for name in [n for n in names if n.startswith("word/media/")]:
|
|
112
|
+
data = zf.read(name)
|
|
113
|
+
if not data:
|
|
114
|
+
_issue(issues, "error", "empty-image", name)
|
|
115
|
+
elif not any(data.startswith(m) for m in IMAGE_MAGIC):
|
|
116
|
+
_issue(issues, "warning", "unknown-image-format",
|
|
117
|
+
f"{name}: unrecognized magic bytes")
|
|
118
|
+
|
|
119
|
+
# --- styles referenced exist ------------------------------------------
|
|
120
|
+
defined = set()
|
|
121
|
+
if "word/styles.xml" in names:
|
|
122
|
+
styles_root = etree.fromstring(zf.read("word/styles.xml"))
|
|
123
|
+
defined = {s.get(f"{{{W}}}styleId")
|
|
124
|
+
for s in styles_root.iter(f"{{{W}}}style")}
|
|
125
|
+
for tag, attr in ((f"{{{W}}}pStyle", f"{{{W}}}val"),
|
|
126
|
+
(f"{{{W}}}rStyle", f"{{{W}}}val"),
|
|
127
|
+
(f"{{{W}}}tblStyle", f"{{{W}}}val")):
|
|
128
|
+
for el in doc_root.iter(tag):
|
|
129
|
+
sid = el.get(attr)
|
|
130
|
+
if sid and sid not in defined:
|
|
131
|
+
_issue(issues, "error", "missing-style",
|
|
132
|
+
f"style id referenced but not defined: {sid}")
|
|
133
|
+
|
|
134
|
+
# --- python-docx can open it ------------------------------------------
|
|
135
|
+
try:
|
|
136
|
+
from docx import Document
|
|
137
|
+
Document(path)
|
|
138
|
+
except Exception as exc: # noqa: BLE001 - triage tool, report anything
|
|
139
|
+
_issue(issues, "error", "python-docx-open-failed", str(exc))
|
|
140
|
+
|
|
141
|
+
ok = not any(i["severity"] == "error" for i in issues)
|
|
142
|
+
return {"ok": ok, "issues": issues}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def main() -> int:
|
|
146
|
+
ap = argparse.ArgumentParser(
|
|
147
|
+
description="Health-check a .docx (not XSD schema validation).")
|
|
148
|
+
ap.add_argument("path", help="the .docx file to check")
|
|
149
|
+
args = ap.parse_args()
|
|
150
|
+
report = validate(args.path)
|
|
151
|
+
print(json.dumps(report, ensure_ascii=False))
|
|
152
|
+
return 0 if report["ok"] else 1
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
if __name__ == "__main__":
|
|
156
|
+
sys.exit(main())
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nous Research
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pdf
|
|
3
|
+
description: "PDF files: create, read, merge, fill, OCR, edit text."
|
|
4
|
+
version: 1.1.0
|
|
5
|
+
author: Nous Research
|
|
6
|
+
license: MIT
|
|
7
|
+
platforms: [linux, macos, windows]
|
|
8
|
+
metadata:
|
|
9
|
+
hermes:
|
|
10
|
+
tags: [pdf, documents, forms, ocr, text-extraction, reportlab, pypdf, pdfplumber, pymupdf, marker]
|
|
11
|
+
category: productivity
|
|
12
|
+
related_skills: [docx, xlsx, powerpoint]
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
# PDF Skill
|
|
16
|
+
|
|
17
|
+
Create PDFs from structured specs, build and fill AcroForm forms (with layout linting and visual overlays), extract text/tables/metadata, merge/split/rotate/watermark/stamp pages, export page images, manage metadata and attachments, and encrypt/decrypt — using pypdf, reportlab, and pdfplumber. Two absorbed capabilities live in references/ (read the matching file before those tasks):
|
|
18
|
+
|
|
19
|
+
- **Scanned/image-only PDFs and OCR** (pymupdf fast path, marker-pdf quality path, scripts/extract_pymupdf.py + scripts/extract_marker.py): `references/ocr-extraction.md`
|
|
20
|
+
- **Editing text inside an existing PDF via natural-language prompts** (nano-pdf CLI): `references/nano-pdf-editing.md`
|
|
21
|
+
|
|
22
|
+
## When to Use
|
|
23
|
+
|
|
24
|
+
- Generate a report, invoice, or multi-page document as PDF.
|
|
25
|
+
- Build a fillable AcroForm (text/checkbox/radio/dropdown) from a JSON spec, linting the layout first.
|
|
26
|
+
- Pull text, tables (JSON/CSV), metadata, or form-field values out of a PDF.
|
|
27
|
+
- Merge, split, rotate, extract page subsets, watermark, stamp text/images at coordinates, bookmark, or compress PDFs.
|
|
28
|
+
- Export pages as PNGs for visual review or for OCR hand-off; set/clear document metadata; add/extract file attachments.
|
|
29
|
+
- Fill or flatten AcroForm forms; encrypt or decrypt with passwords.
|
|
30
|
+
- NOT for scanned/image-only PDFs (use `references/ocr-extraction.md`) and NOT for pixel-perfect HTML-to-PDF rendering (use a headless browser).
|
|
31
|
+
|
|
32
|
+
## Prerequisites
|
|
33
|
+
|
|
34
|
+
- Python 3.10+ with `pypdf`, `reportlab`, `pdfplumber`:
|
|
35
|
+
`python -m pip install pypdf reportlab pdfplumber`
|
|
36
|
+
- Optional, for page rasterization (`pdf_page_image.py`, overlay rendering): `python -m pip install pypdfium2`, or poppler's `pdftoppm` on PATH. Scripts fall back pypdfium2 → pdftoppm and report `{"rendered": false, "missing": [...]}` (exit 0) when neither exists.
|
|
37
|
+
- Each helper script checks imports lazily and prints an install hint if a dependency is missing.
|
|
38
|
+
|
|
39
|
+
## How to Run
|
|
40
|
+
|
|
41
|
+
All helpers live in `scripts/` and are argparse CLIs — run them with the `terminal` tool; every one supports `--help`. They read/write JSON strictly as UTF-8, print JSON results to stdout, and exit non-zero on failure.
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
python scripts/pdf_create.py spec.json -o out.pdf # build PDF from JSON spec
|
|
45
|
+
python scripts/pdf_make_form.py formspec.json -o form.pdf # build fillable AcroForm from JSON spec
|
|
46
|
+
python scripts/pdf_form_layout.py formspec.json # lint form layout BEFORE building
|
|
47
|
+
python scripts/pdf_form_layout.py formspec.json --render-overlay boxes.png [--pdf form.pdf]
|
|
48
|
+
python scripts/pdf_read.py doc.pdf --text # per-page text (JSON)
|
|
49
|
+
python scripts/pdf_read.py doc.pdf --tables --csv-dir t/ # tables to JSON + CSV files
|
|
50
|
+
python scripts/pdf_read.py doc.pdf --meta # metadata, page sizes, encrypted/scanned flags
|
|
51
|
+
python scripts/pdf_read.py form.pdf --fields # form fields: name, type, value
|
|
52
|
+
python scripts/pdf_merge.py a.pdf b.pdf -o merged.pdf [--bookmarks]
|
|
53
|
+
python scripts/pdf_split.py doc.pdf --pages 1-3,7 -o part.pdf [--rotate 90]
|
|
54
|
+
python scripts/pdf_fill_form.py form.pdf --fields-json values.json -o filled.pdf [--flatten]
|
|
55
|
+
python scripts/pdf_secure.py doc.pdf --encrypt -o enc.pdf --user-password your-password
|
|
56
|
+
python scripts/pdf_secure.py enc.pdf --decrypt -o dec.pdf --password your-password
|
|
57
|
+
python scripts/pdf_watermark.py doc.pdf --stamp mark.pdf -o stamped.pdf [--under]
|
|
58
|
+
python scripts/pdf_stamp.py doc.pdf -o out.pdf --text "DRAFT" --x 150 --y 400 \
|
|
59
|
+
--font-size 60 --rotation 45 --opacity 0.3 --color "#cc0000" [--pages 1-3]
|
|
60
|
+
python scripts/pdf_stamp.py doc.pdf -o out.pdf --image sig.png --x 400 --y 60 --width 120
|
|
61
|
+
python scripts/pdf_page_image.py doc.pdf --pages 1-3 --dpi 150 --out-dir imgs/
|
|
62
|
+
python scripts/pdf_meta.py doc.pdf --set-meta --title "T" --author "A" -o out.pdf
|
|
63
|
+
python scripts/pdf_meta.py doc.pdf --attach data.csv -o out.pdf
|
|
64
|
+
python scripts/pdf_meta.py doc.pdf --list-attachments | --extract-attachments dir/
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Quick Reference
|
|
68
|
+
|
|
69
|
+
| Task | Tool | Command / API |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| Create doc (headings, tables, images) | reportlab platypus | `pdf_create.py spec.json -o out.pdf` |
|
|
72
|
+
| Build fillable form | reportlab acroForm | `pdf_make_form.py formspec.json -o form.pdf` |
|
|
73
|
+
| Lint form layout / overlay image | pure python + PIL | `pdf_form_layout.py formspec.json [--render-overlay o.png]` |
|
|
74
|
+
| Per-page text | pdfplumber | `pdf_read.py f.pdf --text` |
|
|
75
|
+
| Tables → JSON/CSV | pdfplumber | `pdf_read.py f.pdf --tables` |
|
|
76
|
+
| Metadata / sizes / encrypted / scanned | pypdf + pdfplumber | `pdf_read.py f.pdf --meta` |
|
|
77
|
+
| Merge (+ outline) | pypdf | `pdf_merge.py a.pdf b.pdf -o m.pdf` |
|
|
78
|
+
| Split / extract / rotate | pypdf | `pdf_split.py f.pdf --pages 2-5 --rotate 90` |
|
|
79
|
+
| List / fill / flatten form | pypdf | `pdf_read.py --fields`, `pdf_fill_form.py` |
|
|
80
|
+
| Encrypt / decrypt (AES-256) | pypdf | `pdf_secure.py --encrypt/--decrypt` |
|
|
81
|
+
| Watermark / stamp PDF page | pypdf | `pdf_watermark.py f.pdf --stamp w.pdf` |
|
|
82
|
+
| Stamp text/image at coordinates | reportlab + pypdf | `pdf_stamp.py f.pdf --text "Sign here" --x 400 --y 60` |
|
|
83
|
+
| Pages → PNG (review / OCR hand-off) | pypdfium2 or pdftoppm | `pdf_page_image.py f.pdf --pages 1-3 --out-dir imgs/` |
|
|
84
|
+
| Set/clear metadata, attachments | pypdf | `pdf_meta.py --set-meta / --attach / --extract-attachments` |
|
|
85
|
+
| Compress content streams | pypdf | `pdf_split.py f.pdf --pages 1-N --compress` |
|
|
86
|
+
|
|
87
|
+
## Procedure
|
|
88
|
+
|
|
89
|
+
1. **Inspect first.** Run `pdf_read.py file.pdf --meta`. Check `encrypted` (if true, decrypt first with `pdf_secure.py --decrypt`) and `likely_scanned_pages`. If pages are image-only, export them with `pdf_page_image.py --pages <scanned> --dpi 300 --out-dir imgs/` and hand the PNGs to the `references/ocr-extraction.md` skill — do not report empty text as "no content".
|
|
90
|
+
2. **Create.** Write a JSON spec with `write_file` (elements: `heading`, `paragraph`, `table`, `image`, `pagebreak`; optional `title`/`author` metadata; page numbers are added automatically), then run `pdf_create.py`. Verify visually with `vision_analyze` on a rendered page image if layout matters.
|
|
91
|
+
3. **Extract.** `--text` gives a JSON list of per-page strings; `--tables` gives row arrays per page and can also emit CSV files. Read results with `read_file`; never eyeball a binary PDF directly.
|
|
92
|
+
4. **Manipulate.** `pdf_merge.py` concatenates and can add one bookmark per source file; `pdf_split.py` handles page ranges (1-based, e.g. `1-3,5,9-`), rotation in 90° steps, and `--compress`. Watermark by preparing a single-page stamp PDF (e.g. via `pdf_create.py`) and overlaying it with `pdf_watermark.py`; for one-liner stamps ("sign here", diagonal DRAFT, corner labels) use `pdf_stamp.py` with text or an image at explicit coordinates.
|
|
93
|
+
5. **Build forms.** Write one form-spec JSON (fields with `label_box`/`entry_box` in PDF points — see `references/forms.md`), lint it with `pdf_form_layout.py` and fix every reported problem, optionally review the `--render-overlay` PNG with `vision_analyze`, then build with `pdf_make_form.py` and confirm with `pdf_read.py --fields`.
|
|
94
|
+
6. **Fill forms.** List fields (`--fields`) to learn exact names and types, write a UTF-8 JSON of `{"FieldName": "value"}` with `write_file` (checkboxes accept `true`/`false`; radio/choice values must match the field's export options), then `pdf_fill_form.py`. Re-read with `--fields` to confirm values landed.
|
|
95
|
+
7. **Metadata & attachments.** `pdf_meta.py --set-meta` writes Title/Author/Subject/Keywords (DocInfo); `--clear-meta` drops them; `--attach`/`--list-attachments`/`--extract-attachments` round-trip embedded files.
|
|
96
|
+
8. **Secure.** Encrypt with distinct user/owner passwords and AES-256. To remove a password you know, `--decrypt` writes an unencrypted copy.
|
|
97
|
+
9. **Verify** (see below) before reporting success.
|
|
98
|
+
|
|
99
|
+
## Pitfalls
|
|
100
|
+
|
|
101
|
+
- **Scanned PDFs**: empty `extract_text()` plus page images means there is no text layer. Route to `references/ocr-extraction.md`; do not fabricate text.
|
|
102
|
+
- **Flattening limits**: `pdf_fill_form.py --flatten` uses pypdf's flatten support, which converts widget appearances into page content. It is reliable for plain text fields and checkboxes but can drop or misrender exotic widgets (rich text, custom appearance streams, some radio groups). Verify the flattened output visually with `vision_analyze`; for bulletproof flattening use an external renderer (e.g. Ghostscript or `pdftoppm`+reassembly) as a fallback.
|
|
103
|
+
- **NeedAppearances**: after filling, viewers only render values if appearance streams exist. The fill script sets the AcroForm `NeedAppearances` flag so conforming viewers regenerate them; some minimal viewers ignore it — flatten if display fidelity matters.
|
|
104
|
+
- **Non-Latin form values**: values are stored correctly (UTF-16), but the field's default font may lack glyphs, so a viewer can show blanks even though the data round-trips. Verify with `--fields`, not just visually.
|
|
105
|
+
- **Compression expectations**: `--compress` only deflates content streams. Typical savings are 0–20%; it does nothing for PDFs dominated by images or already-compressed streams. It is not a substitute for image downsampling (Ghostscript territory).
|
|
106
|
+
- **Permission flags don't enforce**: owner-password permission bits (no-print, no-copy) are polite requests that viewers may honor; any library (including pypdf) can read and strip them. Only the user password actually gates content via encryption. Never present permission flags as security.
|
|
107
|
+
- **Table extraction is heuristic**: pdfplumber detects tables from ruling lines/word alignment; borderless or merged-cell tables may need `table_settings` tuning or manual cleanup.
|
|
108
|
+
- **Page indexing**: helper CLIs take 1-based pages; pypdf APIs are 0-based. The scripts convert — don't double-convert.
|
|
109
|
+
- **Rotated stamp text extraction**: pdfplumber's line grouping scrambles rotated glyphs (a 45° "DRAFT" extracts as stray letters); verify rotated stamps with `pypdf`'s `extract_text()` or a rendered image instead.
|
|
110
|
+
- **Radio groups**: reportlab needs ≥2 `radio()` widgets per group, fills need the slashed export value (`"/red"`), and flatten fidelity is worst for radios — see `references/forms.md`.
|
|
111
|
+
- **Metadata scope**: `pdf_meta.py` writes the classic DocInfo dictionary only; embedded XMP metadata (if any) is left untouched and may show different values in some viewers.
|
|
112
|
+
- **PDF/A is out of scope**: pypdf/reportlab cannot produce or validate conformant PDF/A. If archival conformance is required, run Ghostscript via the `terminal` tool (e.g. `gs -dPDFA=2 -dPDFACompatibilityPolicy=1 -sColorConversionStrategy=UseDeviceIndependentColor -sDEVICE=pdfwrite -o out.pdf in.pdf` with a suitable ICC profile) and validate with veraPDF — both are external installs, and the result still needs validation, not assumption.
|
|
113
|
+
- Rotation must be a multiple of 90; encrypted inputs must be decrypted before any other operation.
|
|
114
|
+
|
|
115
|
+
## Verification
|
|
116
|
+
|
|
117
|
+
- After create/merge/split: `pdf_read.py out.pdf --meta` — confirm `page_count`, and per-page `rotation` when you rotated.
|
|
118
|
+
- After extraction: check the JSON is non-empty and spot-check a known string or cell.
|
|
119
|
+
- Form design loop: `pdf_form_layout.py spec.json` must exit 0; then `--render-overlay boxes.png --pdf form.pdf` and review the PNG with `vision_analyze` (red = entry boxes with field names, blue = label boxes) asking about overlaps, misalignment, and labels detached from their fields. Iterate spec → lint → overlay until clean.
|
|
120
|
+
- After building a form: `pdf_read.py form.pdf --fields` lists every spec field with the right type and options.
|
|
121
|
+
- After form fill: `pdf_read.py filled.pdf --fields` and compare values (exact match, including non-ASCII).
|
|
122
|
+
- After stamping: re-extract text (pypdf for rotated stamps) or render the page with `pdf_page_image.py` and inspect with `vision_analyze`.
|
|
123
|
+
- After metadata/attachment edits: `pdf_read.py --meta` / `pdf_meta.py --list-attachments`, and re-extract an attachment to byte-compare.
|
|
124
|
+
- After encrypt: `--meta` shows `"encrypted": true` and opening without a password fails; after decrypt, text extraction matches the original.
|
|
125
|
+
- For anything visual (watermarks, flattened forms), render and inspect with `vision_analyze`.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Shared page rasterizer with a fallback chain: pypdfium2 -> pdftoppm.
|
|
2
|
+
|
|
3
|
+
Returns PIL Images so callers can annotate/save. Not a CLI.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def available_backends() -> list[str]:
|
|
14
|
+
"""Names of usable rasterizer backends, in preference order."""
|
|
15
|
+
backends = []
|
|
16
|
+
try:
|
|
17
|
+
import pypdfium2 # noqa: F401
|
|
18
|
+
backends.append("pypdfium2")
|
|
19
|
+
except ImportError:
|
|
20
|
+
pass
|
|
21
|
+
if shutil.which("pdftoppm"):
|
|
22
|
+
backends.append("pdftoppm")
|
|
23
|
+
return backends
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def missing_hints() -> list[str]:
|
|
27
|
+
"""Install hints for when no backend is available."""
|
|
28
|
+
return [
|
|
29
|
+
"python3 -m pip install pypdfium2",
|
|
30
|
+
"poppler-utils (provides pdftoppm), e.g. apt-get install poppler-utils",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def rasterize_page(pdf_path: str, page: int, dpi: int = 150, password: str | None = None):
|
|
35
|
+
"""Render one 1-based page to a PIL Image, or None if no backend works.
|
|
36
|
+
|
|
37
|
+
Raises ValueError for an out-of-range page when a backend is present.
|
|
38
|
+
"""
|
|
39
|
+
for backend in available_backends():
|
|
40
|
+
if backend == "pypdfium2":
|
|
41
|
+
return _via_pdfium(pdf_path, page, dpi, password)
|
|
42
|
+
if backend == "pdftoppm":
|
|
43
|
+
img = _via_pdftoppm(pdf_path, page, dpi, password)
|
|
44
|
+
if img is not None:
|
|
45
|
+
return img
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _via_pdfium(pdf_path: str, page: int, dpi: int, password: str | None):
|
|
50
|
+
import pypdfium2 as pdfium
|
|
51
|
+
doc = pdfium.PdfDocument(pdf_path, password=password)
|
|
52
|
+
try:
|
|
53
|
+
if not 1 <= page <= len(doc):
|
|
54
|
+
raise ValueError(f"page {page} out of range 1-{len(doc)}")
|
|
55
|
+
bitmap = doc[page - 1].render(scale=dpi / 72.0)
|
|
56
|
+
return bitmap.to_pil().convert("RGB")
|
|
57
|
+
finally:
|
|
58
|
+
doc.close()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _via_pdftoppm(pdf_path: str, page: int, dpi: int, password: str | None):
|
|
62
|
+
from PIL import Image
|
|
63
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
64
|
+
prefix = str(Path(tmp) / "page")
|
|
65
|
+
cmd = ["pdftoppm", "-png", "-r", str(dpi), "-f", str(page), "-l", str(page)]
|
|
66
|
+
if password:
|
|
67
|
+
cmd += ["-upw", password]
|
|
68
|
+
cmd += [pdf_path, prefix]
|
|
69
|
+
proc = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8")
|
|
70
|
+
if proc.returncode != 0:
|
|
71
|
+
raise ValueError(f"pdftoppm failed: {proc.stderr.strip()}")
|
|
72
|
+
produced = sorted(Path(tmp).glob("page*.png"))
|
|
73
|
+
if not produced:
|
|
74
|
+
raise ValueError(f"page {page} out of range (pdftoppm produced no image)")
|
|
75
|
+
with Image.open(produced[0]) as img:
|
|
76
|
+
return img.convert("RGB")
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Extract text from documents using marker-pdf. High-quality OCR + layout analysis.
|
|
3
|
+
|
|
4
|
+
Requires ~3-5GB disk (PyTorch + models downloaded on first use).
|
|
5
|
+
Supports: PDF, DOCX, PPTX, XLSX, HTML, EPUB, images.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
python extract_marker.py document.pdf
|
|
9
|
+
python extract_marker.py document.pdf --output_dir ./output
|
|
10
|
+
python extract_marker.py presentation.pptx
|
|
11
|
+
python extract_marker.py spreadsheet.xlsx
|
|
12
|
+
python extract_marker.py scanned_doc.pdf # OCR works here
|
|
13
|
+
python extract_marker.py document.pdf --json # Structured output
|
|
14
|
+
python extract_marker.py document.pdf --use_llm # LLM-boosted accuracy
|
|
15
|
+
"""
|
|
16
|
+
import sys
|
|
17
|
+
import os
|
|
18
|
+
|
|
19
|
+
def convert(path, output_dir=None, output_format="markdown", use_llm=False):
|
|
20
|
+
from marker.converters.pdf import PdfConverter
|
|
21
|
+
from marker.models import create_model_dict
|
|
22
|
+
from marker.config.parser import ConfigParser
|
|
23
|
+
|
|
24
|
+
config_dict = {}
|
|
25
|
+
if use_llm:
|
|
26
|
+
config_dict["use_llm"] = True
|
|
27
|
+
|
|
28
|
+
config_parser = ConfigParser(config_dict)
|
|
29
|
+
models = create_model_dict()
|
|
30
|
+
converter = PdfConverter(config=config_parser.generate_config_dict(), artifact_dict=models)
|
|
31
|
+
rendered = converter(path)
|
|
32
|
+
|
|
33
|
+
if output_format == "json":
|
|
34
|
+
import json
|
|
35
|
+
print(json.dumps({
|
|
36
|
+
"markdown": rendered.markdown,
|
|
37
|
+
"metadata": rendered.metadata if hasattr(rendered, "metadata") else {},
|
|
38
|
+
}, indent=2, ensure_ascii=False))
|
|
39
|
+
else:
|
|
40
|
+
print(rendered.markdown)
|
|
41
|
+
|
|
42
|
+
# Save images if output_dir specified
|
|
43
|
+
if output_dir and hasattr(rendered, "images") and rendered.images:
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
Path(output_dir).mkdir(parents=True, exist_ok=True)
|
|
46
|
+
for name, img_data in rendered.images.items():
|
|
47
|
+
img_path = os.path.join(output_dir, name)
|
|
48
|
+
with open(img_path, "wb") as f:
|
|
49
|
+
f.write(img_data)
|
|
50
|
+
print(f"\nSaved {len(rendered.images)} image(s) to {output_dir}/", file=sys.stderr)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def check_requirements():
|
|
54
|
+
"""Check disk space before installing."""
|
|
55
|
+
import shutil
|
|
56
|
+
free_gb = shutil.disk_usage("/").free / (1024**3)
|
|
57
|
+
if free_gb < 5:
|
|
58
|
+
print(f"⚠️ Only {free_gb:.1f}GB free. marker-pdf needs ~5GB for PyTorch + models.")
|
|
59
|
+
print("Use pymupdf instead (scripts/extract_pymupdf.py) or free up disk space.")
|
|
60
|
+
sys.exit(1)
|
|
61
|
+
print(f"✓ {free_gb:.1f}GB free — sufficient for marker-pdf")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
import argparse
|
|
66
|
+
|
|
67
|
+
parser = argparse.ArgumentParser(
|
|
68
|
+
description="Extract text from documents using marker-pdf (high-quality OCR + layout analysis)."
|
|
69
|
+
)
|
|
70
|
+
parser.add_argument("path", nargs="?", help="Document to convert (PDF, DOCX, PPTX, XLSX, HTML, EPUB, image)")
|
|
71
|
+
parser.add_argument("--output_dir", help="Directory to save extracted images")
|
|
72
|
+
parser.add_argument("--json", action="store_true", help="Structured JSON output instead of markdown")
|
|
73
|
+
parser.add_argument("--use_llm", action="store_true", help="LLM-boosted accuracy")
|
|
74
|
+
parser.add_argument("--check", action="store_true", help="Check disk space requirements and exit")
|
|
75
|
+
args = parser.parse_args()
|
|
76
|
+
|
|
77
|
+
if args.check:
|
|
78
|
+
check_requirements()
|
|
79
|
+
sys.exit(0)
|
|
80
|
+
if not args.path:
|
|
81
|
+
parser.error("path is required unless --check is given")
|
|
82
|
+
|
|
83
|
+
convert(
|
|
84
|
+
args.path,
|
|
85
|
+
output_dir=args.output_dir,
|
|
86
|
+
output_format="json" if args.json else "markdown",
|
|
87
|
+
use_llm=args.use_llm,
|
|
88
|
+
)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Extract text from documents using pymupdf. Lightweight (~25MB), no models.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
python extract_pymupdf.py document.pdf
|
|
6
|
+
python extract_pymupdf.py document.pdf --markdown
|
|
7
|
+
python extract_pymupdf.py document.pdf --pages 0-4
|
|
8
|
+
python extract_pymupdf.py document.pdf --images output_dir/
|
|
9
|
+
python extract_pymupdf.py document.pdf --tables
|
|
10
|
+
python extract_pymupdf.py document.pdf --metadata
|
|
11
|
+
"""
|
|
12
|
+
import sys
|
|
13
|
+
import json
|
|
14
|
+
|
|
15
|
+
def extract_text(path, pages=None):
|
|
16
|
+
import pymupdf
|
|
17
|
+
doc = pymupdf.open(path)
|
|
18
|
+
page_range = range(len(doc)) if pages is None else pages
|
|
19
|
+
for i in page_range:
|
|
20
|
+
if i < len(doc):
|
|
21
|
+
print(f"\n--- Page {i+1}/{len(doc)} ---\n")
|
|
22
|
+
print(doc[i].get_text())
|
|
23
|
+
|
|
24
|
+
def extract_markdown(path, pages=None):
|
|
25
|
+
import pymupdf4llm
|
|
26
|
+
md = pymupdf4llm.to_markdown(path, pages=pages)
|
|
27
|
+
print(md)
|
|
28
|
+
|
|
29
|
+
def extract_tables(path):
|
|
30
|
+
import pymupdf
|
|
31
|
+
doc = pymupdf.open(path)
|
|
32
|
+
for i, page in enumerate(doc):
|
|
33
|
+
tables = page.find_tables()
|
|
34
|
+
for j, table in enumerate(tables.tables):
|
|
35
|
+
print(f"\n--- Page {i+1}, Table {j+1} ---\n")
|
|
36
|
+
df = table.to_pandas()
|
|
37
|
+
print(df.to_markdown(index=False))
|
|
38
|
+
|
|
39
|
+
def extract_images(path, output_dir):
|
|
40
|
+
import pymupdf
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
Path(output_dir).mkdir(parents=True, exist_ok=True)
|
|
43
|
+
doc = pymupdf.open(path)
|
|
44
|
+
count = 0
|
|
45
|
+
for i, page in enumerate(doc):
|
|
46
|
+
for img_idx, img in enumerate(page.get_images(full=True)):
|
|
47
|
+
xref = img[0]
|
|
48
|
+
pix = pymupdf.Pixmap(doc, xref)
|
|
49
|
+
if pix.n >= 5:
|
|
50
|
+
pix = pymupdf.Pixmap(pymupdf.csRGB, pix)
|
|
51
|
+
out_path = f"{output_dir}/page{i+1}_img{img_idx+1}.png"
|
|
52
|
+
pix.save(out_path)
|
|
53
|
+
count += 1
|
|
54
|
+
print(f"Extracted {count} images to {output_dir}/")
|
|
55
|
+
|
|
56
|
+
def show_metadata(path):
|
|
57
|
+
import pymupdf
|
|
58
|
+
doc = pymupdf.open(path)
|
|
59
|
+
print(json.dumps({
|
|
60
|
+
"pages": len(doc),
|
|
61
|
+
"title": doc.metadata.get("title", ""),
|
|
62
|
+
"author": doc.metadata.get("author", ""),
|
|
63
|
+
"subject": doc.metadata.get("subject", ""),
|
|
64
|
+
"creator": doc.metadata.get("creator", ""),
|
|
65
|
+
"producer": doc.metadata.get("producer", ""),
|
|
66
|
+
"format": doc.metadata.get("format", ""),
|
|
67
|
+
}, indent=2))
|
|
68
|
+
|
|
69
|
+
if __name__ == "__main__":
|
|
70
|
+
import argparse
|
|
71
|
+
|
|
72
|
+
parser = argparse.ArgumentParser(
|
|
73
|
+
description="Extract text/tables/images/metadata from documents using pymupdf (lightweight, no models)."
|
|
74
|
+
)
|
|
75
|
+
parser.add_argument("path", help="Document to read")
|
|
76
|
+
parser.add_argument("--pages", help="Page selection: N or START-END (0-indexed)")
|
|
77
|
+
parser.add_argument("--markdown", action="store_true", help="Markdown output via pymupdf4llm")
|
|
78
|
+
parser.add_argument("--tables", action="store_true", help="Extract tables as markdown")
|
|
79
|
+
parser.add_argument("--images", nargs="?", const="./images", metavar="OUTPUT_DIR",
|
|
80
|
+
help="Extract embedded images to OUTPUT_DIR (default ./images)")
|
|
81
|
+
parser.add_argument("--metadata", action="store_true", help="Show document metadata as JSON")
|
|
82
|
+
args = parser.parse_args()
|
|
83
|
+
|
|
84
|
+
pages = None
|
|
85
|
+
if args.pages:
|
|
86
|
+
if "-" in args.pages:
|
|
87
|
+
start, end = args.pages.split("-")
|
|
88
|
+
pages = list(range(int(start), int(end) + 1))
|
|
89
|
+
else:
|
|
90
|
+
pages = [int(args.pages)]
|
|
91
|
+
|
|
92
|
+
if args.metadata:
|
|
93
|
+
show_metadata(args.path)
|
|
94
|
+
elif args.tables:
|
|
95
|
+
extract_tables(args.path)
|
|
96
|
+
elif args.images is not None:
|
|
97
|
+
extract_images(args.path, args.images)
|
|
98
|
+
elif args.markdown:
|
|
99
|
+
extract_markdown(args.path, pages=pages)
|
|
100
|
+
else:
|
|
101
|
+
extract_text(args.path, pages=pages)
|