ofdkit 0.3.1__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {ofdkit-0.3.1 → ofdkit-0.5.0}/PKG-INFO +76 -17
  2. {ofdkit-0.3.1 → ofdkit-0.5.0}/README.md +74 -15
  3. {ofdkit-0.3.1 → ofdkit-0.5.0}/pyproject.toml +2 -2
  4. ofdkit-0.5.0/src/ofdkit/_guard.py +82 -0
  5. ofdkit-0.5.0/src/ofdkit/_sources.py +108 -0
  6. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/batch.py +133 -87
  7. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/cli.py +87 -18
  8. ofdkit-0.5.0/src/ofdkit/describe.py +263 -0
  9. ofdkit-0.5.0/src/ofdkit/desktop.py +716 -0
  10. ofdkit-0.5.0/src/ofdkit/desktop_data.py +255 -0
  11. ofdkit-0.5.0/src/ofdkit/desktop_search.py +198 -0
  12. ofdkit-0.5.0/src/ofdkit/document_tools.py +279 -0
  13. ofdkit-0.5.0/src/ofdkit/export_output.py +54 -0
  14. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/invoice.py +19 -7
  15. ofdkit-0.5.0/src/ofdkit/mcp_server.py +253 -0
  16. ofdkit-0.5.0/src/ofdkit/onboarding.py +198 -0
  17. ofdkit-0.5.0/src/ofdkit/page_range.py +71 -0
  18. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/rename.py +115 -34
  19. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/report.py +10 -1
  20. ofdkit-0.5.0/src/ofdkit/review.py +494 -0
  21. ofdkit-0.5.0/src/ofdkit/review_diff.py +451 -0
  22. ofdkit-0.5.0/src/ofdkit/samples/README.txt +5 -0
  23. ofdkit-0.5.0/src/ofdkit/samples/multi-page-sizes.ofd +0 -0
  24. ofdkit-0.5.0/src/ofdkit/text_bundle.py +124 -0
  25. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/xlsx.py +55 -23
  26. ofdkit-0.3.1/src/ofdkit/describe.py +0 -153
  27. ofdkit-0.3.1/src/ofdkit/mcp_server.py +0 -132
  28. {ofdkit-0.3.1 → ofdkit-0.5.0}/LICENSE +0 -0
  29. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/__init__.py +0 -0
  30. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/__main__.py +0 -0
  31. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/_xml.py +0 -0
  32. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/document.py +0 -0
  33. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/errors.py +0 -0
  34. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/layout.py +0 -0
  35. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/markdown.py +0 -0
  36. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/markitdown_plugin.py +0 -0
  37. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/package.py +0 -0
  38. {ofdkit-0.3.1 → ofdkit-0.5.0}/src/ofdkit/py.typed +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ofdkit
3
- Version: 0.3.1
4
- Summary: Read OFD documents (GB/T 33190) and Chinese e-invoices: text, invoice fields, and AI tool integrations.
3
+ Version: 0.5.0
4
+ Summary: Read and search OFD documents (GB/T 33190), extract Chinese e-invoices, and review or export results.
5
5
  Keywords: ofd,gb/t 33190,e-invoice,fapiao,电子发票,数电票,mcp
6
6
  License-Expression: Apache-2.0
7
7
  License-File: LICENSE
@@ -32,11 +32,17 @@ Description-Content-Type: text/markdown
32
32
 
33
33
  A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese fixed-layout format used for e-invoices and official documents): extract text and invoice fields, and use them from AI tools.
34
34
 
35
- > 状态:0.3 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
36
- > Status: 0.3, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
35
+ > 状态:0.5 版,更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
36
+ > Status: 0.5. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
37
37
 
38
38
  ## 能做什么 / What it does
39
39
 
40
+ - Windows x64 用户可下载便携包,解压后双击运行。桌面窗口可搜索文字、跳页、选页保存,并筛选批量结果。
41
+ Windows x64 users can extract and launch the portable app. Search text, jump to pages, save selected pages, and filter batch results.
42
+ - 桌面的跨文件搜索可以查一个 OFD 文件、文件夹或 ZIP。结果显示原页码、行号和原文片段。
43
+ Desktop search finds text across an OFD file, folder or ZIP and shows page and line references.
44
+ - 用桌面窗口选 OFD 文件、逐页读文字,或把发票文件夹和 ZIP 导出到 Excel。文件在本机处理。
45
+ Open OFD text page by page or export invoices from a folder or ZIP in a local desktop window.
40
46
  - 看发票:一条命令显示发票号码、日期、购买方、销售方、金额和明细。
41
47
  Show an invoice: number, date, buyer, seller, amounts and line items, with one command.
42
48
  - 把一个文件夹里的发票汇总到 Excel,也能直接读税务平台批量下载的 .zip 压缩包。发票号码保持原样(不会变成 2.4E+19),金额可以直接求和,重复的发票会标出来。
@@ -45,6 +51,12 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
45
51
  For reimbursement: check that invoices are made out to the right buyer, and rename invoice files after their contents, with a preview and an undo.
46
52
  - 按阅读顺序提取文字,包括模板和复合对象里的文字。
47
53
  Text in reading order, including text in templates and composite objects.
54
+ - 跨文件搜索关键词,导出逐页 JSON 和文字坐标,或把一批 OFD 保存成一个文字 ZIP。
55
+ Search across files, export page data and positioned text runs, or bundle a batch of text exports in a ZIP.
56
+ - 按日期、购销方和问题筛选发票,检查金额与明细的一致性,导出单独的复核表。
57
+ Filter invoice review by date, party and issue, check extracted amounts, and export a review workbook.
58
+ - 对比两次保存的复核结果,查看新发现、仍存在和已处理的问题。
59
+ Compare two saved review reports to track new, persistent and resolved findings.
48
60
  - 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。
49
61
  For programs and AI: invoice fields as JSON, an MCP server, an Agent Skill and a MarkItDown plugin.
50
62
  - 只用 Python 标准库,没有任何第三方依赖;能读很多不规范的文件(路径写法不对、编码不对、XML 前缀错误等)。
@@ -52,15 +64,30 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
52
64
 
53
65
  ## 快速上手 / Quick start
54
66
 
55
- 1. 安装 [Python](https://www.python.org/downloads/) 3.10 或更新版本。Windows 上安装时请勾选 "Add python.exe to PATH"。
67
+ Windows x64 可在 [GitHub 发布页](https://github.com/Edgar-311/ofdkit/releases/latest) 下载 `ofdkit-*-windows-x64.zip`。完整解压后双击 `ofdkit.exe`,然后点“试用样例”开始。命令行、Python 库和 AI 接入可按下面的方法安装。
68
+ On Windows x64, download the portable ZIP, extract it, and open `ofdkit.exe`. Use the Python package for the CLI, library and AI integrations.
69
+
70
+ 第一次用命令行?先看 [Windows 新手指南](https://github.com/Edgar-311/ofdkit/blob/main/docs/quickstart.zh-CN.md):包含普通测试样例、带空格的路径写法、Excel 输出位置和常见报错处理。
71
+ New to the command line? The [Windows beginner guide (Chinese)](https://github.com/Edgar-311/ofdkit/blob/main/docs/quickstart.zh-CN.md) includes a synthetic sample and troubleshooting.
72
+
73
+ 1. 安装 [Python](https://www.python.org/downloads/) 3.10 或更新版本,安装后重新打开终端。
56
74
  Install Python 3.10 or newer.
57
75
  2. 打开命令行(Windows 在开始菜单搜索"终端"或"cmd",Mac 打开"终端"),安装 ofdkit:
58
76
  Open a terminal and install ofdkit:
59
77
 
60
78
  ```bash
61
- pip install ofdkit
79
+ python -m pip install --upgrade ofdkit
80
+ python -m ofdkit --version
62
81
  ```
63
82
 
83
+ 如果 Windows 上 `python` 不可用而 `py` 可用,把上述 `python` 换成 `py`;macOS / Linux 通常使用 `python3`。下文的 `ofdkit` 命令也可以写成 `python -m ofdkit`,使用与安装时相同的 Python。
84
+ Use the same Python to install and run. `python -m ofdkit` also works when the `ofdkit` command is not on PATH.
85
+
86
+ 想用鼠标操作?运行 `python -m ofdkit gui`。在“查看 OFD”选文件,或在“批量复核”选文件夹或 ZIP。桌面窗口需要 Python 的 Tk 支持,可用 `python -m tkinter` 检查。[桌面使用指南](https://github.com/Edgar-311/ofdkit/blob/main/docs/desktop.zh-CN.md)
87
+ Run `python -m ofdkit gui` to open the desktop window. Use `python -m tkinter` to check Tk support.
88
+ 用 `python -m ofdkit demo --gui` 打开内置的三页样例,或用 `python -m ofdkit doctor --check-window` 检查安装和图形窗口。
89
+ Use `python -m ofdkit demo --gui` for an offline demo or `python -m ofdkit doctor --check-window` to test the installation and GUI.
90
+
64
91
  3. 看一张发票(把文件拖进命令行窗口就能填上路径):
65
92
  Show an invoice (drag the file into the terminal window to type its path):
66
93
 
@@ -94,8 +121,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
94
121
  ofdkit batch 发票文件夹 -o 发票汇总.xlsx
95
122
  ```
96
123
 
97
- Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红并写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行。
98
- The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red with the reason) and 明细 (one row per line item). Totals use SUBTOTAL, so they follow filters.
124
+ Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红,有其他提醒的发票(抬头不对、金额缺少或不是数字)标橙,都在"提醒"一栏写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行;不是数字的金额保留原样、不算进合计,合计下面会注明有几张。
125
+ The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red, other reminders such as another buyer or an amount that is missing or not a number in orange, each explained) and 明细 (one row per line item). Totals use SUBTOTAL, so they follow filters.
99
126
 
100
127
  5. 检查发票抬头:加上 `--buyer`,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次:
101
128
  Check who the invoices are made out to: with `--buyer`, invoices for another buyer name or tax ID are flagged (orange in Excel). Repeat it to check both:
@@ -104,8 +131,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
104
131
  ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
105
132
  ```
106
133
 
107
- 6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML 会一起改;改名记录可以用 `--undo` 改回去:
108
- Rename invoice files after their contents. Without `--apply` it only previews; PDF and XML copies with the same name are renamed too; `--undo` restores the old names from the log:
134
+ 6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML 会一起改(其中一个改不了,这张发票的文件都保持原名);改名前会先写好改名记录,写不了就一个文件也不改;用 `--undo` 可以按记录改回去,运行几次都没关系:
135
+ Rename invoice files after their contents. Without `--apply` it only previews; PDF and XML copies with the same name are renamed too (if one cannot be, that invoice's files all keep their names); the log is written before anything is renamed, and nothing is renamed if it cannot be; `--undo` restores the old names from the log and is safe to run again:
109
136
 
110
137
  ```bash
111
138
  ofdkit rename 发票文件夹 # 预览 / preview
@@ -122,18 +149,44 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
122
149
  ofdkit 文件.ofd # 看发票,不是发票就显示文字 / show an invoice, or the text
123
150
  ofdkit 文件夹或压缩包.zip # 发票列表和合计 / list invoices with totals
124
151
  ofdkit batch 文件夹 -o 发票汇总.xlsx # 导出 Excel / export to Excel
152
+ ofdkit batch 文件夹 --exclude-duplicates -o 发票汇总.xlsx # 合计时排除一致的重复记录
125
153
  ofdkit batch 文件夹 -o 发票汇总.csv # 导出 CSV(给程序用)/ export CSV for programs
126
154
  ofdkit 文件夹 --buyer 公司名或税号 # 检查发票抬头 / check the buyer
127
155
  ofdkit rename 文件夹 # 按内容改名(先预览)/ rename after contents (preview first)
128
156
  ofdkit text 文件.ofd # 提取文字 / print text
157
+ ofdkit text 文件.ofd --pages 1,3-5 --markdown -o 摘录.md # 提取指定页
129
158
  ofdkit invoice 发票.ofd # 发票字段(JSON)/ invoice fields as JSON
130
159
  ofdkit info 文件.ofd # 页数、作者等信息 / pages and metadata
131
160
  ofdkit describe 文件.ofd -o 结构.json # 打码的结构,用于报告问题 / masked structure for bug reports
161
+ ofdkit gui # 打开桌面窗口 / open the desktop window
162
+ ofdkit search "付款条件" 文件夹 -r # 跨文件查文字,显示页码和上下文
163
+ ofdkit pages 文件.ofd --pages 2-4 --runs -o 页面.json # 导出页号、文字、尺寸和坐标
164
+ ofdkit export-text 文件夹 -r --markdown -o 文本.zip # 批量导出文字和文件索引
165
+ ofdkit review 文件夹 --only-issues -o 复核.xlsx # 把需要人工核对的记录单独列出
166
+ ofdkit review-diff 上次.json 本次.json # 比较两次复核结果
167
+ ofdkit demo # 试读内置样例 / read the included example
168
+ ofdkit doctor # 检查安装和样例 / check this installation
169
+ ofdkit doctor --file 文件.ofd -o 诊断.json # 输出不含文件路径和正文的读取诊断
132
170
  ```
133
171
 
172
+ 搜索和逐页导出的参数见[文档工具指南](https://github.com/Edgar-311/ofdkit/blob/main/docs/document-tools.zh-CN.md)。
173
+
174
+ 发票复核的筛选、问题代码和表格说明见[发票复核指南](https://github.com/Edgar-311/ofdkit/blob/main/docs/invoice-review.zh-CN.md)。
175
+
176
+ `export-text` 接受多个文件、文件夹或 ZIP。输出使用编号文件名,在 `manifest.json` 中对应原名称、ZIP 成员和读取提示。默认保留已经读出的文档,`--strict` 在读取不完整时保留旧报表。
177
+
134
178
  `show`、`batch` 和 `rename` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
135
179
  Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
136
180
 
181
+ `--pages 1,3-5` 会按原文顺序提取第 1、3、4、5 页。合用 `--markdown` 时,每节保留原页码,只输出选定页的文字。
182
+ With `--pages`, text or Markdown contains only the selected pages, in the original order.
183
+
184
+ `--exclude-duplicates` 只影响金额合计。带有相同发票标识且关键信息和金额一致的记录只计一次。信息冲突或金额不全的组会全部保留在合计中,请人工核对。使用该选项时,Excel 显示整表合计,筛选时合计数不变。Excel 和 CSV 都保留所有行,CSV 的合计显示在命令行提示中。
185
+ With `--exclude-duplicates`, matching copies count once in totals. Conflicting or incomplete groups stay in totals for review. Excel shows a fixed whole-report total. Excel and CSV keep all rows.
186
+
187
+ 导出结果请使用新文件名,保留原 OFD 和 ZIP。程序会检查输出路径,只有新文件保存完整才会替换同名旧报表。
188
+ Exports protect the source and replace an existing report only after the new file has been written in full.
189
+
137
190
  `ofdkit invoice` 的输出示例(数据是虚构的)/ Example output (fictional data):
138
191
 
139
192
  ```json
@@ -161,8 +214,8 @@ Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is
161
214
  }
162
215
  ```
163
216
 
164
- 金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",`warnings` 里会提示。
165
- Amounts are decimal strings, so no precision is lost. `warnings` notes totals that do not add up.
217
+ 金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",或者某个金额不是数字(比如"无法识别",这时保留原样),`warnings` 里会提示。汇总时只加真正的数字:0 就是 0,缺少的和不是数字的不算进合计,并单独计数(`not_summed`)。
218
+ Amounts are decimal strings, so no precision is lost. `warnings` notes totals that do not add up and amounts that are not numbers (kept as found). Summaries add only real numbers: 0 counts as 0, while missing amounts and amounts that are not numbers are left out and counted in `not_summed`.
166
219
 
167
220
  ## 在 AI 工具里使用 / Use from AI tools
168
221
 
@@ -171,12 +224,18 @@ Amounts are decimal strings, so no precision is lost. `warnings` notes totals th
171
224
  让 Claude、Codex、Cursor 等 AI 工具直接读取 OFD 文件。需要先安装 [uv](https://docs.astral.sh/uv/)。所有工具都是只读的。
172
225
  Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires [uv](https://docs.astral.sh/uv/). All tools are read-only.
173
226
 
227
+ 已在[官方 MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.Edgar-311/ofdkit) 上架,名字是 `io.github.Edgar-311/ofdkit`;支持这个目录的工具可以直接搜索安装。
228
+ Listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.Edgar-311/ofdkit) as `io.github.Edgar-311/ofdkit`; tools that read the registry can install it from there.
229
+
174
230
  | 工具 / Tool | 作用 / What it does |
175
231
  | --- | --- |
176
232
  | `read_ofd_text` | 按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range |
233
+ | `read_ofd_pages` | 结构化逐页文字和尺寸 / structured page text and dimensions |
234
+ | `search_ofd_text` | 搜索本机 OFD 文档,返回页码、行号和片段 / local text search with page and line references |
177
235
  | `read_ofd_invoice` | 发票字段 / invoice fields |
178
236
  | `ofd_info` | 页数、尺寸、元数据 / pages, sizes, metadata |
179
- | `list_ofd_invoices` | 汇总一个文件夹里的发票,可以检查抬头 / summarise a folder of invoices, optionally checking the buyer |
237
+ | `list_ofd_invoices` | 汇总文件夹里的发票,可查抬头或去重合计 / folder totals with buyer and duplicate options |
238
+ | `review_ofd_invoices` | 检查金额、明细及提取问题 / check internally inconsistent fields or extraction issues |
180
239
 
181
240
  Claude Code:
182
241
 
@@ -205,8 +264,8 @@ command = "uvx"
205
264
  args = ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
206
265
  ```
207
266
 
208
- 加上 `--root 文件夹` 可以只允许读取这个文件夹里的文件。
209
- Add `--root FOLDER` to allow only files inside that folder.
267
+ 加上 `--root 文件夹` 可以只允许读取这个文件夹里的文件。判断的是文件的真实位置:文件夹里指向外面的快捷方式式链接(符号链接、Windows 的目录联接)不会被读取,汇总文件夹时会跳过并计数(`skipped_outside_root`)。
268
+ Add `--root FOLDER` to allow only files inside that folder. The check uses each file's real location, so symbolic links and Windows directory junctions that lead outside are not read; folder listings skip and count them (`skipped_outside_root`).
210
269
 
211
270
  ### Agent Skill
212
271
 
@@ -247,8 +306,8 @@ for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["
247
306
 
248
307
  ## 遇到读不出的文件 / Reporting a problem
249
308
 
250
- 请不要把真实发票发到网上。用这个命令导出文件结构,文字会全部打码,只保留结构和位置,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里:
251
- Please do not post real invoices. Export the structure with all text masked and attach it to a [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose):
309
+ 请不要把真实发票发到网上。用这个命令导出文件结构,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里。文字、文件名和较长的号码会打码(汉字变成"字",数字变成"0",字母变成 x),只保留结构、坐标和 OFD 格式自己的名字(如 `Doc_0`、`Content.xml`)。打码是尽力而为,发出去之前请自己再看一遍:
310
+ Please do not post real invoices. Export the structure and attach it to a [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose). Text, file names and long numbers are masked; the structure, coordinates and the OFD format's own names (`Doc_0`, `Content.xml`) are kept. Masking is a best effort, so look through the file before posting it:
252
311
 
253
312
  ```bash
254
313
  ofdkit describe 文件.ofd -o 结构.json
@@ -6,11 +6,17 @@
6
6
 
7
7
  A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese fixed-layout format used for e-invoices and official documents): extract text and invoice fields, and use them from AI tools.
8
8
 
9
- > 状态:0.3 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
10
- > Status: 0.3, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
9
+ > 状态:0.5 版,更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
10
+ > Status: 0.5. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
11
11
 
12
12
  ## 能做什么 / What it does
13
13
 
14
+ - Windows x64 用户可下载便携包,解压后双击运行。桌面窗口可搜索文字、跳页、选页保存,并筛选批量结果。
15
+ Windows x64 users can extract and launch the portable app. Search text, jump to pages, save selected pages, and filter batch results.
16
+ - 桌面的跨文件搜索可以查一个 OFD 文件、文件夹或 ZIP。结果显示原页码、行号和原文片段。
17
+ Desktop search finds text across an OFD file, folder or ZIP and shows page and line references.
18
+ - 用桌面窗口选 OFD 文件、逐页读文字,或把发票文件夹和 ZIP 导出到 Excel。文件在本机处理。
19
+ Open OFD text page by page or export invoices from a folder or ZIP in a local desktop window.
14
20
  - 看发票:一条命令显示发票号码、日期、购买方、销售方、金额和明细。
15
21
  Show an invoice: number, date, buyer, seller, amounts and line items, with one command.
16
22
  - 把一个文件夹里的发票汇总到 Excel,也能直接读税务平台批量下载的 .zip 压缩包。发票号码保持原样(不会变成 2.4E+19),金额可以直接求和,重复的发票会标出来。
@@ -19,6 +25,12 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
19
25
  For reimbursement: check that invoices are made out to the right buyer, and rename invoice files after their contents, with a preview and an undo.
20
26
  - 按阅读顺序提取文字,包括模板和复合对象里的文字。
21
27
  Text in reading order, including text in templates and composite objects.
28
+ - 跨文件搜索关键词,导出逐页 JSON 和文字坐标,或把一批 OFD 保存成一个文字 ZIP。
29
+ Search across files, export page data and positioned text runs, or bundle a batch of text exports in a ZIP.
30
+ - 按日期、购销方和问题筛选发票,检查金额与明细的一致性,导出单独的复核表。
31
+ Filter invoice review by date, party and issue, check extracted amounts, and export a review workbook.
32
+ - 对比两次保存的复核结果,查看新发现、仍存在和已处理的问题。
33
+ Compare two saved review reports to track new, persistent and resolved findings.
22
34
  - 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。
23
35
  For programs and AI: invoice fields as JSON, an MCP server, an Agent Skill and a MarkItDown plugin.
24
36
  - 只用 Python 标准库,没有任何第三方依赖;能读很多不规范的文件(路径写法不对、编码不对、XML 前缀错误等)。
@@ -26,15 +38,30 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
26
38
 
27
39
  ## 快速上手 / Quick start
28
40
 
29
- 1. 安装 [Python](https://www.python.org/downloads/) 3.10 或更新版本。Windows 上安装时请勾选 "Add python.exe to PATH"。
41
+ Windows x64 可在 [GitHub 发布页](https://github.com/Edgar-311/ofdkit/releases/latest) 下载 `ofdkit-*-windows-x64.zip`。完整解压后双击 `ofdkit.exe`,然后点“试用样例”开始。命令行、Python 库和 AI 接入可按下面的方法安装。
42
+ On Windows x64, download the portable ZIP, extract it, and open `ofdkit.exe`. Use the Python package for the CLI, library and AI integrations.
43
+
44
+ 第一次用命令行?先看 [Windows 新手指南](https://github.com/Edgar-311/ofdkit/blob/main/docs/quickstart.zh-CN.md):包含普通测试样例、带空格的路径写法、Excel 输出位置和常见报错处理。
45
+ New to the command line? The [Windows beginner guide (Chinese)](https://github.com/Edgar-311/ofdkit/blob/main/docs/quickstart.zh-CN.md) includes a synthetic sample and troubleshooting.
46
+
47
+ 1. 安装 [Python](https://www.python.org/downloads/) 3.10 或更新版本,安装后重新打开终端。
30
48
  Install Python 3.10 or newer.
31
49
  2. 打开命令行(Windows 在开始菜单搜索"终端"或"cmd",Mac 打开"终端"),安装 ofdkit:
32
50
  Open a terminal and install ofdkit:
33
51
 
34
52
  ```bash
35
- pip install ofdkit
53
+ python -m pip install --upgrade ofdkit
54
+ python -m ofdkit --version
36
55
  ```
37
56
 
57
+ 如果 Windows 上 `python` 不可用而 `py` 可用,把上述 `python` 换成 `py`;macOS / Linux 通常使用 `python3`。下文的 `ofdkit` 命令也可以写成 `python -m ofdkit`,使用与安装时相同的 Python。
58
+ Use the same Python to install and run. `python -m ofdkit` also works when the `ofdkit` command is not on PATH.
59
+
60
+ 想用鼠标操作?运行 `python -m ofdkit gui`。在“查看 OFD”选文件,或在“批量复核”选文件夹或 ZIP。桌面窗口需要 Python 的 Tk 支持,可用 `python -m tkinter` 检查。[桌面使用指南](https://github.com/Edgar-311/ofdkit/blob/main/docs/desktop.zh-CN.md)
61
+ Run `python -m ofdkit gui` to open the desktop window. Use `python -m tkinter` to check Tk support.
62
+ 用 `python -m ofdkit demo --gui` 打开内置的三页样例,或用 `python -m ofdkit doctor --check-window` 检查安装和图形窗口。
63
+ Use `python -m ofdkit demo --gui` for an offline demo or `python -m ofdkit doctor --check-window` to test the installation and GUI.
64
+
38
65
  3. 看一张发票(把文件拖进命令行窗口就能填上路径):
39
66
  Show an invoice (drag the file into the terminal window to type its path):
40
67
 
@@ -68,8 +95,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
68
95
  ofdkit batch 发票文件夹 -o 发票汇总.xlsx
69
96
  ```
70
97
 
71
- Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红并写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行。
72
- The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red with the reason) and 明细 (one row per line item). Totals use SUBTOTAL, so they follow filters.
98
+ Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红,有其他提醒的发票(抬头不对、金额缺少或不是数字)标橙,都在"提醒"一栏写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行;不是数字的金额保留原样、不算进合计,合计下面会注明有几张。
99
+ The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red, other reminders such as another buyer or an amount that is missing or not a number in orange, each explained) and 明细 (one row per line item). Totals use SUBTOTAL, so they follow filters.
73
100
 
74
101
  5. 检查发票抬头:加上 `--buyer`,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次:
75
102
  Check who the invoices are made out to: with `--buyer`, invoices for another buyer name or tax ID are flagged (orange in Excel). Repeat it to check both:
@@ -78,8 +105,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
78
105
  ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
79
106
  ```
80
107
 
81
- 6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML 会一起改;改名记录可以用 `--undo` 改回去:
82
- Rename invoice files after their contents. Without `--apply` it only previews; PDF and XML copies with the same name are renamed too; `--undo` restores the old names from the log:
108
+ 6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML 会一起改(其中一个改不了,这张发票的文件都保持原名);改名前会先写好改名记录,写不了就一个文件也不改;用 `--undo` 可以按记录改回去,运行几次都没关系:
109
+ Rename invoice files after their contents. Without `--apply` it only previews; PDF and XML copies with the same name are renamed too (if one cannot be, that invoice's files all keep their names); the log is written before anything is renamed, and nothing is renamed if it cannot be; `--undo` restores the old names from the log and is safe to run again:
83
110
 
84
111
  ```bash
85
112
  ofdkit rename 发票文件夹 # 预览 / preview
@@ -96,18 +123,44 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
96
123
  ofdkit 文件.ofd # 看发票,不是发票就显示文字 / show an invoice, or the text
97
124
  ofdkit 文件夹或压缩包.zip # 发票列表和合计 / list invoices with totals
98
125
  ofdkit batch 文件夹 -o 发票汇总.xlsx # 导出 Excel / export to Excel
126
+ ofdkit batch 文件夹 --exclude-duplicates -o 发票汇总.xlsx # 合计时排除一致的重复记录
99
127
  ofdkit batch 文件夹 -o 发票汇总.csv # 导出 CSV(给程序用)/ export CSV for programs
100
128
  ofdkit 文件夹 --buyer 公司名或税号 # 检查发票抬头 / check the buyer
101
129
  ofdkit rename 文件夹 # 按内容改名(先预览)/ rename after contents (preview first)
102
130
  ofdkit text 文件.ofd # 提取文字 / print text
131
+ ofdkit text 文件.ofd --pages 1,3-5 --markdown -o 摘录.md # 提取指定页
103
132
  ofdkit invoice 发票.ofd # 发票字段(JSON)/ invoice fields as JSON
104
133
  ofdkit info 文件.ofd # 页数、作者等信息 / pages and metadata
105
134
  ofdkit describe 文件.ofd -o 结构.json # 打码的结构,用于报告问题 / masked structure for bug reports
135
+ ofdkit gui # 打开桌面窗口 / open the desktop window
136
+ ofdkit search "付款条件" 文件夹 -r # 跨文件查文字,显示页码和上下文
137
+ ofdkit pages 文件.ofd --pages 2-4 --runs -o 页面.json # 导出页号、文字、尺寸和坐标
138
+ ofdkit export-text 文件夹 -r --markdown -o 文本.zip # 批量导出文字和文件索引
139
+ ofdkit review 文件夹 --only-issues -o 复核.xlsx # 把需要人工核对的记录单独列出
140
+ ofdkit review-diff 上次.json 本次.json # 比较两次复核结果
141
+ ofdkit demo # 试读内置样例 / read the included example
142
+ ofdkit doctor # 检查安装和样例 / check this installation
143
+ ofdkit doctor --file 文件.ofd -o 诊断.json # 输出不含文件路径和正文的读取诊断
106
144
  ```
107
145
 
146
+ 搜索和逐页导出的参数见[文档工具指南](https://github.com/Edgar-311/ofdkit/blob/main/docs/document-tools.zh-CN.md)。
147
+
148
+ 发票复核的筛选、问题代码和表格说明见[发票复核指南](https://github.com/Edgar-311/ofdkit/blob/main/docs/invoice-review.zh-CN.md)。
149
+
150
+ `export-text` 接受多个文件、文件夹或 ZIP。输出使用编号文件名,在 `manifest.json` 中对应原名称、ZIP 成员和读取提示。默认保留已经读出的文档,`--strict` 在读取不完整时保留旧报表。
151
+
108
152
  `show`、`batch` 和 `rename` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
109
153
  Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
110
154
 
155
+ `--pages 1,3-5` 会按原文顺序提取第 1、3、4、5 页。合用 `--markdown` 时,每节保留原页码,只输出选定页的文字。
156
+ With `--pages`, text or Markdown contains only the selected pages, in the original order.
157
+
158
+ `--exclude-duplicates` 只影响金额合计。带有相同发票标识且关键信息和金额一致的记录只计一次。信息冲突或金额不全的组会全部保留在合计中,请人工核对。使用该选项时,Excel 显示整表合计,筛选时合计数不变。Excel 和 CSV 都保留所有行,CSV 的合计显示在命令行提示中。
159
+ With `--exclude-duplicates`, matching copies count once in totals. Conflicting or incomplete groups stay in totals for review. Excel shows a fixed whole-report total. Excel and CSV keep all rows.
160
+
161
+ 导出结果请使用新文件名,保留原 OFD 和 ZIP。程序会检查输出路径,只有新文件保存完整才会替换同名旧报表。
162
+ Exports protect the source and replace an existing report only after the new file has been written in full.
163
+
111
164
  `ofdkit invoice` 的输出示例(数据是虚构的)/ Example output (fictional data):
112
165
 
113
166
  ```json
@@ -135,8 +188,8 @@ Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is
135
188
  }
136
189
  ```
137
190
 
138
- 金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",`warnings` 里会提示。
139
- Amounts are decimal strings, so no precision is lost. `warnings` notes totals that do not add up.
191
+ 金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",或者某个金额不是数字(比如"无法识别",这时保留原样),`warnings` 里会提示。汇总时只加真正的数字:0 就是 0,缺少的和不是数字的不算进合计,并单独计数(`not_summed`)。
192
+ Amounts are decimal strings, so no precision is lost. `warnings` notes totals that do not add up and amounts that are not numbers (kept as found). Summaries add only real numbers: 0 counts as 0, while missing amounts and amounts that are not numbers are left out and counted in `not_summed`.
140
193
 
141
194
  ## 在 AI 工具里使用 / Use from AI tools
142
195
 
@@ -145,12 +198,18 @@ Amounts are decimal strings, so no precision is lost. `warnings` notes totals th
145
198
  让 Claude、Codex、Cursor 等 AI 工具直接读取 OFD 文件。需要先安装 [uv](https://docs.astral.sh/uv/)。所有工具都是只读的。
146
199
  Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires [uv](https://docs.astral.sh/uv/). All tools are read-only.
147
200
 
201
+ 已在[官方 MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.Edgar-311/ofdkit) 上架,名字是 `io.github.Edgar-311/ofdkit`;支持这个目录的工具可以直接搜索安装。
202
+ Listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.Edgar-311/ofdkit) as `io.github.Edgar-311/ofdkit`; tools that read the registry can install it from there.
203
+
148
204
  | 工具 / Tool | 作用 / What it does |
149
205
  | --- | --- |
150
206
  | `read_ofd_text` | 按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range |
207
+ | `read_ofd_pages` | 结构化逐页文字和尺寸 / structured page text and dimensions |
208
+ | `search_ofd_text` | 搜索本机 OFD 文档,返回页码、行号和片段 / local text search with page and line references |
151
209
  | `read_ofd_invoice` | 发票字段 / invoice fields |
152
210
  | `ofd_info` | 页数、尺寸、元数据 / pages, sizes, metadata |
153
- | `list_ofd_invoices` | 汇总一个文件夹里的发票,可以检查抬头 / summarise a folder of invoices, optionally checking the buyer |
211
+ | `list_ofd_invoices` | 汇总文件夹里的发票,可查抬头或去重合计 / folder totals with buyer and duplicate options |
212
+ | `review_ofd_invoices` | 检查金额、明细及提取问题 / check internally inconsistent fields or extraction issues |
154
213
 
155
214
  Claude Code:
156
215
 
@@ -179,8 +238,8 @@ command = "uvx"
179
238
  args = ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
180
239
  ```
181
240
 
182
- 加上 `--root 文件夹` 可以只允许读取这个文件夹里的文件。
183
- Add `--root FOLDER` to allow only files inside that folder.
241
+ 加上 `--root 文件夹` 可以只允许读取这个文件夹里的文件。判断的是文件的真实位置:文件夹里指向外面的快捷方式式链接(符号链接、Windows 的目录联接)不会被读取,汇总文件夹时会跳过并计数(`skipped_outside_root`)。
242
+ Add `--root FOLDER` to allow only files inside that folder. The check uses each file's real location, so symbolic links and Windows directory junctions that lead outside are not read; folder listings skip and count them (`skipped_outside_root`).
184
243
 
185
244
  ### Agent Skill
186
245
 
@@ -221,8 +280,8 @@ for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["
221
280
 
222
281
  ## 遇到读不出的文件 / Reporting a problem
223
282
 
224
- 请不要把真实发票发到网上。用这个命令导出文件结构,文字会全部打码,只保留结构和位置,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里:
225
- Please do not post real invoices. Export the structure with all text masked and attach it to a [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose):
283
+ 请不要把真实发票发到网上。用这个命令导出文件结构,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里。文字、文件名和较长的号码会打码(汉字变成"字",数字变成"0",字母变成 x),只保留结构、坐标和 OFD 格式自己的名字(如 `Doc_0`、`Content.xml`)。打码是尽力而为,发出去之前请自己再看一遍:
284
+ Please do not post real invoices. Export the structure and attach it to a [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose). Text, file names and long numbers are masked; the structure, coordinates and the OFD format's own names (`Doc_0`, `Content.xml`) are kept. Masking is a best effort, so look through the file before posting it:
226
285
 
227
286
  ```bash
228
287
  ofdkit describe 文件.ofd -o 结构.json
@@ -4,8 +4,8 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "ofdkit"
7
- version = "0.3.1"
8
- description = "Read OFD documents (GB/T 33190) and Chinese e-invoices: text, invoice fields, and AI tool integrations."
7
+ version = "0.5.0"
8
+ description = "Read and search OFD documents (GB/T 33190), extract Chinese e-invoices, and review or export results."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
11
11
  license-files = ["LICENSE"]
@@ -0,0 +1,82 @@
1
+ """Keep file access inside one folder, for the MCP server's ``--root`` option.
2
+
3
+ A path inside the folder can still lead outside it: a symbolic link, a Windows
4
+ directory junction, or a folder replaced by a link after it was listed. So every file is
5
+ checked by its final, resolved path right before it is opened, and again through the
6
+ opened handle; folders that lead outside are not searched at all.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from collections.abc import Iterator
13
+ from pathlib import Path
14
+ from typing import BinaryIO
15
+
16
+
17
+ class OutsideRootError(PermissionError):
18
+ """A path leads outside the allowed folder."""
19
+
20
+
21
+ class PathGuard:
22
+ """Allows reading files only when their real location is inside ``root``."""
23
+
24
+ def __init__(self, root: str | Path) -> None:
25
+ self.root = Path(os.path.realpath(Path(root).expanduser()))
26
+ #: Paths that were skipped because they lead outside the folder.
27
+ self.refused: list[str] = []
28
+
29
+ def inside(self, path: str | Path) -> bool:
30
+ """True when the real location of ``path`` (all links followed) is inside the folder."""
31
+ real = Path(os.path.realpath(path))
32
+ return real == self.root or self.root in real.parents
33
+
34
+ def check(self, path: str | Path) -> Path:
35
+ """The real location of ``path``, or OutsideRootError."""
36
+ real = Path(os.path.realpath(Path(path).expanduser()))
37
+ if not (real == self.root or self.root in real.parents):
38
+ raise OutsideRootError(f"{path} is outside the allowed folder {self.root}")
39
+ return real
40
+
41
+ def open(self, path: str | Path) -> BinaryIO:
42
+ """Open a file for reading after checking where it really is.
43
+
44
+ The resolved path is opened, not the one given, and the opened handle is compared
45
+ with what the path points at afterwards, so a link swapped in between is caught.
46
+ """
47
+ real = self.check(path)
48
+ stream = open(real, "rb") # noqa: SIM115 - the caller closes it
49
+ try:
50
+ if not os.path.samestat(os.fstat(stream.fileno()), os.stat(real)) or not self.inside(real):
51
+ raise OutsideRootError(f"{path} changed while it was opened")
52
+ except BaseException:
53
+ stream.close()
54
+ raise
55
+ return stream
56
+
57
+ def walk(self, folder: Path, recursive: bool) -> Iterator[Path]:
58
+ """Files in ``folder`` (and its subfolders) whose real location is inside the root.
59
+
60
+ Links that lead outside are skipped and noted in :attr:`refused`; folders are
61
+ never entered twice, so link loops end.
62
+ """
63
+ seen: set[str] = set()
64
+ pending = [folder]
65
+ while pending:
66
+ current = pending.pop()
67
+ real = os.path.realpath(current)
68
+ if real in seen:
69
+ continue
70
+ seen.add(real)
71
+ try:
72
+ entries = sorted(current.iterdir())
73
+ except OSError:
74
+ continue
75
+ for entry in entries:
76
+ if not self.inside(entry):
77
+ self.refused.append(str(entry))
78
+ elif entry.is_dir():
79
+ if recursive:
80
+ pending.append(entry)
81
+ elif entry.is_file():
82
+ yield entry
@@ -0,0 +1,108 @@
1
+ """Read OFD files directly or from ZIP members, without extracting any files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import zipfile
7
+ import zlib
8
+ from collections.abc import Iterator
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import BinaryIO
13
+
14
+ from ._guard import PathGuard
15
+ from .document import OFDDocument
16
+ from .package import MAX_ENTRIES, _entry_name, _normalize
17
+
18
+ EMPTY_ARCHIVE = "no .ofd files in this ZIP archive"
19
+ MAX_ARCHIVE_MEMBER_SIZE = 128 * 1024 * 1024
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class DocumentInput:
24
+ file: str
25
+ source: Path | bytes | None = None
26
+ error: str | None = None
27
+ member: str | None = None
28
+
29
+
30
+ def _open_path(path: Path, guard: PathGuard | None) -> BinaryIO:
31
+ return guard.open(path) if guard is not None else path.open("rb")
32
+
33
+
34
+ @contextmanager
35
+ def open_document_source(source: Path | bytes, guard: PathGuard | None = None) -> Iterator[OFDDocument]:
36
+ if isinstance(source, Path):
37
+ with _open_path(source, guard) as stream, OFDDocument(stream) as document:
38
+ yield document
39
+ else:
40
+ with OFDDocument(source) as document:
41
+ yield document
42
+
43
+
44
+ def _members(archive: zipfile.ZipFile) -> list[tuple[str, zipfile.ZipInfo]] | None:
45
+ infos = archive.infolist()
46
+ if len(infos) > MAX_ENTRIES:
47
+ return None
48
+ names = [(_normalize(_entry_name(info)), info) for info in infos if not info.is_dir()]
49
+ if any(name.casefold() == "ofd.xml" for name, _ in names):
50
+ return None # This is itself an OFD file with a .zip suffix.
51
+ return sorted(((name, info) for name, info in names if name.lower().endswith(".ofd")), key=lambda pair: pair[0])
52
+
53
+
54
+ def has_ofd_members(path: Path, guard: PathGuard | None = None) -> bool:
55
+ """Whether a ZIP archive contains at least one OFD document."""
56
+ try:
57
+ with _open_path(path, guard) as stream, zipfile.ZipFile(stream) as archive:
58
+ return bool(_members(archive))
59
+ except (zipfile.BadZipFile, OSError, ValueError, EOFError):
60
+ return False
61
+
62
+
63
+ def iter_document_inputs(
64
+ path: Path, limit: int | None = None, guard: PathGuard | None = None,
65
+ *, member_size_limit: int = MAX_ARCHIVE_MEMBER_SIZE,
66
+ ) -> Iterator[DocumentInput]:
67
+ """Yield a path or bounded ZIP member bytes, with an item for each read error.
68
+
69
+ Consume each input before advancing to avoid retaining multiple member copies.
70
+ Close the iterator if stopping early so that the archive handle is closed.
71
+ """
72
+ if limit is not None and limit <= 0:
73
+ return
74
+ if path.suffix.lower() == ".zip":
75
+ is_archive = False
76
+ try:
77
+ with _open_path(path, guard) as stream, zipfile.ZipFile(stream) as archive:
78
+ members = _members(archive)
79
+ if members is not None:
80
+ is_archive = True
81
+ if not members:
82
+ yield DocumentInput(str(path), error=EMPTY_ARCHIVE)
83
+ for name, info in members[:limit]:
84
+ # The normalized member name is a label only, never a local path.
85
+ label = f"{path}{os.sep}{name.replace('/', os.sep)}"
86
+ yield _read_member(archive, info, name, label, member_size_limit)
87
+ except (zipfile.BadZipFile, OSError, ValueError, EOFError) as exc:
88
+ if is_archive:
89
+ yield DocumentInput(str(path), error=f"cannot read the archive: {exc}")
90
+ if is_archive:
91
+ return
92
+ yield DocumentInput(str(path), source=path)
93
+
94
+
95
+ def _read_member(
96
+ archive: zipfile.ZipFile, info: zipfile.ZipInfo, name: str, label: str, size_limit: int
97
+ ) -> DocumentInput:
98
+ if info.file_size > size_limit:
99
+ return DocumentInput(label, error=f"too large to read from the archive ({info.file_size} bytes)", member=name)
100
+ try:
101
+ with archive.open(info) as stream:
102
+ data = stream.read(size_limit + 1)
103
+ except (zipfile.BadZipFile, zlib.error, RuntimeError, NotImplementedError, EOFError) as exc:
104
+ # RuntimeError includes password-protected entries.
105
+ return DocumentInput(label, error=f"cannot read from the archive: {exc}", member=name)
106
+ if len(data) > size_limit:
107
+ return DocumentInput(label, error=f"too large to read from the archive (over {size_limit} bytes)", member=name)
108
+ return DocumentInput(label, source=data, member=name)