ofdkit 0.1.0__tar.gz → 0.3.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.3.0/PKG-INFO ADDED
@@ -0,0 +1,273 @@
1
+ Metadata-Version: 2.4
2
+ Name: ofdkit
3
+ Version: 0.3.0
4
+ Summary: Read OFD documents (GB/T 33190) and Chinese e-invoices: text, invoice fields, and AI tool integrations.
5
+ Keywords: ofd,gb/t 33190,e-invoice,fapiao,电子发票,数电票,mcp
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Natural Language :: Chinese (Simplified)
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
15
+ Classifier: Topic :: Text Processing
16
+ Requires-Dist: markitdown>=0.1,<0.2 ; extra == 'markitdown'
17
+ Requires-Dist: mcp>=2.3,<3 ; extra == 'mcp'
18
+ Maintainer: Edgar-311
19
+ Requires-Python: >=3.10
20
+ Project-URL: Homepage, https://github.com/Edgar-311/ofdkit
21
+ Project-URL: Issues, https://github.com/Edgar-311/ofdkit/issues
22
+ Project-URL: Changelog, https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md
23
+ Provides-Extra: markitdown
24
+ Provides-Extra: mcp
25
+ Description-Content-Type: text/markdown
26
+
27
+ # ofdkit
28
+
29
+ 轻量的 Python 工具,用来读取 OFD 文件,提取里面的文字和发票字段,并能接入 AI 工具。OFD 是中国的国家标准版式文档格式(GB/T 33190),常见于电子发票和公文。
30
+
31
+ 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.
32
+
33
+ > 状态:0.3 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
34
+ > Status: 0.3, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
35
+
36
+ ## 能做什么 / What it does
37
+
38
+ - 看发票:一条命令显示发票号码、日期、购买方、销售方、金额和明细。
39
+ Show an invoice: number, date, buyer, seller, amounts and line items, with one command.
40
+ - 把一个文件夹里的发票汇总到 Excel,也能直接读税务平台批量下载的 .zip 压缩包。发票号码保持原样(不会变成 2.4E+19),金额可以直接求和,重复的发票会标出来。
41
+ Summarise a folder of invoices, or a .zip archive downloaded from the tax service, into an Excel workbook: invoice numbers stay intact, amounts are numbers, duplicates are flagged.
42
+ - 报销帮手:检查发票抬头(购买方名称、税号)对不对;按发票内容给文件改名,可以预览、可以改回去。
43
+ 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.
44
+ - 按阅读顺序提取文字,包括模板和复合对象里的文字。
45
+ Text in reading order, including text in templates and composite objects.
46
+ - 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。
47
+ For programs and AI: invoice fields as JSON, an MCP server, an Agent Skill and a MarkItDown plugin.
48
+ - 只用 Python 标准库,没有任何第三方依赖;能读很多不规范的文件(路径写法不对、编码不对、XML 前缀错误等)。
49
+ Standard library only, no dependencies; reads many non-conforming files (bad paths, encodings, XML prefixes).
50
+
51
+ ## 快速上手 / Quick start
52
+
53
+ 1. 安装 [Python](https://www.python.org/downloads/) 3.10 或更新版本。Windows 上安装时请勾选 "Add python.exe to PATH"。
54
+ Install Python 3.10 or newer.
55
+ 2. 打开命令行(Windows 在开始菜单搜索"终端"或"cmd",Mac 打开"终端"),安装 ofdkit:
56
+ Open a terminal and install ofdkit:
57
+
58
+ ```bash
59
+ pip install ofdkit
60
+ ```
61
+
62
+ 3. 看一张发票(把文件拖进命令行窗口就能填上路径):
63
+ Show an invoice (drag the file into the terminal window to type its path):
64
+
65
+ ```bash
66
+ ofdkit 发票.ofd
67
+ ```
68
+
69
+ ```text
70
+ 电子发票(普通发票)
71
+
72
+ 发票号码 00000000000000000001
73
+ 开票日期 2026-01-02
74
+ 购买方 测试单位甲
75
+ 税号 TESTBUYER0001
76
+ 销售方 测试单位乙
77
+ 税号 TESTSELLER0002
78
+ 金额 100.00
79
+ 税额 6.00
80
+ 价税合计 106.00
81
+ 明细 *测试*服务项目 100.00 6%
82
+ 开票人 测试人员
83
+ ```
84
+
85
+ (数据是虚构的 / fictional data)
86
+
87
+ 4. 看一个文件夹或 .zip 压缩包里的所有发票和合计,然后导出到 Excel:
88
+ List every invoice in a folder or .zip archive with totals, then export to Excel:
89
+
90
+ ```bash
91
+ ofdkit 发票文件夹
92
+ ofdkit batch 发票文件夹 -o 发票汇总.xlsx
93
+ ```
94
+
95
+ Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红并写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行。
96
+ 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.
97
+
98
+ 5. 检查发票抬头:加上 `--buyer`,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次:
99
+ 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:
100
+
101
+ ```bash
102
+ ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
103
+ ```
104
+
105
+ 6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML 会一起改;改名记录可以用 `--undo` 改回去:
106
+ 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:
107
+
108
+ ```bash
109
+ ofdkit rename 发票文件夹 # 预览 / preview
110
+ ofdkit rename 发票文件夹 --apply # 改名 / rename
111
+ ofdkit rename --undo 发票文件夹/改名记录_20261028_093000.csv
112
+ ```
113
+
114
+ 名字的格式可以改,例如 `--pattern "{开票日期}_{购买方}_{商品}"`。可以用的字段:开票日期、发票号码、发票代码、发票种类、销售方、销售方税号、购买方、购买方税号、金额、税额、价税合计、商品、原文件名。
115
+ The name format can be changed with `--pattern`; fields are listed by `ofdkit rename --help` (English names such as `{date}`, `{seller}` and `{total}` work too).
116
+
117
+ ## 命令行 / Command line
118
+
119
+ ```bash
120
+ ofdkit 文件.ofd # 看发票,不是发票就显示文字 / show an invoice, or the text
121
+ ofdkit 文件夹或压缩包.zip # 发票列表和合计 / list invoices with totals
122
+ ofdkit batch 文件夹 -o 发票汇总.xlsx # 导出 Excel / export to Excel
123
+ ofdkit batch 文件夹 -o 发票汇总.csv # 导出 CSV(给程序用)/ export CSV for programs
124
+ ofdkit 文件夹 --buyer 公司名或税号 # 检查发票抬头 / check the buyer
125
+ ofdkit rename 文件夹 # 按内容改名(先预览)/ rename after contents (preview first)
126
+ ofdkit text 文件.ofd # 提取文字 / print text
127
+ ofdkit invoice 发票.ofd # 发票字段(JSON)/ invoice fields as JSON
128
+ ofdkit info 文件.ofd # 页数、作者等信息 / pages and metadata
129
+ ofdkit describe 文件.ofd -o 结构.json # 打码的结构,用于报告问题 / masked structure for bug reports
130
+ ```
131
+
132
+ `show`、`batch` 和 `rename` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
133
+ Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
134
+
135
+ `ofdkit invoice` 的输出示例(数据是虚构的)/ Example output (fictional data):
136
+
137
+ ```json
138
+ {
139
+ "invoice_number": "00000000000000000001",
140
+ "invoice_code": null,
141
+ "issue_date": "2026-01-02",
142
+ "check_code": null,
143
+ "machine_number": null,
144
+ "buyer": {"name": "测试单位甲", "tax_id": "TESTBUYER0001", "address_phone": null, "bank_account": null},
145
+ "seller": {"name": "测试单位乙", "tax_id": "TESTSELLER0002", "address_phone": null, "bank_account": null},
146
+ "amount_without_tax": "100.00",
147
+ "tax_amount": "6.00",
148
+ "total_amount": "106.00",
149
+ "issuer": "测试人员",
150
+ "payee": null,
151
+ "reviewer": null,
152
+ "note": null,
153
+ "items": [
154
+ {"name": "*测试*服务项目", "specification": null, "unit": null, "quantity": null,
155
+ "unit_price": null, "amount": "100.00", "tax_rate": "6%", "tax_amount": "6.00"}
156
+ ],
157
+ "sources": ["custom_tags"],
158
+ "warnings": []
159
+ }
160
+ ```
161
+
162
+ 金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",`warnings` 里会提示。
163
+ Amounts are decimal strings, so no precision is lost. `warnings` notes totals that do not add up.
164
+
165
+ ## 在 AI 工具里使用 / Use from AI tools
166
+
167
+ ### MCP 服务器 / MCP server
168
+
169
+ 让 Claude、Codex、Cursor 等 AI 工具直接读取 OFD 文件。需要先安装 [uv](https://docs.astral.sh/uv/)。所有工具都是只读的。
170
+ Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires [uv](https://docs.astral.sh/uv/). All tools are read-only.
171
+
172
+ | 工具 / Tool | 作用 / What it does |
173
+ | --- | --- |
174
+ | `read_ofd_text` | 按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range |
175
+ | `read_ofd_invoice` | 发票字段 / invoice fields |
176
+ | `ofd_info` | 页数、尺寸、元数据 / pages, sizes, metadata |
177
+ | `list_ofd_invoices` | 汇总一个文件夹里的发票,可以检查抬头 / summarise a folder of invoices, optionally checking the buyer |
178
+
179
+ Claude Code:
180
+
181
+ ```bash
182
+ claude mcp add ofdkit -- uvx --from "ofdkit[mcp]" ofdkit mcp
183
+ ```
184
+
185
+ Claude Desktop、Cursor 等使用 JSON 配置的工具 / tools with a JSON config:
186
+
187
+ ```json
188
+ {
189
+ "mcpServers": {
190
+ "ofdkit": {
191
+ "command": "uvx",
192
+ "args": ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
193
+ }
194
+ }
195
+ }
196
+ ```
197
+
198
+ Codex(`~/.codex/config.toml`):
199
+
200
+ ```toml
201
+ [mcp_servers.ofdkit]
202
+ command = "uvx"
203
+ args = ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
204
+ ```
205
+
206
+ 加上 `--root 文件夹` 可以只允许读取这个文件夹里的文件。
207
+ Add `--root FOLDER` to allow only files inside that folder.
208
+
209
+ ### Agent Skill
210
+
211
+ [`skills/ofd-reader`](https://github.com/Edgar-311/ofdkit/tree/main/skills/ofd-reader) 告诉 AI 什么时候、怎么用 ofdkit 命令行,适用于支持 [Agent Skills](https://agentskills.io) 的工具。把这个文件夹复制到:
212
+ [`skills/ofd-reader`](https://github.com/Edgar-311/ofdkit/tree/main/skills/ofd-reader) tells an AI agent when and how to use the ofdkit command line. Copy the folder to:
213
+
214
+ - Claude Code: `~/.claude/skills/ofd-reader/`
215
+ - Codex: `~/.codex/skills/ofd-reader/`
216
+
217
+ ### MarkItDown 插件 / MarkItDown plugin
218
+
219
+ [MarkItDown](https://github.com/microsoft/markitdown) 是把各种文件转成 Markdown 给 AI 读的工具。安装插件后它就能读 OFD:
220
+ [MarkItDown](https://github.com/microsoft/markitdown) converts files to Markdown for AI. With this plugin it reads OFD too:
221
+
222
+ ```bash
223
+ pip install "ofdkit[markitdown]"
224
+ markitdown --use-plugins 发票.ofd
225
+ ```
226
+
227
+ ## Python
228
+
229
+ ```python
230
+ import ofdkit
231
+
232
+ with ofdkit.open("发票.ofd") as doc:
233
+ print(doc.text())
234
+ invoice = doc.invoice() # 不是发票时返回 None / None if not an invoice
235
+ if invoice:
236
+ print(invoice.invoice_number, invoice.total_amount)
237
+
238
+ # 文件夹、.zip 压缩包或多个文件 / folders, ZIP archives or several files
239
+ for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["某某有限公司"]):
240
+ if result.invoice:
241
+ print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "", result.buyer_mismatch)
242
+ else:
243
+ print(result.file, result.error)
244
+ ```
245
+
246
+ ## 遇到读不出的文件 / Reporting a problem
247
+
248
+ 请不要把真实发票发到网上。用这个命令导出文件结构,文字会全部打码,只保留结构和位置,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里:
249
+ 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):
250
+
251
+ ```bash
252
+ ofdkit describe 文件.ofd -o 结构.json
253
+ ```
254
+
255
+ ## 注意 / Notes
256
+
257
+ - ofdkit 只读取文件里写了什么,不验证发票真伪。查验真伪请使用国家税务总局的发票查验平台。
258
+ ofdkit reports what a file contains. It does not verify that an invoice is genuine.
259
+ - 文字如果是画成图形或图片的,就读不出来(需要 OCR,不在本项目范围内)。
260
+ Text drawn as shapes or images cannot be extracted (that needs OCR, which is out of scope).
261
+ - 阅读顺序是根据位置推测的。两栏的正文会按栏读,表格按行读;版面特别复杂的页面(比如多栏加图片的杂志页)可能不完全准确。
262
+ Reading order is inferred from positions. Prose columns are read column by column and tables row by row; very complex pages (magazine layouts with pictures) may not come out perfectly.
263
+
264
+ ## 原则 / Principles
265
+
266
+ - 只读取 OFD,不生成、不修改发票。
267
+ Reads OFD only. It never creates or modifies invoices.
268
+ - 本项目大部分代码由 AI(Claude)编写,维护者负责决定方向和批准发布。
269
+ Most code is written with AI assistance (Claude). The maintainer sets the direction and approves releases.
270
+
271
+ ## 许可证 / License
272
+
273
+ [Apache-2.0](https://github.com/Edgar-311/ofdkit/blob/main/LICENSE)
ofdkit-0.3.0/README.md ADDED
@@ -0,0 +1,247 @@
1
+ # ofdkit
2
+
3
+ 轻量的 Python 工具,用来读取 OFD 文件,提取里面的文字和发票字段,并能接入 AI 工具。OFD 是中国的国家标准版式文档格式(GB/T 33190),常见于电子发票和公文。
4
+
5
+ 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.
6
+
7
+ > 状态:0.3 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
8
+ > Status: 0.3, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
9
+
10
+ ## 能做什么 / What it does
11
+
12
+ - 看发票:一条命令显示发票号码、日期、购买方、销售方、金额和明细。
13
+ Show an invoice: number, date, buyer, seller, amounts and line items, with one command.
14
+ - 把一个文件夹里的发票汇总到 Excel,也能直接读税务平台批量下载的 .zip 压缩包。发票号码保持原样(不会变成 2.4E+19),金额可以直接求和,重复的发票会标出来。
15
+ Summarise a folder of invoices, or a .zip archive downloaded from the tax service, into an Excel workbook: invoice numbers stay intact, amounts are numbers, duplicates are flagged.
16
+ - 报销帮手:检查发票抬头(购买方名称、税号)对不对;按发票内容给文件改名,可以预览、可以改回去。
17
+ 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.
18
+ - 按阅读顺序提取文字,包括模板和复合对象里的文字。
19
+ Text in reading order, including text in templates and composite objects.
20
+ - 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。
21
+ For programs and AI: invoice fields as JSON, an MCP server, an Agent Skill and a MarkItDown plugin.
22
+ - 只用 Python 标准库,没有任何第三方依赖;能读很多不规范的文件(路径写法不对、编码不对、XML 前缀错误等)。
23
+ Standard library only, no dependencies; reads many non-conforming files (bad paths, encodings, XML prefixes).
24
+
25
+ ## 快速上手 / Quick start
26
+
27
+ 1. 安装 [Python](https://www.python.org/downloads/) 3.10 或更新版本。Windows 上安装时请勾选 "Add python.exe to PATH"。
28
+ Install Python 3.10 or newer.
29
+ 2. 打开命令行(Windows 在开始菜单搜索"终端"或"cmd",Mac 打开"终端"),安装 ofdkit:
30
+ Open a terminal and install ofdkit:
31
+
32
+ ```bash
33
+ pip install ofdkit
34
+ ```
35
+
36
+ 3. 看一张发票(把文件拖进命令行窗口就能填上路径):
37
+ Show an invoice (drag the file into the terminal window to type its path):
38
+
39
+ ```bash
40
+ ofdkit 发票.ofd
41
+ ```
42
+
43
+ ```text
44
+ 电子发票(普通发票)
45
+
46
+ 发票号码 00000000000000000001
47
+ 开票日期 2026-01-02
48
+ 购买方 测试单位甲
49
+ 税号 TESTBUYER0001
50
+ 销售方 测试单位乙
51
+ 税号 TESTSELLER0002
52
+ 金额 100.00
53
+ 税额 6.00
54
+ 价税合计 106.00
55
+ 明细 *测试*服务项目 100.00 6%
56
+ 开票人 测试人员
57
+ ```
58
+
59
+ (数据是虚构的 / fictional data)
60
+
61
+ 4. 看一个文件夹或 .zip 压缩包里的所有发票和合计,然后导出到 Excel:
62
+ List every invoice in a folder or .zip archive with totals, then export to Excel:
63
+
64
+ ```bash
65
+ ofdkit 发票文件夹
66
+ ofdkit batch 发票文件夹 -o 发票汇总.xlsx
67
+ ```
68
+
69
+ Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红并写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行。
70
+ 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.
71
+
72
+ 5. 检查发票抬头:加上 `--buyer`,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次:
73
+ 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:
74
+
75
+ ```bash
76
+ ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
77
+ ```
78
+
79
+ 6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML 会一起改;改名记录可以用 `--undo` 改回去:
80
+ 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:
81
+
82
+ ```bash
83
+ ofdkit rename 发票文件夹 # 预览 / preview
84
+ ofdkit rename 发票文件夹 --apply # 改名 / rename
85
+ ofdkit rename --undo 发票文件夹/改名记录_20261028_093000.csv
86
+ ```
87
+
88
+ 名字的格式可以改,例如 `--pattern "{开票日期}_{购买方}_{商品}"`。可以用的字段:开票日期、发票号码、发票代码、发票种类、销售方、销售方税号、购买方、购买方税号、金额、税额、价税合计、商品、原文件名。
89
+ The name format can be changed with `--pattern`; fields are listed by `ofdkit rename --help` (English names such as `{date}`, `{seller}` and `{total}` work too).
90
+
91
+ ## 命令行 / Command line
92
+
93
+ ```bash
94
+ ofdkit 文件.ofd # 看发票,不是发票就显示文字 / show an invoice, or the text
95
+ ofdkit 文件夹或压缩包.zip # 发票列表和合计 / list invoices with totals
96
+ ofdkit batch 文件夹 -o 发票汇总.xlsx # 导出 Excel / export to Excel
97
+ ofdkit batch 文件夹 -o 发票汇总.csv # 导出 CSV(给程序用)/ export CSV for programs
98
+ ofdkit 文件夹 --buyer 公司名或税号 # 检查发票抬头 / check the buyer
99
+ ofdkit rename 文件夹 # 按内容改名(先预览)/ rename after contents (preview first)
100
+ ofdkit text 文件.ofd # 提取文字 / print text
101
+ ofdkit invoice 发票.ofd # 发票字段(JSON)/ invoice fields as JSON
102
+ ofdkit info 文件.ofd # 页数、作者等信息 / pages and metadata
103
+ ofdkit describe 文件.ofd -o 结构.json # 打码的结构,用于报告问题 / masked structure for bug reports
104
+ ```
105
+
106
+ `show`、`batch` 和 `rename` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
107
+ Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
108
+
109
+ `ofdkit invoice` 的输出示例(数据是虚构的)/ Example output (fictional data):
110
+
111
+ ```json
112
+ {
113
+ "invoice_number": "00000000000000000001",
114
+ "invoice_code": null,
115
+ "issue_date": "2026-01-02",
116
+ "check_code": null,
117
+ "machine_number": null,
118
+ "buyer": {"name": "测试单位甲", "tax_id": "TESTBUYER0001", "address_phone": null, "bank_account": null},
119
+ "seller": {"name": "测试单位乙", "tax_id": "TESTSELLER0002", "address_phone": null, "bank_account": null},
120
+ "amount_without_tax": "100.00",
121
+ "tax_amount": "6.00",
122
+ "total_amount": "106.00",
123
+ "issuer": "测试人员",
124
+ "payee": null,
125
+ "reviewer": null,
126
+ "note": null,
127
+ "items": [
128
+ {"name": "*测试*服务项目", "specification": null, "unit": null, "quantity": null,
129
+ "unit_price": null, "amount": "100.00", "tax_rate": "6%", "tax_amount": "6.00"}
130
+ ],
131
+ "sources": ["custom_tags"],
132
+ "warnings": []
133
+ }
134
+ ```
135
+
136
+ 金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",`warnings` 里会提示。
137
+ Amounts are decimal strings, so no precision is lost. `warnings` notes totals that do not add up.
138
+
139
+ ## 在 AI 工具里使用 / Use from AI tools
140
+
141
+ ### MCP 服务器 / MCP server
142
+
143
+ 让 Claude、Codex、Cursor 等 AI 工具直接读取 OFD 文件。需要先安装 [uv](https://docs.astral.sh/uv/)。所有工具都是只读的。
144
+ Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires [uv](https://docs.astral.sh/uv/). All tools are read-only.
145
+
146
+ | 工具 / Tool | 作用 / What it does |
147
+ | --- | --- |
148
+ | `read_ofd_text` | 按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range |
149
+ | `read_ofd_invoice` | 发票字段 / invoice fields |
150
+ | `ofd_info` | 页数、尺寸、元数据 / pages, sizes, metadata |
151
+ | `list_ofd_invoices` | 汇总一个文件夹里的发票,可以检查抬头 / summarise a folder of invoices, optionally checking the buyer |
152
+
153
+ Claude Code:
154
+
155
+ ```bash
156
+ claude mcp add ofdkit -- uvx --from "ofdkit[mcp]" ofdkit mcp
157
+ ```
158
+
159
+ Claude Desktop、Cursor 等使用 JSON 配置的工具 / tools with a JSON config:
160
+
161
+ ```json
162
+ {
163
+ "mcpServers": {
164
+ "ofdkit": {
165
+ "command": "uvx",
166
+ "args": ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
167
+ }
168
+ }
169
+ }
170
+ ```
171
+
172
+ Codex(`~/.codex/config.toml`):
173
+
174
+ ```toml
175
+ [mcp_servers.ofdkit]
176
+ command = "uvx"
177
+ args = ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
178
+ ```
179
+
180
+ 加上 `--root 文件夹` 可以只允许读取这个文件夹里的文件。
181
+ Add `--root FOLDER` to allow only files inside that folder.
182
+
183
+ ### Agent Skill
184
+
185
+ [`skills/ofd-reader`](https://github.com/Edgar-311/ofdkit/tree/main/skills/ofd-reader) 告诉 AI 什么时候、怎么用 ofdkit 命令行,适用于支持 [Agent Skills](https://agentskills.io) 的工具。把这个文件夹复制到:
186
+ [`skills/ofd-reader`](https://github.com/Edgar-311/ofdkit/tree/main/skills/ofd-reader) tells an AI agent when and how to use the ofdkit command line. Copy the folder to:
187
+
188
+ - Claude Code: `~/.claude/skills/ofd-reader/`
189
+ - Codex: `~/.codex/skills/ofd-reader/`
190
+
191
+ ### MarkItDown 插件 / MarkItDown plugin
192
+
193
+ [MarkItDown](https://github.com/microsoft/markitdown) 是把各种文件转成 Markdown 给 AI 读的工具。安装插件后它就能读 OFD:
194
+ [MarkItDown](https://github.com/microsoft/markitdown) converts files to Markdown for AI. With this plugin it reads OFD too:
195
+
196
+ ```bash
197
+ pip install "ofdkit[markitdown]"
198
+ markitdown --use-plugins 发票.ofd
199
+ ```
200
+
201
+ ## Python
202
+
203
+ ```python
204
+ import ofdkit
205
+
206
+ with ofdkit.open("发票.ofd") as doc:
207
+ print(doc.text())
208
+ invoice = doc.invoice() # 不是发票时返回 None / None if not an invoice
209
+ if invoice:
210
+ print(invoice.invoice_number, invoice.total_amount)
211
+
212
+ # 文件夹、.zip 压缩包或多个文件 / folders, ZIP archives or several files
213
+ for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["某某有限公司"]):
214
+ if result.invoice:
215
+ print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "", result.buyer_mismatch)
216
+ else:
217
+ print(result.file, result.error)
218
+ ```
219
+
220
+ ## 遇到读不出的文件 / Reporting a problem
221
+
222
+ 请不要把真实发票发到网上。用这个命令导出文件结构,文字会全部打码,只保留结构和位置,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里:
223
+ 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):
224
+
225
+ ```bash
226
+ ofdkit describe 文件.ofd -o 结构.json
227
+ ```
228
+
229
+ ## 注意 / Notes
230
+
231
+ - ofdkit 只读取文件里写了什么,不验证发票真伪。查验真伪请使用国家税务总局的发票查验平台。
232
+ ofdkit reports what a file contains. It does not verify that an invoice is genuine.
233
+ - 文字如果是画成图形或图片的,就读不出来(需要 OCR,不在本项目范围内)。
234
+ Text drawn as shapes or images cannot be extracted (that needs OCR, which is out of scope).
235
+ - 阅读顺序是根据位置推测的。两栏的正文会按栏读,表格按行读;版面特别复杂的页面(比如多栏加图片的杂志页)可能不完全准确。
236
+ Reading order is inferred from positions. Prose columns are read column by column and tables row by row; very complex pages (magazine layouts with pictures) may not come out perfectly.
237
+
238
+ ## 原则 / Principles
239
+
240
+ - 只读取 OFD,不生成、不修改发票。
241
+ Reads OFD only. It never creates or modifies invoices.
242
+ - 本项目大部分代码由 AI(Claude)编写,维护者负责决定方向和批准发布。
243
+ Most code is written with AI assistance (Claude). The maintainer sets the direction and approves releases.
244
+
245
+ ## 许可证 / License
246
+
247
+ [Apache-2.0](https://github.com/Edgar-311/ofdkit/blob/main/LICENSE)
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "ofdkit"
7
- version = "0.1.0"
7
+ version = "0.3.0"
8
8
  description = "Read OFD documents (GB/T 33190) and Chinese e-invoices: text, invoice fields, and AI tool integrations."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -9,6 +9,7 @@
9
9
  from importlib.metadata import PackageNotFoundError
10
10
  from importlib.metadata import version as _version
11
11
 
12
+ from .batch import InvoiceFile, read_invoices
12
13
  from .document import DocInfo, OFDDocument, Page, TextRun
13
14
  from .errors import OFDError, OFDFormatError, OFDLimitError
14
15
  from .invoice import Invoice, LineItem, Party
@@ -22,6 +23,7 @@ except PackageNotFoundError: # running from a source checkout that is not insta
22
23
  __all__ = [
23
24
  "DocInfo",
24
25
  "Invoice",
26
+ "InvoiceFile",
25
27
  "LineItem",
26
28
  "OFDDocument",
27
29
  "OFDError",
@@ -34,6 +36,7 @@ __all__ = [
34
36
  "extract_invoice",
35
37
  "extract_text",
36
38
  "open",
39
+ "read_invoices",
37
40
  ]
38
41
 
39
42
 
@@ -68,6 +68,11 @@ def child_text(element: ET.Element | None, name: str) -> str | None:
68
68
 
69
69
  def parse_xml(data: bytes, name: str = "XML") -> ET.Element:
70
70
  """Parse an XML part strictly, falling back to a repaired copy for broken files."""
71
+ return parse_xml_reporting(data, name)[0]
72
+
73
+
74
+ def parse_xml_reporting(data: bytes, name: str = "XML") -> tuple[ET.Element, bool]:
75
+ """Like parse_xml, and also say whether the part needed repairing to parse."""
71
76
  try:
72
77
  text = _decode(data)
73
78
  except UnicodeError as exc:
@@ -76,14 +81,24 @@ def parse_xml(data: bytes, name: str = "XML") -> ET.Element:
76
81
  raise OFDLimitError(f"{name}: DTDs and entity declarations are not allowed")
77
82
  text = _XML_DECLARATION.sub("", text, count=1)
78
83
  try:
79
- return ET.fromstring(text)
84
+ return ET.fromstring(text), False
80
85
  except ET.ParseError as first_error:
81
86
  try:
82
- return ET.fromstring(_repair(text))
87
+ return ET.fromstring(_repair(text)), True
83
88
  except ET.ParseError:
84
89
  raise OFDFormatError(f"{name}: invalid XML: {first_error}") from first_error
85
90
 
86
91
 
92
+ def declared_encoding(data: bytes) -> str | None:
93
+ """The encoding named in the XML declaration, 'BOM:UTF-8'/'BOM:UTF-16' for a byte order mark, or None."""
94
+ if data.startswith(codecs.BOM_UTF8):
95
+ return "BOM:UTF-8"
96
+ if data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)):
97
+ return "BOM:UTF-16"
98
+ match = _DECLARED_ENCODING.match(data)
99
+ return match.group(1).decode("ascii") if match else None
100
+
101
+
87
102
  def _decode(data: bytes) -> str:
88
103
  if data.startswith(codecs.BOM_UTF8):
89
104
  return data[len(codecs.BOM_UTF8):].decode("utf-8", errors="replace")