docs(skill-office): 按正交能力重写 office-pdf 技能
将 office-pdf 从按流程组织改为十项正交能力(内容提取、页面渲染、页面组织、 几何变换、内容叠加、批注与链接、交互表单、文档导航、内嵌附件、文档管理与 输出)加组合示例表;跨能力的加密、不可改写、新建页面、页码索引规则集中 在开头。正文预算从 1,500 提到 3,000 token。smoke.py 补充批注删除、扁平化、 XMP、附件和页码标签检查;刷新 office-pdf-progressive 快照。
This commit is contained in:
1 parent
8701fcf231
commit
ef84fe8259
7 files changed
+114
-37
No files matched your search
@@ -18,8 +18,8 @@
|
||||
en: 619c88b3615cc8f5
|
||||
zh: 65b770b54e851e4b
|
||||
/deepseek-ai-dsh-skill-office/use-this-package/progressive-loading:
|
||||
en: 775f610ae4c9f1b0
|
||||
zh: 0c0335ee0122aeaa
|
||||
en: a8b087011a026024
|
||||
zh: 12155db5afeb1dec
|
||||
/deepseek-ai-dsh-skill-office/understand-the-implementation:
|
||||
en: 607022538541b75f
|
||||
zh: 9fc65ba288db5785
|
||||
@@ -30,8 +30,8 @@
|
||||
en: ed08fd35aa30c97c
|
||||
zh: 42e97ba44f07bcb5
|
||||
/deepseek-ai-dsh-skill-office/model-experience/kv-cache-effect:
|
||||
en: 8b09585f8cda4c9a
|
||||
zh: 8ed7ed180a47d48a
|
||||
en: 8e98a9afd98c9c80
|
||||
zh: 4fa3aaa3893e4f44
|
||||
/deepseek-ai-dsh-skill-office/known-limitations-and-deferred-work:
|
||||
en: cefdfc32e0202819
|
||||
zh: 77382735960758b2
|
||||
|
||||
@@ -45,7 +45,7 @@ A relative `assetRoot` rejects registration. Catalog discovery reads each `SKILL
|
||||
<a id="progressive-loading"></a>
|
||||
### Progressive loading
|
||||
|
||||
The model chooses skills from the task; the host does not inject complete instructions based on file extensions. With complete resources, all five skills are listed and loadable by name through `skill` or explicit user invocation. Loading an Office skill makes the three Office tools available from the next step; when they are not in the tool list, such as after a PTC resume or fork, the skills direct the model to load `office` again. Legacy `.doc`, `.xls`, and `.ppt` files, which python-docx, openpyxl, and python-pptx cannot read, are converted with `office_convert` before editing. Requested appearance changes, including spreadsheet cell fills and text alignment, require rendering even without an explicit visual-check request, and so do new or changed slide content in presentations; an explicit request to skip rendering takes precedence. Standalone operations use the dedicated tools after routing without loading an authoring skill. PDF export alone stops after checking that the copied output starts with `%PDF-`, without loading `office-pdf`. A PDF input loads `office-pdf`, which extracts text, splits, merges, protects, and fills forms with pypdf, and renders pages with `office_render` only when their text is empty or garbled, their layout or figures matter, or the user asks for images.
|
||||
The model chooses skills from the task; the host does not inject complete instructions based on file extensions. With complete resources, all five skills are listed and loadable by name through `skill` or explicit user invocation. Loading an Office skill makes the three Office tools available from the next step; when they are not in the tool list, such as after a PTC resume or fork, the skills direct the model to load `office` again. Legacy `.doc`, `.xls`, and `.ppt` files, which python-docx, openpyxl, and python-pptx cannot read, are converted with `office_convert` before editing. Requested appearance changes, including spreadsheet cell fills and text alignment, require rendering even without an explicit visual-check request, and so do new or changed slide content in presentations; an explicit request to skip rendering takes precedence. Standalone operations use the dedicated tools after routing without loading an authoring skill. PDF export alone stops after checking that the copied output starts with `%PDF-`, without loading `office-pdf`. A PDF input loads `office-pdf`, which describes ten pypdf capabilities, from text extraction and page organization through annotations, forms, bookmarks, attachments, and metadata, that combine into tasks such as watermarks or flattened forms, and renders pages with `office_render` only when their text is empty or garbled, their layout or figures matter, a changed page needs a visual check, or the user asks for images.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
@@ -57,7 +57,7 @@ flowchart TD
|
||||
C --> D["Author and validate content, structure and data"]
|
||||
D -->|No additional operation needed| F["Deliver"]
|
||||
|
||||
B -->|PDF input| G["skill(office-pdf): pypdf text, pages, and forms"]
|
||||
B -->|PDF input| G["skill(office-pdf): pypdf capabilities combined per task"]
|
||||
G -->|Text and structure checks suffice| F
|
||||
G -->|Empty or garbled text, layout, or visual check| R
|
||||
|
||||
@@ -118,7 +118,7 @@ Indirectly, through `dsh-tool-skill`, which renders the initial Office summary a
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
Skill results append to history, and loaded text or images remain after an operation finishes. With `tool-office` mounted, the first successful Office skill load enables the three tool declarations on the next step. A skill omitted or removed for unreadable resources changes the catalog, which a later step publishes as a catalog update. Character estimates use `ceil(characters / 4)`: the summary is at most 50 tokens and the router body at most 200; each authoring body is at most 70% of its recorded earlier estimate: 1,688 tokens for `office-docx`, 1,879 for `office-pptx`, and 2,330 for `office-xlsx`. `office-pdf` has no earlier estimate; its body is at most 1,500 tokens, and its summary adds about 23 tokens to every catalog. The appended Python environment section stays fixed while the configuration stays unchanged, and counts toward each skill body. Skill wrappers, the generic catalog, shell and Office tool declarations, and `load_workspace_dependencies` are separate costs, and these estimates are not server usage.
|
||||
Skill results append to history, and loaded text or images remain after an operation finishes. With `tool-office` mounted, the first successful Office skill load enables the three tool declarations on the next step. A skill omitted or removed for unreadable resources changes the catalog, which a later step publishes as a catalog update. Character estimates use `ceil(characters / 4)`: the summary is at most 50 tokens and the router body at most 200; each authoring body is at most 70% of its recorded earlier estimate: 1,688 tokens for `office-docx`, 1,879 for `office-pptx`, and 2,330 for `office-xlsx`. `office-pdf` has no earlier estimate; its body covers ten capabilities and is at most 3,000 tokens, and its summary adds about 23 tokens to every catalog. The appended Python environment section stays fixed while the configuration stays unchanged, and counts toward each skill body. Skill wrappers, the generic catalog, shell and Office tool declarations, and `load_workspace_dependencies` are separate costs, and these estimates are not server usage.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ kind: "package-reference"
|
||||
<a id="progressive-loading"></a>
|
||||
### 渐进加载
|
||||
|
||||
模型依据任务选择技能;宿主不会根据文件扩展名注入完整说明。资源完整时,五个技能均列入目录,可通过 `skill` 按名称加载或由用户显式调用。加载 Office 技能后,三个 Office 工具从下一步开始可用;工具不在列表中时(例如 PTC 模式 resume 或 fork 之后),技能会指示模型重新加载 `office`。python-docx、openpyxl 和 python-pptx 无法读取的旧格式 `.doc`、`.xls`、`.ppt` 文件,先用 `office_convert` 转换再编辑。用户要求的外观修改,包括电子表格单元格填充和文本对齐,即使没有明确要求视觉检查,也需要渲染,演示文稿中新增或修改的幻灯片内容同样需要渲染;用户明确要求跳过渲染时以该要求为准。单独的操作任务在路由后直接调用专用工具,不加载创作技能。单独的 PDF 导出在检查复制出的文件以 `%PDF-` 开头后即结束,不加载 `office-pdf`。输入为 PDF 时加载 `office-pdf`:用 pypdf 提取文字、拆分、合并、加密和填写表单,只在页面文字为空或乱码、版面或图表重要、或用户要求图片时用 `office_render` 渲染相关页。
|
||||
模型依据任务选择技能;宿主不会根据文件扩展名注入完整说明。资源完整时,五个技能均列入目录,可通过 `skill` 按名称加载或由用户显式调用。加载 Office 技能后,三个 Office 工具从下一步开始可用;工具不在列表中时(例如 PTC 模式 resume 或 fork 之后),技能会指示模型重新加载 `office`。python-docx、openpyxl 和 python-pptx 无法读取的旧格式 `.doc`、`.xls`、`.ppt` 文件,先用 `office_convert` 转换再编辑。用户要求的外观修改,包括电子表格单元格填充和文本对齐,即使没有明确要求视觉检查,也需要渲染,演示文稿中新增或修改的幻灯片内容同样需要渲染;用户明确要求跳过渲染时以该要求为准。单独的操作任务在路由后直接调用专用工具,不加载创作技能。单独的 PDF 导出在检查复制出的文件以 `%PDF-` 开头后即结束,不加载 `office-pdf`。输入为 PDF 时加载 `office-pdf`:它描述 pypdf 的十项能力,从文字提取、页面组织到批注、表单、书签、附件和元数据,由这些能力组合出水印、扁平化表单等任务;只在页面文字为空或乱码、版面或图表重要、修改后的页面需要视觉检查、或用户要求图片时用 `office_render` 渲染相关页。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
@@ -57,7 +57,7 @@ flowchart TD
|
||||
C --> D["Author and validate content, structure and data"]
|
||||
D -->|No additional operation needed| F["Deliver"]
|
||||
|
||||
B -->|PDF input| G["skill(office-pdf): pypdf text, pages, and forms"]
|
||||
B -->|PDF input| G["skill(office-pdf): pypdf capabilities combined per task"]
|
||||
G -->|Text and structure checks suffice| F
|
||||
G -->|Empty or garbled text, layout, or visual check| R
|
||||
|
||||
@@ -118,7 +118,7 @@ flowchart TD
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
技能结果追加到历史中,操作完成后已加载文本或图片仍保留在历史中。挂载 `tool-office` 时,首次成功加载 Office 技能会在下一步启用三个工具声明。因资源不可读而省略或移除的技能会改变目录,后续步骤会将其作为目录更新发布。字符估算采用 `ceil(字符数 / 4)`:摘要最多 50 token,路由正文最多 200 token;每个创作正文最多为其记录的早期估算的 70%:`office-docx` 为 1,688 token,`office-pptx` 为 1,879 token,`office-xlsx` 为 2,330 token。`office-pdf` 没有早期估算,其正文最多 1,500 token,其摘要使每个目录增加约 23 token。配置不变时,追加的 Python 环境说明保持不变,并计入各技能正文。技能包装、通用目录、shell 与 Office 工具声明和 `load_workspace_dependencies` 单独计费;这些估算不等同于服务端 usage。
|
||||
技能结果追加到历史中,操作完成后已加载文本或图片仍保留在历史中。挂载 `tool-office` 时,首次成功加载 Office 技能会在下一步启用三个工具声明。因资源不可读而省略或移除的技能会改变目录,后续步骤会将其作为目录更新发布。字符估算采用 `ceil(字符数 / 4)`:摘要最多 50 token,路由正文最多 200 token;每个创作正文最多为其记录的早期估算的 70%:`office-docx` 为 1,688 token,`office-pptx` 为 1,879 token,`office-xlsx` 为 2,330 token。`office-pdf` 没有早期估算,其正文覆盖十项能力,最多 3,000 token,其摘要使每个目录增加约 23 token。配置不变时,追加的 Python 环境说明保持不变,并计入各技能正文。技能包装、通用目录、shell 与 Office 工具声明和 `load_workspace_dependencies` 单独计费;这些估算不等同于服务端 usage。
|
||||
|
||||
## 已知限制与后续工作
|
||||
|
||||
|
||||
@@ -5,16 +5,21 @@ description: Read, extract, inspect, split, merge, protect, or fill an existing
|
||||
|
||||
# PDF files
|
||||
|
||||
Use `pypdf` for text, metadata, pages, protection, and form fields unless an explicit user or applicable AGENTS.md requirement names another library. Run Python as described in the Python environment section below. Do not install command-line PDF tools or OCR engines.
|
||||
Use `pypdf` unless an explicit user or applicable AGENTS.md requirement names another library. Run Python as described in the Python environment section below. Do not install command-line PDF tools or OCR engines.
|
||||
|
||||
Keep scripts and outputs in the task workspace; runtime and skill resources are read-only. Write results to a new file and leave the source PDF unchanged unless an in-place edit is requested.
|
||||
|
||||
Name Python scripts for their task, such as `split_pdf.py`; avoid module names such as `pypdf.py` or `inspect.py` that shadow imported libraries.
|
||||
|
||||
## Read and inspect
|
||||
Keep scripts and outputs in the task workspace; runtime and skill resources are read-only. Write results to a new file and leave the source PDF unchanged unless an in-place edit is requested. Name Python scripts for their task, such as `split_pdf.py`; avoid module names such as `pypdf.py` or `inspect.py` that shadow imported libraries.
|
||||
|
||||
If `office_render`, `office_convert`, or `office_recalculate` is not in your tools, load `office` with `skill`; they appear next step.
|
||||
|
||||
Rules for every capability below:
|
||||
|
||||
- An encrypted file needs `reader.decrypt(password)` first. pypdf alone opens RC4-protected files; AES-protected files, which most current producers write, also need the `cryptography` package, which is not installed. When it is missing, report that the file cannot be opened.
|
||||
- pypdf cannot retype or reflow existing text, and nothing here removes content permanently: cropped, covered, or de-annotated areas keep their text and images in the file, so none of these is a redaction. To change wording, edit the source document and convert it again; without a source, offer annotations or explain the limit.
|
||||
- New pages, such as a cover, stamp, or header, come from `office-docx` or `office-pptx` plus `office_convert` with `format: "pdf"`; copy the temporary file into the workspace. `office_convert` does not accept PDF input.
|
||||
- User page numbers start at 1; pypdf indexes start at 0, and a range such as `pages=(0, 2)` excludes its end.
|
||||
|
||||
## Read and extract content
|
||||
|
||||
Start with text; a page image costs many times more context than its text:
|
||||
|
||||
```python
|
||||
@@ -27,43 +32,92 @@ for number, page in enumerate(reader.pages, start=1):
|
||||
print(page.extract_text())
|
||||
```
|
||||
|
||||
`extract_text(extraction_mode="layout")` keeps horizontal positions for tables. Extracted text can lose reading order and formatting and omits images; `page.images` yields embedded images with `.name` and `.data`.
|
||||
`extract_text(extraction_mode="layout")` keeps approximate horizontal positions for tables; `orientations=(0,)` keeps upright text only; `visitor_text=lambda text, cm, tm, font, size: ...` receives each run with its position `(tm[4], tm[5])` for filtering by region. `page.images` yields embedded images with `.name` and `.data`: the pictures placed on a page, not an image of the page. Extraction performs no OCR and can lose reading order, table structure, and formatting.
|
||||
|
||||
Call `office_render` with `pages` for pages whose text is empty or garbled, which marks a scan or an image-only page; for layout, figures, charts, stamps, or signatures; or when the user asks for images or visual inspection. Render only the pages you need, a few at a time; raise `dpi` above the default 144 only for small print. Text you read from rendered pages is a transcription; say so. No OCR engine is available, so a scan gains no searchable text layer and a long scan is read selectively.
|
||||
## Render and read pages
|
||||
|
||||
An encrypted file needs `reader.decrypt(password)` before reading. pypdf alone opens RC4-protected files; AES-protected files, which most current producers write, also need the `cryptography` package. When it is missing, report that the file cannot be opened.
|
||||
Call `office_render` with `pages` for pages whose text is empty or garbled, which marks a scan or an image-only page; for layout, figures, charts, stamps, or signatures; to check a changed page; or when the user asks for images or visual inspection. Render only the pages you need, a few at a time; raise `dpi` above the default 144 only for small print. Text you read from rendered pages is a transcription; say so. It adds no text layer to the PDF, and a long scan is read selectively.
|
||||
|
||||
## Pages, protection, and forms
|
||||
## Organize pages
|
||||
|
||||
`PdfWriter` builds the result and never modifies its inputs. Page selections are zero-based with an exclusive end:
|
||||
`PdfWriter` builds the result without modifying its inputs; `PdfWriter(clone_from="input.pdf")` copies one file for single-file edits, and one writer per range splits a file:
|
||||
|
||||
```python
|
||||
from pypdf import PdfWriter
|
||||
|
||||
writer = PdfWriter()
|
||||
writer.append("report.pdf", pages=(0, 2)) # pages 1-2
|
||||
writer.append("appendix.pdf")
|
||||
writer.pages[0].rotate(90)
|
||||
writer.add_metadata({"/Title": "Report with appendix"})
|
||||
writer.append("cover.pdf")
|
||||
writer.append("report.pdf", pages=[2, 0, 1]) # pages 3, 1, 2
|
||||
writer.merge(1, "appendix.pdf", pages=(0, 2)) # pages 1-2, after the cover
|
||||
del writer.pages[-1]
|
||||
writer.write("combined.pdf")
|
||||
```
|
||||
|
||||
`PdfWriter(clone_from="input.pdf")` copies one file for single-file edits; one writer per page splits a file. Cloning a decrypted reader into a new writer removes protection. The recommended AES encryption needs the missing `cryptography` package; when the user asks to protect a file, explain this limit. Call `writer.encrypt("password", algorithm="RC4-128")` only if the user accepts insecure RC4, and name RC4-128 on delivery. `page.merge_transformed_page(stamp, Transformation().scale(0.5))`, with `Transformation` imported from pypdf, overlays a watermark or stamp page taken from another PDF, which `office_convert` can produce from a document.
|
||||
Take a repeated page from a reader again; inserting an existing `writer.pages` entry shares one object, so a later rotation or overlay changes every copy.
|
||||
|
||||
For a form, list fields with `reader.get_fields()`; a checkbox lists its states under `/_States_`. Fill every page of a cloned writer with `writer.update_page_form_field_values(page, {"name": "Ada Lovelace", "agree": "/Yes"}, auto_regenerate=False)`. A printed form without fields cannot be filled this way, and XFA forms are unsupported; place `pypdf.annotations.FreeText` notes by coordinates only when the user accepts annotations.
|
||||
## Transform page geometry
|
||||
|
||||
pypdf cannot retype or reflow existing text or remove content permanently. To change the wording of a PDF, edit its source document and convert it again; without a source, offer annotations or explain the limit.
|
||||
`page.rotate(90)` turns the displayed page clockwise. `page.mediabox` is the paper and `page.cropbox` the visible area, in points from the lower-left corner of the unrotated page; set `page.cropbox.lower_left` and `.upper_right` to trim margins. `page.scale_to(595, 842)` resizes page and content to A4; `page.add_transformation(Transformation().scale(0.9).translate(30, 40))` moves content inside unchanged boxes. Render changed pages to check for clipped or out-of-bounds content.
|
||||
|
||||
## Create and convert
|
||||
## Overlay page content
|
||||
|
||||
To create a PDF, write the content with `office-docx` or `office-pptx`, call `office_convert` with `format: "pdf"`, and copy the temporary file to the destination. `office_convert` does not accept PDF input.
|
||||
Draw a page from another PDF over or under each target page:
|
||||
|
||||
PDF to Word is a reconstruction: extract text with pypdf, load `office-docx` and build the document with python-docx, keeping the headings, paragraphs, and simple tables you can recognize. Layout, fonts, embedded images, and scanned pages do not carry over; deliver the result as a text reconstruction, never as a faithful conversion.
|
||||
```python
|
||||
from pypdf import PdfReader, PdfWriter, Transformation
|
||||
|
||||
stamp = PdfReader("stamp.pdf").pages[0]
|
||||
writer = PdfWriter(clone_from="input.pdf")
|
||||
for page in writer.pages:
|
||||
page.merge_transformed_page(stamp, Transformation().scale(0.5).translate(400, 20), over=True)
|
||||
writer.write("stamped.pdf")
|
||||
```
|
||||
|
||||
`over=False` places a watermark beneath the content. Create overlay pages with the rule above; visible page numbers need one generated page per target page. For several pages per sheet, merge scaled pages onto `writer.add_blank_page(width, height)`.
|
||||
|
||||
## Annotations and links
|
||||
|
||||
Read `page.get("/Annots", [])`, calling `.get_object()` on each entry for `/Subtype`, `/Rect`, and `/Contents`. Add with `writer.add_annotation(page_index, annotation)` using `Text`, `FreeText`, `Highlight` with `quad_points` and `highlight_color="ffff00"`, `Rectangle`, `Line`, or `Link` with `url` or `target_page_index` from `pypdf.annotations`. Remove by type, such as `writer.remove_annotations(subtypes=["/Highlight", "/FreeText"])`; without `subtypes` it also removes links and the `/Widget` controls of form fields. Render the page to check position and display, and verify link targets.
|
||||
|
||||
## Interactive forms
|
||||
|
||||
List fields with `reader.get_fields()`; a checkbox lists its states under `/_States_`. `writer.update_page_form_field_values(None, {"name": "Ada Lovelace", "agree": "/Yes"}, auto_regenerate=False)` fills every page of a cloned writer and writes appearances. A field's value and its visible appearance are separate; render the page to see the result. To flatten, pass every field with `flatten=True`, which draws the values into the page content, then `writer.remove_annotations(subtypes="/Widget")` and `del writer.root_object["/AcroForm"]`. A printed or scanned form has no fields, and XFA forms are unsupported; place `FreeText` annotations by coordinates only when the user accepts annotations.
|
||||
|
||||
## Document navigation
|
||||
|
||||
`reader.outline` nests bookmarks as lists; `reader.get_destination_page_number(item)` resolves one. `part = writer.add_outline_item("Part 1", 0)` and `writer.add_outline_item("Section 1.1", 2, parent=part)` add a hierarchy; `writer.append(path, outline_item="Title")` bookmarks each merged file. `reader.named_destinations` and `writer.add_named_destination("appendix", 9)` manage named targets. `reader.page_labels` lists displayed page numbers; `writer.set_page_label(0, 3, style="/r")` labels pages 1-4 as i-iv and `writer.set_page_label(4, 9, style="/D", start=1)` restarts at 1. Bookmarks are not a table-of-contents page, and labels do not change numbers printed on pages. After reordering, check where each bookmark and destination points.
|
||||
|
||||
## Embedded attachments
|
||||
|
||||
`reader.attachments` maps each name to a list of contents, because names repeat. Write extracted files under `Path(name).name` in a new directory, rename duplicates, and never open or run them. `writer.add_attachment("data.csv", data)` adds a file. To remove some, collect the entries to keep from `writer.attachments`, `del writer.root_object["/Names"]["/EmbeddedFiles"]`, and add the kept entries again; they lose descriptions and dates. `/FileAttachment` annotations on pages are separate from this list.
|
||||
|
||||
## Document management and output
|
||||
|
||||
**Metadata.** `reader.metadata` holds the document information and `reader.xmp_metadata` the separate XMP packet; viewers may show either, so change both. `writer.add_metadata({"/Title": "Report"})` sets information entries. For XMP, take `writer.xmp_metadata` or `pypdf.xmp.XmpInformation.create()`, set fields such as `xmp.dc_title = {"x-default": "Report"}`, and assign it back to `writer.xmp_metadata`. Assigning `None` to `writer.metadata` or `writer.xmp_metadata` removes it.
|
||||
|
||||
**Protection.** `PdfWriter(clone_from=reader)` after `reader.decrypt(password)` writes an unprotected copy. Protecting a file needs AES, which needs the missing `cryptography` package; explain this limit and do not fall back to RC4 by default. Call `writer.encrypt("password", algorithm="RC4-128")` only if the user accepts insecure RC4, and name RC4-128 on delivery.
|
||||
|
||||
**Optimization.** `page.compress_content_streams()` on each writer page and `writer.compress_identical_objects()` reduce size without changing appearance. Compare sizes afterward; image-heavy files shrink little, and no reduction is guaranteed.
|
||||
|
||||
**Writing.** Write to a new path. For an in-place edit, write beside the source and replace it only after the checks below pass.
|
||||
|
||||
## Combined tasks
|
||||
|
||||
| Task | Capabilities |
|
||||
|---|---|
|
||||
| Text PDF to Word | Read and extract content → build with `office-docx` |
|
||||
| Scanned PDF to Word | Render and read pages → build with `office-docx` |
|
||||
| Merge reports with chapter bookmarks | Organize pages → document navigation → write and check |
|
||||
| Watermark or page numbers | Create overlay pages → transform geometry → overlay → render |
|
||||
| Deliver a filled form as non-editable | Fill fields → check appearance → flatten → write and check |
|
||||
| Tidy and shrink a scan | Organize pages → transform geometry → optimize → render |
|
||||
|
||||
A Word reconstruction keeps the headings, paragraphs, and simple tables you can recognize; layout, fonts, and images do not carry over, so deliver it as a reconstruction, never as a faithful conversion.
|
||||
|
||||
## Check and deliver
|
||||
|
||||
Reopen the written file with `PdfReader` and verify page count and order, rotation, text of changed pages, field values, and encryption state against the request; confirm the source bytes are unchanged. Call `office_render` on the changed pages when their appearance is the deliverable, such as a stamp or a filled form, or when the user asks; a request to skip rendering takes precedence.
|
||||
Reopen the written file with `PdfReader` and verify what the request changed: page count and order, rotation and boxes, text of changed pages, annotations, field values, bookmarks and labels, attachments, metadata, and encryption state; confirm the source bytes are unchanged. Call `office_render` on changed pages when their appearance is the deliverable, such as a stamp, crop, annotation, or filled form, or when the user asks; a request to skip rendering takes precedence.
|
||||
|
||||
A fully transparent or uniformly blank image of populated content means the renderer failed, which ends visual checks for the task and leaves the source as it is. When content and structure checks pass, state the visual status only as "Content and structure checks passed; visual inspection was not completed." or "内容与结构检查通过;视觉检查未完成。".
|
||||
|
||||
Report what was not possible: image-only pages, transcribed text, dropped formatting, unfilled fields. Call `present({"files":[{"path":"combined.pdf"}]})` with the actual final PDF or DOCX path. It exposes the current file without copying or preserving its bytes; keep it in place and omit scripts and intermediate files unless requested. If `present` is unavailable, use the session's supported file delivery method.
|
||||
Report what was not possible: image-only pages, transcribed text, dropped formatting, unfilled fields, unsupported protection. Call `present({"files":[{"path":"combined.pdf"}]})` with the actual final PDF or DOCX path. It exposes the current file without copying or preserving its bytes; keep it in place and omit scripts and intermediate files unless requested. If `present` is unavailable, use the session's supported file delivery method.
|
||||
@@ -42,7 +42,7 @@ describe('bundled Office skills', () => {
|
||||
const pdf = (await ctx.skills.get('office-pdf'))!
|
||||
expect(pdf.description).toBe('Read, extract, inspect, split, merge, protect, or fill an existing PDF; PDF to Word (.pdf).')
|
||||
// The budget includes the appended Python environment section.
|
||||
expect(Math.ceil(pdf.content.length / 4)).toBeLessThanOrEqual(1500)
|
||||
expect(Math.ceil(pdf.content.length / 4)).toBeLessThanOrEqual(3000)
|
||||
expect(pdf.content).toContain('`pypdf`')
|
||||
expect(pdf.content).toContain('`office_render` with `pages`')
|
||||
expect(pdf.content).toContain('"Content and structure checks passed; visual inspection was not completed." or "内容与结构检查通过;视觉检查未完成。"')
|
||||
|
||||
@@ -24,7 +24,9 @@ from pptx.chart.data import CategoryChartData
|
||||
from pptx.enum.chart import XL_CHART_TYPE
|
||||
from pptx.util import Inches
|
||||
from pypdf import PdfReader, PdfWriter
|
||||
from pypdf.annotations import Text
|
||||
from pypdf.errors import DependencyError
|
||||
from pypdf.xmp import XmpInformation
|
||||
from pypdf.generic import ArrayObject, DictionaryObject, FloatObject, NameObject, NumberObject, TextStringObject
|
||||
|
||||
|
||||
@@ -128,11 +130,21 @@ def main():
|
||||
pdf.add_blank_page(width=200, height=100)
|
||||
pdf.add_blank_page(width=100, height=200).rotate(90)
|
||||
pdf.add_metadata({"/Title": "Office PDF"})
|
||||
xmp = XmpInformation.create()
|
||||
xmp.dc_title = {"x-default": "Office PDF"}
|
||||
pdf.xmp_metadata = xmp
|
||||
pdf.add_attachment("data.csv", b"a,b")
|
||||
pdf.add_attachment("data.csv", b"c,d")
|
||||
pdf.set_page_label(0, 0, style="/r")
|
||||
pdf.set_page_label(1, 1, style="/D", start=1)
|
||||
pdf.write(root / "document.pdf")
|
||||
reopened_pdf = PdfReader(root / "document.pdf")
|
||||
assert len(reopened_pdf.pages) == 2
|
||||
assert reopened_pdf.pages[1].rotation == 90
|
||||
assert reopened_pdf.metadata.title == "Office PDF"
|
||||
assert reopened_pdf.xmp_metadata.dc_title == {"x-default": "Office PDF"}
|
||||
assert dict(reopened_pdf.attachments) == {"data.csv": [b"a,b", b"c,d"]}
|
||||
assert reopened_pdf.page_labels == ["i", "1"]
|
||||
|
||||
form = PdfWriter()
|
||||
form.add_blank_page(width=300, height=200)
|
||||
@@ -143,15 +155,26 @@ def main():
|
||||
NameObject("/DA"): TextStringObject("/Helv 12 Tf 0 g"),
|
||||
}))
|
||||
form.root_object[NameObject("/AcroForm")] = DictionaryObject({NameObject("/Fields"): ArrayObject([field.indirect_reference])})
|
||||
form.add_annotation(0, Text(text="Review note", rect=(220, 150, 240, 170)))
|
||||
form.write(root / "form.pdf")
|
||||
filled = PdfWriter(clone_from=root / "form.pdf")
|
||||
for page in filled.pages:
|
||||
filled.update_page_form_field_values(page, {"name": "Ada Lovelace"}, auto_regenerate=False)
|
||||
filled.update_page_form_field_values(None, {"name": "Ada Lovelace"}, auto_regenerate=False)
|
||||
filled.remove_annotations(subtypes=["/Text"])
|
||||
filled.write(root / "filled.pdf")
|
||||
reopened_form = PdfReader(root / "filled.pdf")
|
||||
assert reopened_form.get_fields()["name"].value == "Ada Lovelace"
|
||||
assert reopened_form.trailer["/Root"]["/AcroForm"].get("/NeedAppearances") is not True
|
||||
assert [annotation.get_object()["/Subtype"] for annotation in reopened_form.pages[0]["/Annots"]] == ["/Widget"]
|
||||
assert "/AP" in reopened_form.pages[0]["/Annots"][0].get_object()
|
||||
flattened = PdfWriter(clone_from=root / "form.pdf")
|
||||
flattened.update_page_form_field_values(None, {"name": "Ada Lovelace"}, flatten=True)
|
||||
flattened.remove_annotations(subtypes="/Widget")
|
||||
del flattened.root_object["/AcroForm"]
|
||||
flattened.write(root / "flattened.pdf")
|
||||
reopened_flattened = PdfReader(root / "flattened.pdf")
|
||||
assert reopened_flattened.get_fields() is None
|
||||
assert "/Widget" not in [annotation.get_object()["/Subtype"] for annotation in reopened_flattened.pages[0].get("/Annots", [])]
|
||||
assert reopened_flattened.pages[0].extract_text() == "Ada Lovelace"
|
||||
|
||||
# The payload omits cryptography, so only the RC4 algorithm named by the PDF skill is available.
|
||||
try:
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"office_convert"},{"type":"tool-addition","toolName":"office_recalculate"},{"type":"tool-addition","toolName":"office_render"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_2","name":"skill","arguments":"{\"name\":\"office-pdf\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1793628044612,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628044612,"index":0,"dt":[],"id":"call_office_2","name":"skill","args":["{\"name\":\"office-pdf\"}"]},{"type":"chunk","time":1793628044612,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_2","name":"skill","arguments":"{\"name\":\"office-pdf\"}"}}},{"type":"chunk","time":1793628044612,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_office_2","name":"skill","arguments":"{\"name\":\"office-pdf\"}"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_2"},"toolCallId":"call_office_2","content":[{"type":"text","text":"<skill_content name=\"office-pdf\">\n<skill_resources>\nBase directory for this skill: {{cwd}}/office-skills/office-pdf\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n</skill_resources>\n\n<skill_instructions>\n# PDF files\n\nUse `pypdf` for text, metadata, pages, protection, and form fields unless an explicit user or applicable AGENTS.md requirement names another library. Run Python as described in the Python environment section below. Do not install command-line PDF tools or OCR engines.\n\nKeep scripts and outputs in the task workspace; runtime and skill resources are read-only. Write results to a new file and leave the source PDF unchanged unless an in-place edit is requested.\n\nName Python scripts for their task, such as `split_pdf.py`; avoid module names such as `pypdf.py` or `inspect.py` that shadow imported libraries.\n\n## Read and inspect\n\nIf `office_render`, `office_convert`, or `office_recalculate` is not in your tools, load `office` with `skill`; they appear next step.\n\nStart with text; a page image costs many times more context than its text:\n\n```python\nfrom pypdf import PdfReader\n\nreader = PdfReader(\"input.pdf\")\nprint(len(reader.pages), reader.metadata)\nfor number, page in enumerate(reader.pages, start=1):\n print(f\"--- page {number} ---\")\n print(page.extract_text())\n```\n\n`extract_text(extraction_mode=\"layout\")` keeps horizontal positions for tables. Extracted text can lose reading order and formatting and omits images; `page.images` yields embedded images with `.name` and `.data`.\n\nCall `office_render` with `pages` for pages whose text is empty or garbled, which marks a scan or an image-only page; for layout, figures, charts, stamps, or signatures; or when the user asks for images or visual inspection. Render only the pages you need, a few at a time; raise `dpi` above the default 144 only for small print. Text you read from rendered pages is a transcription; say so. No OCR engine is available, so a scan gains no searchable text layer and a long scan is read selectively.\n\nAn encrypted file needs `reader.decrypt(password)` before reading. pypdf alone opens RC4-protected files; AES-protected files, which most current producers write, also need the `cryptography` package. When it is missing, report that the file cannot be opened.\n\n## Pages, protection, and forms\n\n`PdfWriter` builds the result and never modifies its inputs. Page selections are zero-based with an exclusive end:\n\n```python\nfrom pypdf import PdfWriter\n\nwriter = PdfWriter()\nwriter.append(\"report.pdf\", pages=(0, 2)) # pages 1-2\nwriter.append(\"appendix.pdf\")\nwriter.pages[0].rotate(90)\nwriter.add_metadata({\"/Title\": \"Report with appendix\"})\nwriter.write(\"combined.pdf\")\n```\n\n`PdfWriter(clone_from=\"input.pdf\")` copies one file for single-file edits; one writer per page splits a file. Cloning a decrypted reader into a new writer removes protection. The recommended AES encryption needs the missing `cryptography` package; when the user asks to protect a file, explain this limit. Call `writer.encrypt(\"password\", algorithm=\"RC4-128\")` only if the user accepts insecure RC4, and name RC4-128 on delivery. `page.merge_transformed_page(stamp, Transformation().scale(0.5))`, with `Transformation` imported from pypdf, overlays a watermark or stamp page taken from another PDF, which `office_convert` can produce from a document.\n\nFor a form, list fields with `reader.get_fields()`; a checkbox lists its states under `/_States_`. Fill every page of a cloned writer with `writer.update_page_form_field_values(page, {\"name\": \"Ada Lovelace\", \"agree\": \"/Yes\"}, auto_regenerate=False)`. A printed form without fields cannot be filled this way, and XFA forms are unsupported; place `pypdf.annotations.FreeText` notes by coordinates only when the user accepts annotations.\n\npypdf cannot retype or reflow existing text or remove content permanently. To change the wording of a PDF, edit its source document and convert it again; without a source, offer annotations or explain the limit.\n\n## Create and convert\n\nTo create a PDF, write the content with `office-docx` or `office-pptx`, call `office_convert` with `format: \"pdf\"`, and copy the temporary file to the destination. `office_convert` does not accept PDF input.\n\nPDF to Word is a reconstruction: extract text with pypdf, load `office-docx` and build the document with python-docx, keeping the headings, paragraphs, and simple tables you can recognize. Layout, fonts, embedded images, and scanned pages do not carry over; deliver the result as a text reconstruction, never as a faithful conversion.\n\n## Check and deliver\n\nReopen the written file with `PdfReader` and veriLine truncated
|
||||
{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_2"},"toolCallId":"call_office_2","content":[{"type":"text","text":"<skill_content name=\"office-pdf\">\n<skill_resources>\nBase directory for this skill: {{cwd}}/office-skills/office-pdf\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n</skill_resources>\n\n<skill_instructions>\n# PDF files\n\nUse `pypdf` unless an explicit user or applicable AGENTS.md requirement names another library. Run Python as described in the Python environment section below. Do not install command-line PDF tools or OCR engines.\n\nKeep scripts and outputs in the task workspace; runtime and skill resources are read-only. Write results to a new file and leave the source PDF unchanged unless an in-place edit is requested. Name Python scripts for their task, such as `split_pdf.py`; avoid module names such as `pypdf.py` or `inspect.py` that shadow imported libraries.\n\nIf `office_render`, `office_convert`, or `office_recalculate` is not in your tools, load `office` with `skill`; they appear next step.\n\nRules for every capability below:\n\n- An encrypted file needs `reader.decrypt(password)` first. pypdf alone opens RC4-protected files; AES-protected files, which most current producers write, also need the `cryptography` package, which is not installed. When it is missing, report that the file cannot be opened.\n- pypdf cannot retype or reflow existing text, and nothing here removes content permanently: cropped, covered, or de-annotated areas keep their text and images in the file, so none of these is a redaction. To change wording, edit the source document and convert it again; without a source, offer annotations or explain the limit.\n- New pages, such as a cover, stamp, or header, come from `office-docx` or `office-pptx` plus `office_convert` with `format: \"pdf\"`; copy the temporary file into the workspace. `office_convert` does not accept PDF input.\n- User page numbers start at 1; pypdf indexes start at 0, and a range such as `pages=(0, 2)` excludes its end.\n\n## Read and extract content\n\nStart with text; a page image costs many times more context than its text:\n\n```python\nfrom pypdf import PdfReader\n\nreader = PdfReader(\"input.pdf\")\nprint(len(reader.pages), reader.metadata)\nfor number, page in enumerate(reader.pages, start=1):\n print(f\"--- page {number} ---\")\n print(page.extract_text())\n```\n\n`extract_text(extraction_mode=\"layout\")` keeps approximate horizontal positions for tables; `orientations=(0,)` keeps upright text only; `visitor_text=lambda text, cm, tm, font, size: ...` receives each run with its position `(tm[4], tm[5])` for filtering by region. `page.images` yields embedded images with `.name` and `.data`: the pictures placed on a page, not an image of the page. Extraction performs no OCR and can lose reading order, table structure, and formatting.\n\n## Render and read pages\n\nCall `office_render` with `pages` for pages whose text is empty or garbled, which marks a scan or an image-only page; for layout, figures, charts, stamps, or signatures; to check a changed page; or when the user asks for images or visual inspection. Render only the pages you need, a few at a time; raise `dpi` above the default 144 only for small print. Text you read from rendered pages is a transcription; say so. It adds no text layer to the PDF, and a long scan is read selectively.\n\n## Organize pages\n\n`PdfWriter` builds the result without modifying its inputs; `PdfWriter(clone_from=\"input.pdf\")` copies one file for single-file edits, and one writer per range splits a file:\n\n```python\nfrom pypdf import PdfWriter\n\nwriter = PdfWriter()\nwriter.append(\"cover.pdf\")\nwriter.append(\"report.pdf\", pages=[2, 0, 1]) # pages 3, 1, 2\nwriter.merge(1, \"appendix.pdf\", pages=(0, 2)) # pages 1-2, after the cover\ndel writer.pages[-1]\nwriter.write(\"combined.pdf\")\n```\n\nTake a repeated page from a reader again; inserting an existing `writer.pages` entry shares one object, so a later rotation or overlay changes every copy.\n\n## Transform page geometry\n\n`page.rotate(90)` turns the displayed page clockwise. `page.mediabox` is the paper and `page.cropbox` the visible area, in points from the lower-left corner of the unrotated page; set `page.cropbox.lower_left` and `.upper_right` to trim margins. `page.scale_to(595, 842)` resizes page and content to A4; `page.add_transformation(Transformation().scale(0.9).translate(30, 40))` moves content inside unchanged boxes. Render changed pages to check for clipped or out-of-bounds content.\n\n## Overlay page content\n\nDraw a page from another PDF over or under each target page:\n\n```python\nfrom pypdf import PdfReader, PdfWriter, Transformation\n\nstamp = PdfReader(\"stamp.pdf\").pages[0]\nwriter = PdfWriter(clone_from=\"input.pdf\")\nfor page in writer.pages:\n paLine truncated
|
||||
{"type":"step/end","data":{"turn":1,"step":2}}
|
||||
{"type":"step/start","data":{"turn":1,"step":3}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1793628044644,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793628044645,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1793628044645,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1793628044645,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1793628044645,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
|
||||
|
||||
Reference in new issue
Block a user