ofdkit 0.4.0__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.
- {ofdkit-0.4.0 → ofdkit-0.5.0}/PKG-INFO +63 -7
- {ofdkit-0.4.0 → ofdkit-0.5.0}/README.md +61 -5
- {ofdkit-0.4.0 → ofdkit-0.5.0}/pyproject.toml +2 -2
- ofdkit-0.5.0/src/ofdkit/_sources.py +108 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/batch.py +89 -81
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/cli.py +75 -14
- ofdkit-0.5.0/src/ofdkit/desktop.py +716 -0
- ofdkit-0.5.0/src/ofdkit/desktop_data.py +255 -0
- ofdkit-0.5.0/src/ofdkit/desktop_search.py +198 -0
- ofdkit-0.5.0/src/ofdkit/document_tools.py +279 -0
- ofdkit-0.5.0/src/ofdkit/export_output.py +54 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/mcp_server.py +96 -5
- ofdkit-0.5.0/src/ofdkit/onboarding.py +198 -0
- ofdkit-0.5.0/src/ofdkit/page_range.py +71 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/report.py +5 -1
- ofdkit-0.5.0/src/ofdkit/review.py +494 -0
- ofdkit-0.5.0/src/ofdkit/review_diff.py +451 -0
- ofdkit-0.5.0/src/ofdkit/samples/README.txt +5 -0
- ofdkit-0.5.0/src/ofdkit/samples/multi-page-sizes.ofd +0 -0
- ofdkit-0.5.0/src/ofdkit/text_bundle.py +124 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/xlsx.py +35 -13
- {ofdkit-0.4.0 → ofdkit-0.5.0}/LICENSE +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/__init__.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/__main__.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/_guard.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/_xml.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/describe.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/document.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/errors.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/invoice.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/layout.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/markdown.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/markitdown_plugin.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/package.py +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/py.typed +0 -0
- {ofdkit-0.4.0 → ofdkit-0.5.0}/src/ofdkit/rename.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ofdkit
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: Read OFD documents (GB/T 33190)
|
|
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.
|
|
36
|
-
> Status: 0.
|
|
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
|
-
|
|
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
|
|
|
@@ -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
|
|
@@ -177,9 +230,12 @@ Listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v
|
|
|
177
230
|
| 工具 / Tool | 作用 / What it does |
|
|
178
231
|
| --- | --- |
|
|
179
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 |
|
|
180
235
|
| `read_ofd_invoice` | 发票字段 / invoice fields |
|
|
181
236
|
| `ofd_info` | 页数、尺寸、元数据 / pages, sizes, metadata |
|
|
182
|
-
| `list_ofd_invoices` |
|
|
237
|
+
| `list_ofd_invoices` | 汇总文件夹里的发票,可查抬头或去重合计 / folder totals with buyer and duplicate options |
|
|
238
|
+
| `review_ofd_invoices` | 检查金额、明细及提取问题 / check internally inconsistent fields or extraction issues |
|
|
183
239
|
|
|
184
240
|
Claude Code:
|
|
185
241
|
|
|
@@ -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.
|
|
10
|
-
> Status: 0.
|
|
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
|
-
|
|
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
|
|
|
@@ -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
|
|
@@ -151,9 +204,12 @@ Listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v
|
|
|
151
204
|
| 工具 / Tool | 作用 / What it does |
|
|
152
205
|
| --- | --- |
|
|
153
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 |
|
|
154
209
|
| `read_ofd_invoice` | 发票字段 / invoice fields |
|
|
155
210
|
| `ofd_info` | 页数、尺寸、元数据 / pages, sizes, metadata |
|
|
156
|
-
| `list_ofd_invoices` |
|
|
211
|
+
| `list_ofd_invoices` | 汇总文件夹里的发票,可查抬头或去重合计 / folder totals with buyer and duplicate options |
|
|
212
|
+
| `review_ofd_invoices` | 检查金额、明细及提取问题 / check internally inconsistent fields or extraction issues |
|
|
157
213
|
|
|
158
214
|
Claude Code:
|
|
159
215
|
|
|
@@ -4,8 +4,8 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "ofdkit"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "Read OFD documents (GB/T 33190)
|
|
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,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)
|
|
@@ -8,20 +8,17 @@ after the archive and its path inside it (``下载.zip/发票1.ofd``).
|
|
|
8
8
|
from __future__ import annotations
|
|
9
9
|
|
|
10
10
|
import re
|
|
11
|
-
import zipfile
|
|
12
|
-
import zlib
|
|
13
11
|
from collections import Counter
|
|
14
12
|
from collections.abc import Iterable, Sequence
|
|
15
13
|
from dataclasses import dataclass, field
|
|
16
14
|
from decimal import Decimal
|
|
17
15
|
from pathlib import Path
|
|
18
|
-
from typing import Any,
|
|
16
|
+
from typing import Any, Literal
|
|
19
17
|
|
|
20
18
|
from ._guard import PathGuard
|
|
21
|
-
from .
|
|
19
|
+
from ._sources import EMPTY_ARCHIVE, MAX_ARCHIVE_MEMBER_SIZE, has_ofd_members, iter_document_inputs, open_document_source
|
|
22
20
|
from .errors import OFDError
|
|
23
21
|
from .invoice import AMOUNT_FIELDS, NOT_A_NUMBER, Invoice, parse_amount
|
|
24
|
-
from .package import MAX_ENTRIES, _entry_name, _normalize
|
|
25
22
|
|
|
26
23
|
COLUMNS = [
|
|
27
24
|
"file",
|
|
@@ -45,10 +42,6 @@ COLUMNS = [
|
|
|
45
42
|
NO_INVOICE = "no invoice data"
|
|
46
43
|
DUPLICATE = "duplicate invoice number"
|
|
47
44
|
BUYER_MISMATCH = "buyer is not"
|
|
48
|
-
EMPTY_ARCHIVE = "no .ofd files in this ZIP archive"
|
|
49
|
-
|
|
50
|
-
#: Largest OFD file, uncompressed, that is read from inside a ZIP archive.
|
|
51
|
-
MAX_ARCHIVE_MEMBER_SIZE = 128 * 1024 * 1024
|
|
52
45
|
|
|
53
46
|
|
|
54
47
|
@dataclass
|
|
@@ -111,7 +104,7 @@ def find_ofd_files(
|
|
|
111
104
|
candidates = [p for p in (path.rglob("*") if recursive else path.glob("*")) if p.is_file()]
|
|
112
105
|
for candidate in sorted(candidates):
|
|
113
106
|
suffix = candidate.suffix.lower()
|
|
114
|
-
if suffix == ".ofd" or (suffix == ".zip" and
|
|
107
|
+
if suffix == ".ofd" or (suffix == ".zip" and has_ofd_members(candidate, guard)):
|
|
115
108
|
found.append(candidate)
|
|
116
109
|
elif path.exists():
|
|
117
110
|
found.append(path)
|
|
@@ -273,25 +266,79 @@ def problems(result: InvoiceFile) -> list[str]:
|
|
|
273
266
|
return found
|
|
274
267
|
|
|
275
268
|
|
|
276
|
-
def summary(
|
|
269
|
+
def summary(
|
|
270
|
+
results: Sequence[InvoiceFile | dict[str, Any]], *, exclude_duplicates: bool = False
|
|
271
|
+
) -> dict[str, Any]:
|
|
277
272
|
"""Counts and sums over the results (or rows from :func:`invoice_rows`).
|
|
278
273
|
|
|
279
|
-
``total_amount_sum`` adds every invoice
|
|
280
|
-
counts
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
274
|
+
By default, ``total_amount_sum`` adds every invoice and the alternative
|
|
275
|
+
``total_amount_sum_without_duplicates`` counts the first row per invoice identity.
|
|
276
|
+
With ``exclude_duplicates``, all three sums and ``not_summed`` use the reviewed
|
|
277
|
+
rows: repeated rows are left out only when the whole group agrees on the
|
|
278
|
+
compared fields and has three numeric amounts. Both total-amount keys then
|
|
279
|
+
represent that same selection. ``duplicates_excluded`` counts left-out rows
|
|
280
|
+
and ``duplicate_review_groups`` counts groups left in for manual review.
|
|
281
|
+
|
|
282
|
+
``not_summed`` counts missing and non-numeric amounts separately for each sum.
|
|
283
|
+
The results themselves and all file counts are unchanged by this option.
|
|
284
284
|
"""
|
|
285
|
+
return _summarize(results, exclude_duplicates=exclude_duplicates)[0]
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
_DuplicateAction = Literal["included", "excluded", "review"]
|
|
289
|
+
# A difference in any of these fields is a reason to keep the full group. The
|
|
290
|
+
# same comparison works for InvoiceFile objects and exported invoice_rows.
|
|
291
|
+
_DUPLICATE_FIELDS = ("invoice_type", "issue_date", "items", "item_names")
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _duplicate_signature(row: dict[str, Any]) -> tuple[Any, ...] | None:
|
|
295
|
+
amounts = tuple(parse_amount(str(row[column])) for column in AMOUNT_FIELDS)
|
|
296
|
+
if None in amounts:
|
|
297
|
+
return None
|
|
298
|
+
return (
|
|
299
|
+
*amounts,
|
|
300
|
+
*(_normal_name(str(row.get(f"{party}_name") or "")) for party in ("buyer", "seller")),
|
|
301
|
+
*(_normal_tax_id(str(row.get(f"{party}_tax_id") or "")) for party in ("buyer", "seller")),
|
|
302
|
+
*(row.get(column) for column in _DUPLICATE_FIELDS),
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _summarize(
|
|
307
|
+
results: Sequence[InvoiceFile | dict[str, Any]], *, exclude_duplicates: bool
|
|
308
|
+
) -> tuple[dict[str, Any], dict[int, _DuplicateAction]]:
|
|
309
|
+
"""Return the summary and the decisions for individual worksheet rows."""
|
|
285
310
|
rows = [result if isinstance(result, dict) else invoice_row(result) for result in results]
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
for
|
|
290
|
-
|
|
291
|
-
if row["invoice_number"]
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
311
|
+
invoice_indexes = [index for index, row in enumerate(rows) if not row["error"]]
|
|
312
|
+
invoices = [rows[index] for index in invoice_indexes]
|
|
313
|
+
groups: dict[tuple[str, str], list[int]] = {}
|
|
314
|
+
for index in invoice_indexes:
|
|
315
|
+
row = rows[index]
|
|
316
|
+
if row["invoice_number"]:
|
|
317
|
+
key = (row["invoice_code"], row["invoice_number"])
|
|
318
|
+
groups.setdefault(key, []).append(index)
|
|
319
|
+
repeated = sum(len(group) - 1 for group in groups.values())
|
|
320
|
+
actions: dict[int, _DuplicateAction] = {}
|
|
321
|
+
review_count = 0
|
|
322
|
+
if exclude_duplicates:
|
|
323
|
+
for group in groups.values():
|
|
324
|
+
if len(group) < 2:
|
|
325
|
+
continue
|
|
326
|
+
first, *others = group
|
|
327
|
+
signature = _duplicate_signature(rows[first])
|
|
328
|
+
if signature is None or any(_duplicate_signature(rows[index]) != signature for index in others):
|
|
329
|
+
actions.update(dict.fromkeys(group, "review"))
|
|
330
|
+
review_count += 1
|
|
331
|
+
else:
|
|
332
|
+
actions[first] = "included"
|
|
333
|
+
actions.update(dict.fromkeys(others, "excluded"))
|
|
334
|
+
excluded = {index for index, action in actions.items() if action == "excluded"}
|
|
335
|
+
selected = [rows[index] for index in invoice_indexes if index not in excluded]
|
|
336
|
+
unique = selected
|
|
337
|
+
else:
|
|
338
|
+
excluded = set()
|
|
339
|
+
selected = invoices
|
|
340
|
+
after_first = {index for group in groups.values() for index in group[1:]}
|
|
341
|
+
unique = [rows[index] for index in invoice_indexes if index not in after_first]
|
|
295
342
|
|
|
296
343
|
def total(column: str, selected: list[dict[str, Any]]) -> str:
|
|
297
344
|
values = (parse_amount(str(row[column])) for row in selected if row[column] != "")
|
|
@@ -299,78 +346,44 @@ def summary(results: Sequence[InvoiceFile | dict[str, Any]]) -> dict[str, Any]:
|
|
|
299
346
|
|
|
300
347
|
not_summed = {
|
|
301
348
|
column: {
|
|
302
|
-
"missing": sum(1 for row in
|
|
303
|
-
"invalid": sum(1 for row in
|
|
349
|
+
"missing": sum(1 for row in selected if row[column] == ""),
|
|
350
|
+
"invalid": sum(1 for row in selected if row[column] != "" and parse_amount(str(row[column])) is None),
|
|
304
351
|
}
|
|
305
352
|
for column in AMOUNT_FIELDS
|
|
306
353
|
}
|
|
307
354
|
|
|
308
|
-
|
|
355
|
+
totals = {
|
|
309
356
|
"files": len(rows),
|
|
310
357
|
"invoices": len(invoices),
|
|
311
358
|
"without_invoice_data": sum(1 for row in rows if row["error"] == NO_INVOICE),
|
|
312
359
|
"errors": sum(1 for row in rows if row["error"] and row["error"] != NO_INVOICE),
|
|
313
|
-
"duplicates":
|
|
360
|
+
"duplicates": repeated,
|
|
314
361
|
"buyer_mismatches": sum(1 for row in invoices if BUYER_MISMATCH in row["warnings"]),
|
|
315
|
-
"amount_without_tax_sum": total("amount_without_tax",
|
|
316
|
-
"tax_amount_sum": total("tax_amount",
|
|
317
|
-
"total_amount_sum": total("total_amount",
|
|
362
|
+
"amount_without_tax_sum": total("amount_without_tax", selected),
|
|
363
|
+
"tax_amount_sum": total("tax_amount", selected),
|
|
364
|
+
"total_amount_sum": total("total_amount", selected),
|
|
318
365
|
"total_amount_sum_without_duplicates": total("total_amount", unique),
|
|
319
366
|
"not_summed": not_summed,
|
|
320
367
|
}
|
|
368
|
+
if exclude_duplicates:
|
|
369
|
+
totals.update(duplicates_excluded=len(excluded), duplicate_review_groups=review_count)
|
|
370
|
+
return totals, actions
|
|
321
371
|
|
|
322
372
|
|
|
323
373
|
def _read_path(path: Path, limit: int | None = None, guard: PathGuard | None = None) -> list[InvoiceFile]:
|
|
324
|
-
if path.suffix.lower() != ".zip":
|
|
325
|
-
return [_read_one(str(path), path, guard)]
|
|
326
|
-
members = _archive_members(path, guard)
|
|
327
|
-
if members is None: # not a readable archive, or an OFD file named .zip
|
|
328
|
-
return [_read_one(str(path), path, guard)]
|
|
329
|
-
if not members:
|
|
330
|
-
return [InvoiceFile(str(path), error=EMPTY_ARCHIVE)]
|
|
331
374
|
results = []
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
results.append(InvoiceFile(label, error=f"too large to read from the archive ({info.file_size} bytes)"))
|
|
338
|
-
continue
|
|
339
|
-
try:
|
|
340
|
-
data = archive.read(info)
|
|
341
|
-
except (zipfile.BadZipFile, zlib.error, RuntimeError, NotImplementedError, EOFError) as exc:
|
|
342
|
-
# RuntimeError: a password-protected entry.
|
|
343
|
-
results.append(InvoiceFile(label, error=f"cannot read from the archive: {exc}"))
|
|
344
|
-
continue
|
|
345
|
-
results.append(_read_one(label, data))
|
|
346
|
-
except (zipfile.BadZipFile, OSError) as exc:
|
|
347
|
-
return [*results, InvoiceFile(str(path), error=f"cannot read the archive: {exc}")]
|
|
375
|
+
for item in iter_document_inputs(path, limit, guard, member_size_limit=MAX_ARCHIVE_MEMBER_SIZE):
|
|
376
|
+
if item.source is None:
|
|
377
|
+
results.append(InvoiceFile(item.file, error=item.error))
|
|
378
|
+
else:
|
|
379
|
+
results.append(_read_one(item.file, item.source, guard))
|
|
348
380
|
return results
|
|
349
381
|
|
|
350
382
|
|
|
351
|
-
def _archive_members(path: Path, guard: PathGuard | None = None) -> list[zipfile.ZipInfo] | None:
|
|
352
|
-
"""The ``.ofd`` entries of a ZIP archive, or None if ``path`` is no archive of OFD files."""
|
|
353
|
-
try:
|
|
354
|
-
with _open(path, guard) as stream, zipfile.ZipFile(stream) as archive:
|
|
355
|
-
infos = archive.infolist()
|
|
356
|
-
except (zipfile.BadZipFile, OSError, ValueError, EOFError):
|
|
357
|
-
return None
|
|
358
|
-
if len(infos) > MAX_ENTRIES:
|
|
359
|
-
return None
|
|
360
|
-
names = [(_normalize(_entry_name(info)), info) for info in infos if not info.is_dir()]
|
|
361
|
-
if any(name.casefold() == "ofd.xml" for name, _ in names): # an OFD file itself
|
|
362
|
-
return None
|
|
363
|
-
return [info for name, info in sorted(names, key=lambda pair: pair[0]) if name.lower().endswith(".ofd")]
|
|
364
|
-
|
|
365
|
-
|
|
366
383
|
def _read_one(label: str, source: Path | bytes, guard: PathGuard | None = None) -> InvoiceFile:
|
|
367
384
|
try:
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
invoice = document.invoice()
|
|
371
|
-
else:
|
|
372
|
-
with OFDDocument(source) as document:
|
|
373
|
-
invoice = document.invoice()
|
|
385
|
+
with open_document_source(source, guard) as document:
|
|
386
|
+
invoice = document.invoice()
|
|
374
387
|
except (OFDError, OSError) as exc:
|
|
375
388
|
return InvoiceFile(label, error=str(exc))
|
|
376
389
|
if invoice is None:
|
|
@@ -378,11 +391,6 @@ def _read_one(label: str, source: Path | bytes, guard: PathGuard | None = None)
|
|
|
378
391
|
return InvoiceFile(label, invoice=invoice)
|
|
379
392
|
|
|
380
393
|
|
|
381
|
-
def _open(path: Path, guard: PathGuard | None) -> BinaryIO:
|
|
382
|
-
"""Open a file for reading, through ``guard`` when there is one."""
|
|
383
|
-
return guard.open(path) if guard is not None else open(path, "rb")
|
|
384
|
-
|
|
385
|
-
|
|
386
394
|
def _duplicate_key(result: InvoiceFile) -> tuple[str, str] | None:
|
|
387
395
|
"""Older invoices are unique only by code and number together; 数电票 have no code."""
|
|
388
396
|
invoice = result.invoice
|