ofdkit 0.1.0__tar.gz → 0.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ofdkit
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Read OFD documents (GB/T 33190) and Chinese e-invoices: text, invoice fields, and AI tool integrations.
5
5
  Keywords: ofd,gb/t 33190,e-invoice,fapiao,电子发票,数电票,mcp
6
6
  License-Expression: Apache-2.0
@@ -30,37 +30,85 @@ Description-Content-Type: text/markdown
30
30
 
31
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
32
 
33
- > 状态:0.1 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
34
- > Status: 0.1, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
33
+ > 状态:0.2 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
34
+ > Status: 0.2, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
35
35
 
36
36
  ## 能做什么 / What it does
37
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.
38
42
  - 按阅读顺序提取文字,包括模板和复合对象里的文字。
39
43
  Text in reading order, including text in templates and composite objects.
40
- - 读取电子发票字段(数电票和增值税电子发票),输出 JSON:发票号码、开票日期、购买方、销售方、金额、税额、价税合计、明细。
41
- Invoice fields from e-invoices as JSON: number, date, buyer, seller, amounts, tax, total, line items.
42
- - 把一个文件夹里的发票汇总成 CSV,Excel 可以直接打开,并提示重复的发票号码。
43
- A folder of invoices summarised as CSV (opens in Excel), with duplicate invoice numbers flagged.
44
+ - 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。
45
+ For programs and AI: invoice fields as JSON, an MCP server, an Agent Skill and a MarkItDown plugin.
44
46
  - 只用 Python 标准库,没有任何第三方依赖;能读很多不规范的文件(路径写法不对、编码不对、XML 前缀错误等)。
45
47
  Standard library only, no dependencies; reads many non-conforming files (bad paths, encodings, XML prefixes).
46
48
 
47
- ## 安装 / Install
49
+ ## 快速上手 / Quick start
48
50
 
49
- 需要 Python 3.10 或更新版本。Requires Python 3.10+.
51
+ 1. 安装 [Python](https://www.python.org/downloads/) 3.10 或更新版本。Windows 上安装时请勾选 "Add python.exe to PATH"。
52
+ Install Python 3.10 or newer.
53
+ 2. 打开命令行(Windows 在开始菜单搜索"终端"或"cmd",Mac 打开"终端"),安装 ofdkit:
54
+ Open a terminal and install ofdkit:
50
55
 
51
- ```bash
52
- pip install ofdkit
53
- ```
56
+ ```bash
57
+ pip install ofdkit
58
+ ```
59
+
60
+ 3. 看一张发票(把文件拖进命令行窗口就能填上路径):
61
+ Show an invoice (drag the file into the terminal window to type its path):
62
+
63
+ ```bash
64
+ ofdkit 发票.ofd
65
+ ```
66
+
67
+ ```text
68
+ 电子发票(普通发票)
69
+
70
+ 发票号码 00000000000000000001
71
+ 开票日期 2026-01-02
72
+ 购买方 测试单位甲
73
+ 税号 TESTBUYER0001
74
+ 销售方 测试单位乙
75
+ 税号 TESTSELLER0002
76
+ 金额 100.00
77
+ 税额 6.00
78
+ 价税合计 106.00
79
+ 明细 *测试*服务项目 100.00 6%
80
+ 开票人 测试人员
81
+ ```
82
+
83
+ (数据是虚构的 / fictional data)
84
+
85
+ 4. 看一个文件夹或 .zip 压缩包里的所有发票和合计,然后导出到 Excel:
86
+ List every invoice in a folder or .zip archive with totals, then export to Excel:
87
+
88
+ ```bash
89
+ ofdkit 发票文件夹
90
+ ofdkit batch 发票文件夹 -o 发票汇总.xlsx
91
+ ```
92
+
93
+ Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红并写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行。
94
+ 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.
54
95
 
55
96
  ## 命令行 / Command line
56
97
 
57
98
  ```bash
99
+ ofdkit 文件.ofd # 看发票,不是发票就显示文字 / show an invoice, or the text
100
+ ofdkit 文件夹或压缩包.zip # 发票列表和合计 / list invoices with totals
101
+ ofdkit batch 文件夹 -o 发票汇总.xlsx # 导出 Excel / export to Excel
102
+ ofdkit batch 文件夹 -o 发票汇总.csv # 导出 CSV(给程序用)/ export CSV for programs
58
103
  ofdkit text 文件.ofd # 提取文字 / print text
59
104
  ofdkit invoice 发票.ofd # 发票字段(JSON)/ invoice fields as JSON
60
- ofdkit batch 发票文件夹/ -o 发票汇总.csv # 批量汇总 / summarise a folder as CSV
61
105
  ofdkit info 文件.ofd # 页数、作者等信息 / pages and metadata
106
+ ofdkit describe 文件.ofd -o 结构.json # 打码的结构,用于报告问题 / masked structure for bug reports
62
107
  ```
63
108
 
109
+ `batch` 和 `show` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
110
+ Add `-r` to `batch` and `show` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
111
+
64
112
  `ofdkit invoice` 的输出示例(数据是虚构的)/ Example output (fictional data):
65
113
 
66
114
  ```json
@@ -163,6 +211,22 @@ with ofdkit.open("发票.ofd") as doc:
163
211
  invoice = doc.invoice() # 不是发票时返回 None / None if not an invoice
164
212
  if invoice:
165
213
  print(invoice.invoice_number, invoice.total_amount)
214
+
215
+ # 文件夹、.zip 压缩包或多个文件 / folders, ZIP archives or several files
216
+ for result in ofdkit.read_invoices("发票文件夹", recursive=True):
217
+ if result.invoice:
218
+ print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "")
219
+ else:
220
+ print(result.file, result.error)
221
+ ```
222
+
223
+ ## 遇到读不出的文件 / Reporting a problem
224
+
225
+ 请不要把真实发票发到网上。用这个命令导出文件结构,文字会全部打码,只保留结构和位置,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里:
226
+ 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):
227
+
228
+ ```bash
229
+ ofdkit describe 文件.ofd -o 结构.json
166
230
  ```
167
231
 
168
232
  ## 注意 / Notes
@@ -171,8 +235,8 @@ with ofdkit.open("发票.ofd") as doc:
171
235
  ofdkit reports what a file contains. It does not verify that an invoice is genuine.
172
236
  - 文字如果是画成图形或图片的,就读不出来(需要 OCR,不在本项目范围内)。
173
237
  Text drawn as shapes or images cannot be extracted (that needs OCR, which is out of scope).
174
- - 多栏排版的页面,目前两栏的文字会出现在同一行,用三个空格隔开。
175
- On multi-column pages, both columns currently share each line, separated by three spaces.
238
+ - 阅读顺序是根据位置推测的。两栏的正文会按栏读,表格按行读;版面特别复杂的页面(比如多栏加图片的杂志页)可能不完全准确。
239
+ 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.
176
240
 
177
241
  ## 原则 / Principles
178
242
 
@@ -4,37 +4,85 @@
4
4
 
5
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
6
 
7
- > 状态:0.1 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
8
- > Status: 0.1, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
7
+ > 状态:0.2 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
8
+ > Status: 0.2, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
9
9
 
10
10
  ## 能做什么 / What it does
11
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.
12
16
  - 按阅读顺序提取文字,包括模板和复合对象里的文字。
13
17
  Text in reading order, including text in templates and composite objects.
14
- - 读取电子发票字段(数电票和增值税电子发票),输出 JSON:发票号码、开票日期、购买方、销售方、金额、税额、价税合计、明细。
15
- Invoice fields from e-invoices as JSON: number, date, buyer, seller, amounts, tax, total, line items.
16
- - 把一个文件夹里的发票汇总成 CSV,Excel 可以直接打开,并提示重复的发票号码。
17
- A folder of invoices summarised as CSV (opens in Excel), with duplicate invoice numbers flagged.
18
+ - 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。
19
+ For programs and AI: invoice fields as JSON, an MCP server, an Agent Skill and a MarkItDown plugin.
18
20
  - 只用 Python 标准库,没有任何第三方依赖;能读很多不规范的文件(路径写法不对、编码不对、XML 前缀错误等)。
19
21
  Standard library only, no dependencies; reads many non-conforming files (bad paths, encodings, XML prefixes).
20
22
 
21
- ## 安装 / Install
23
+ ## 快速上手 / Quick start
22
24
 
23
- 需要 Python 3.10 或更新版本。Requires Python 3.10+.
25
+ 1. 安装 [Python](https://www.python.org/downloads/) 3.10 或更新版本。Windows 上安装时请勾选 "Add python.exe to PATH"。
26
+ Install Python 3.10 or newer.
27
+ 2. 打开命令行(Windows 在开始菜单搜索"终端"或"cmd",Mac 打开"终端"),安装 ofdkit:
28
+ Open a terminal and install ofdkit:
24
29
 
25
- ```bash
26
- pip install ofdkit
27
- ```
30
+ ```bash
31
+ pip install ofdkit
32
+ ```
33
+
34
+ 3. 看一张发票(把文件拖进命令行窗口就能填上路径):
35
+ Show an invoice (drag the file into the terminal window to type its path):
36
+
37
+ ```bash
38
+ ofdkit 发票.ofd
39
+ ```
40
+
41
+ ```text
42
+ 电子发票(普通发票)
43
+
44
+ 发票号码 00000000000000000001
45
+ 开票日期 2026-01-02
46
+ 购买方 测试单位甲
47
+ 税号 TESTBUYER0001
48
+ 销售方 测试单位乙
49
+ 税号 TESTSELLER0002
50
+ 金额 100.00
51
+ 税额 6.00
52
+ 价税合计 106.00
53
+ 明细 *测试*服务项目 100.00 6%
54
+ 开票人 测试人员
55
+ ```
56
+
57
+ (数据是虚构的 / fictional data)
58
+
59
+ 4. 看一个文件夹或 .zip 压缩包里的所有发票和合计,然后导出到 Excel:
60
+ List every invoice in a folder or .zip archive with totals, then export to Excel:
61
+
62
+ ```bash
63
+ ofdkit 发票文件夹
64
+ ofdkit batch 发票文件夹 -o 发票汇总.xlsx
65
+ ```
66
+
67
+ Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红并写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行。
68
+ 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.
28
69
 
29
70
  ## 命令行 / Command line
30
71
 
31
72
  ```bash
73
+ ofdkit 文件.ofd # 看发票,不是发票就显示文字 / show an invoice, or the text
74
+ ofdkit 文件夹或压缩包.zip # 发票列表和合计 / list invoices with totals
75
+ ofdkit batch 文件夹 -o 发票汇总.xlsx # 导出 Excel / export to Excel
76
+ ofdkit batch 文件夹 -o 发票汇总.csv # 导出 CSV(给程序用)/ export CSV for programs
32
77
  ofdkit text 文件.ofd # 提取文字 / print text
33
78
  ofdkit invoice 发票.ofd # 发票字段(JSON)/ invoice fields as JSON
34
- ofdkit batch 发票文件夹/ -o 发票汇总.csv # 批量汇总 / summarise a folder as CSV
35
79
  ofdkit info 文件.ofd # 页数、作者等信息 / pages and metadata
80
+ ofdkit describe 文件.ofd -o 结构.json # 打码的结构,用于报告问题 / masked structure for bug reports
36
81
  ```
37
82
 
83
+ `batch` 和 `show` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
84
+ Add `-r` to `batch` and `show` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
85
+
38
86
  `ofdkit invoice` 的输出示例(数据是虚构的)/ Example output (fictional data):
39
87
 
40
88
  ```json
@@ -137,6 +185,22 @@ with ofdkit.open("发票.ofd") as doc:
137
185
  invoice = doc.invoice() # 不是发票时返回 None / None if not an invoice
138
186
  if invoice:
139
187
  print(invoice.invoice_number, invoice.total_amount)
188
+
189
+ # 文件夹、.zip 压缩包或多个文件 / folders, ZIP archives or several files
190
+ for result in ofdkit.read_invoices("发票文件夹", recursive=True):
191
+ if result.invoice:
192
+ print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "")
193
+ else:
194
+ print(result.file, result.error)
195
+ ```
196
+
197
+ ## 遇到读不出的文件 / Reporting a problem
198
+
199
+ 请不要把真实发票发到网上。用这个命令导出文件结构,文字会全部打码,只保留结构和位置,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里:
200
+ 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):
201
+
202
+ ```bash
203
+ ofdkit describe 文件.ofd -o 结构.json
140
204
  ```
141
205
 
142
206
  ## 注意 / Notes
@@ -145,8 +209,8 @@ with ofdkit.open("发票.ofd") as doc:
145
209
  ofdkit reports what a file contains. It does not verify that an invoice is genuine.
146
210
  - 文字如果是画成图形或图片的,就读不出来(需要 OCR,不在本项目范围内)。
147
211
  Text drawn as shapes or images cannot be extracted (that needs OCR, which is out of scope).
148
- - 多栏排版的页面,目前两栏的文字会出现在同一行,用三个空格隔开。
149
- On multi-column pages, both columns currently share each line, separated by three spaces.
212
+ - 阅读顺序是根据位置推测的。两栏的正文会按栏读,表格按行读;版面特别复杂的页面(比如多栏加图片的杂志页)可能不完全准确。
213
+ 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.
150
214
 
151
215
  ## 原则 / Principles
152
216
 
@@ -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.2.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")
@@ -0,0 +1,293 @@
1
+ """Many files at once: find OFD files, also inside ZIP archives, and read their invoices.
2
+
3
+ The tax authority's e-invoice service hands out many invoices as one ZIP archive, so an
4
+ archive counts as a folder: each ``.ofd`` file inside it becomes its own result, named
5
+ after the archive and its path inside it (``下载.zip/发票1.ofd``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import zipfile
12
+ import zlib
13
+ from collections import Counter
14
+ from collections.abc import Iterable, Sequence
15
+ from dataclasses import dataclass
16
+ from decimal import Decimal, InvalidOperation
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from .document import OFDDocument
21
+ from .errors import OFDError
22
+ from .invoice import Invoice
23
+ from .package import MAX_ENTRIES, _entry_name, _normalize
24
+
25
+ COLUMNS = [
26
+ "file",
27
+ "invoice_number",
28
+ "invoice_code",
29
+ "invoice_type",
30
+ "issue_date",
31
+ "buyer_name",
32
+ "buyer_tax_id",
33
+ "seller_name",
34
+ "seller_tax_id",
35
+ "amount_without_tax",
36
+ "tax_amount",
37
+ "total_amount",
38
+ "items",
39
+ "item_names",
40
+ "warnings",
41
+ "error",
42
+ ]
43
+
44
+ NO_INVOICE = "no invoice data"
45
+ DUPLICATE = "duplicate invoice number"
46
+ EMPTY_ARCHIVE = "no .ofd files in this ZIP archive"
47
+
48
+ #: Largest OFD file, uncompressed, that is read from inside a ZIP archive.
49
+ MAX_ARCHIVE_MEMBER_SIZE = 128 * 1024 * 1024
50
+
51
+
52
+ @dataclass
53
+ class InvoiceFile:
54
+ """One OFD file read by :func:`read_invoices`."""
55
+
56
+ #: The file's path. For a file inside a ZIP archive, the archive's path joined with
57
+ #: the file's path inside it.
58
+ file: str
59
+ #: The invoice, or None when the file could not be read or holds no invoice data.
60
+ invoice: Invoice | None = None
61
+ #: Why there is no invoice.
62
+ error: str | None = None
63
+ #: Another file has the same invoice number (and invoice code, for older invoices).
64
+ duplicate: bool = False
65
+
66
+
67
+ def read_invoices(paths: str | Path | Iterable[str | Path], recursive: bool = False) -> list[InvoiceFile]:
68
+ """Read every OFD file in ``paths``: files, folders and ZIP archives of OFD files.
69
+
70
+ Folders are searched for ``.ofd`` files and for ZIP archives that contain some;
71
+ ``recursive`` also searches their subfolders. Raises FileNotFoundError if a path
72
+ does not exist.
73
+ """
74
+ if isinstance(paths, (str, Path)):
75
+ paths = [paths]
76
+ files, missing = find_ofd_files(paths, recursive)
77
+ if missing:
78
+ raise FileNotFoundError(f"{missing[0]} does not exist")
79
+ return read_invoice_files(files)
80
+
81
+
82
+ def find_ofd_files(paths: Iterable[str | Path], recursive: bool = False) -> tuple[list[Path], list[str]]:
83
+ """Files to read in ``paths``, plus the paths that do not exist.
84
+
85
+ Files given directly are always kept. In folders, ``.ofd`` files are kept, and
86
+ ``.zip`` files that contain at least one ``.ofd`` file.
87
+ """
88
+ found: list[Path] = []
89
+ missing: list[str] = []
90
+ for raw in paths:
91
+ path = Path(raw)
92
+ if path.is_dir():
93
+ candidates = path.rglob("*") if recursive else path.glob("*")
94
+ for candidate in sorted(candidates):
95
+ if not candidate.is_file():
96
+ continue
97
+ suffix = candidate.suffix.lower()
98
+ if suffix == ".ofd" or (suffix == ".zip" and _archive_members(candidate)):
99
+ found.append(candidate)
100
+ elif path.exists():
101
+ found.append(path)
102
+ else:
103
+ missing.append(str(raw))
104
+ return found, missing
105
+
106
+
107
+ def read_invoice_files(files: Sequence[Path], limit: int | None = None) -> list[InvoiceFile]:
108
+ """Read the files found by :func:`find_ofd_files`, expanding ZIP archives.
109
+
110
+ With ``limit``, stop after that many OFD files.
111
+ """
112
+ results: list[InvoiceFile] = []
113
+ for path in files:
114
+ remaining = None if limit is None else limit - len(results)
115
+ if remaining is not None and remaining <= 0:
116
+ break
117
+ results.extend(_read_path(Path(path), remaining))
118
+ keys = Counter(key for key in map(_duplicate_key, results) if key)
119
+ for result in results:
120
+ key = _duplicate_key(result)
121
+ result.duplicate = bool(key) and keys[key] > 1
122
+ return results
123
+
124
+
125
+ def invoice_rows(files: Sequence[Path]) -> list[dict[str, Any]]:
126
+ """One row per OFD file, with the columns in :data:`COLUMNS`."""
127
+ return [invoice_row(result) for result in read_invoice_files(files)]
128
+
129
+
130
+ def invoice_row(result: InvoiceFile | Path) -> dict[str, Any]:
131
+ """A result as a flat row with the columns in :data:`COLUMNS`."""
132
+ if not isinstance(result, InvoiceFile): # a path, as in ofdkit 0.1
133
+ result = _read_one(str(result), result)
134
+ row: dict[str, Any] = dict.fromkeys(COLUMNS, "")
135
+ row["file"] = result.file
136
+ row["error"] = result.error or ""
137
+ invoice = result.invoice
138
+ if invoice is not None:
139
+ warnings = [*invoice.warnings, *([DUPLICATE] if result.duplicate else [])]
140
+ row.update(
141
+ {
142
+ "invoice_number": invoice.invoice_number or "",
143
+ "invoice_code": invoice.invoice_code or "",
144
+ "invoice_type": invoice.invoice_type or "",
145
+ "issue_date": invoice.issue_date or "",
146
+ "buyer_name": invoice.buyer.name or "",
147
+ "buyer_tax_id": invoice.buyer.tax_id or "",
148
+ "seller_name": invoice.seller.name or "",
149
+ "seller_tax_id": invoice.seller.tax_id or "",
150
+ "amount_without_tax": invoice.amount_without_tax or "",
151
+ "tax_amount": invoice.tax_amount or "",
152
+ "total_amount": invoice.total_amount or "",
153
+ "items": len(invoice.items),
154
+ "item_names": item_names(invoice),
155
+ "warnings": "; ".join(warnings),
156
+ }
157
+ )
158
+ return row
159
+
160
+
161
+ def item_names(invoice: Invoice, limit: int | None = None) -> str:
162
+ """Distinct names of the invoice's line items joined with ;, such as ``*餐饮服务*餐费``.
163
+
164
+ With ``limit``, at most that many names are shown, followed by 等 when there are more.
165
+ """
166
+ names = list(dict.fromkeys(item.name for item in invoice.items if item.name))
167
+ if limit is not None and len(names) > limit:
168
+ return ";".join(names[:limit]) + "等"
169
+ return ";".join(names)
170
+
171
+
172
+ _TOTALS_WARNING = re.compile(r"amount_without_tax \+ tax_amount != total_amount \((.*) \+ (.*) != (.*)\)")
173
+
174
+
175
+ def problems(result: InvoiceFile) -> list[str]:
176
+ """What is wrong with a result, in Chinese, for people reading a summary."""
177
+ if result.error == NO_INVOICE:
178
+ return ["不是发票(没有发票数据)"]
179
+ if result.error == EMPTY_ARCHIVE:
180
+ return ["压缩包里没有 OFD 文件"]
181
+ if result.error and result.error.startswith("not an OFD file"):
182
+ return [f"读不出来:不是 OFD 文件,或者文件已损坏({result.error})"]
183
+ if result.error:
184
+ return [f"读不出来:{result.error}"]
185
+ found = []
186
+ if result.duplicate:
187
+ found.append("发票号码重复")
188
+ for warning in result.invoice.warnings if result.invoice else []:
189
+ match = _TOTALS_WARNING.fullmatch(warning)
190
+ found.append(f"金额 + 税额 ≠ 价税合计({match[1]} + {match[2]} ≠ {match[3]})" if match else warning)
191
+ return found
192
+
193
+
194
+ def summary(results: Sequence[InvoiceFile | dict[str, Any]]) -> dict[str, Any]:
195
+ """Counts and sums over the results (or rows from :func:`invoice_rows`).
196
+
197
+ ``total_amount_sum`` adds every invoice; ``total_amount_sum_without_duplicates``
198
+ counts an invoice that appears in several files only once.
199
+ """
200
+ rows = [result if isinstance(result, dict) else invoice_row(result) for result in results]
201
+ invoices = [row for row in rows if not row["error"]]
202
+ seen: set[tuple[str, str]] = set()
203
+ unique: list[dict[str, Any]] = []
204
+ for row in invoices:
205
+ key = (row["invoice_code"], row["invoice_number"])
206
+ if row["invoice_number"] and key in seen:
207
+ continue
208
+ seen.add(key)
209
+ unique.append(row)
210
+
211
+ def total(column: str, selected: list[dict[str, Any]]) -> str:
212
+ return str(sum((_decimal(row[column]) for row in selected), Decimal(0)))
213
+
214
+ return {
215
+ "files": len(rows),
216
+ "invoices": len(invoices),
217
+ "without_invoice_data": sum(1 for row in rows if row["error"] == NO_INVOICE),
218
+ "errors": sum(1 for row in rows if row["error"] and row["error"] != NO_INVOICE),
219
+ "duplicates": len(invoices) - len(unique),
220
+ "amount_without_tax_sum": total("amount_without_tax", invoices),
221
+ "tax_amount_sum": total("tax_amount", invoices),
222
+ "total_amount_sum": total("total_amount", invoices),
223
+ "total_amount_sum_without_duplicates": total("total_amount", unique),
224
+ }
225
+
226
+
227
+ def _read_path(path: Path, limit: int | None = None) -> list[InvoiceFile]:
228
+ if path.suffix.lower() != ".zip":
229
+ return [_read_one(str(path), path)]
230
+ members = _archive_members(path)
231
+ if members is None: # not a readable archive, or an OFD file named .zip
232
+ return [_read_one(str(path), path)]
233
+ if not members:
234
+ return [InvoiceFile(str(path), error=EMPTY_ARCHIVE)]
235
+ results = []
236
+ try:
237
+ with zipfile.ZipFile(path) as archive:
238
+ for info in members[:limit]:
239
+ label = str(path / _normalize(_entry_name(info)))
240
+ if info.file_size > MAX_ARCHIVE_MEMBER_SIZE:
241
+ results.append(InvoiceFile(label, error=f"too large to read from the archive ({info.file_size} bytes)"))
242
+ continue
243
+ try:
244
+ data = archive.read(info)
245
+ except (zipfile.BadZipFile, zlib.error, RuntimeError, NotImplementedError, EOFError) as exc:
246
+ # RuntimeError: a password-protected entry.
247
+ results.append(InvoiceFile(label, error=f"cannot read from the archive: {exc}"))
248
+ continue
249
+ results.append(_read_one(label, data))
250
+ except (zipfile.BadZipFile, OSError) as exc:
251
+ return [*results, InvoiceFile(str(path), error=f"cannot read the archive: {exc}")]
252
+ return results
253
+
254
+
255
+ def _archive_members(path: Path) -> list[zipfile.ZipInfo] | None:
256
+ """The ``.ofd`` entries of a ZIP archive, or None if ``path`` is no archive of OFD files."""
257
+ try:
258
+ with zipfile.ZipFile(path) as archive:
259
+ infos = archive.infolist()
260
+ except (zipfile.BadZipFile, OSError, ValueError, EOFError):
261
+ return None
262
+ if len(infos) > MAX_ENTRIES:
263
+ return None
264
+ names = [(_normalize(_entry_name(info)), info) for info in infos if not info.is_dir()]
265
+ if any(name.casefold() == "ofd.xml" for name, _ in names): # an OFD file itself
266
+ return None
267
+ return [info for name, info in sorted(names, key=lambda pair: pair[0]) if name.lower().endswith(".ofd")]
268
+
269
+
270
+ def _read_one(label: str, source: Path | bytes) -> InvoiceFile:
271
+ try:
272
+ with OFDDocument(source) as document:
273
+ invoice = document.invoice()
274
+ except (OFDError, OSError) as exc:
275
+ return InvoiceFile(label, error=str(exc))
276
+ if invoice is None:
277
+ return InvoiceFile(label, error=NO_INVOICE)
278
+ return InvoiceFile(label, invoice=invoice)
279
+
280
+
281
+ def _duplicate_key(result: InvoiceFile) -> tuple[str, str] | None:
282
+ """Older invoices are unique only by code and number together; 数电票 have no code."""
283
+ invoice = result.invoice
284
+ if invoice is None or not invoice.invoice_number:
285
+ return None
286
+ return (invoice.invoice_code or "", invoice.invoice_number)
287
+
288
+
289
+ def _decimal(value: str) -> Decimal:
290
+ try:
291
+ return Decimal(value)
292
+ except (InvalidOperation, TypeError):
293
+ return Decimal(0)