ofdkit 0.3.1__tar.gz → 0.4.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.1 → ofdkit-0.4.0}/PKG-INFO +16 -13
- {ofdkit-0.3.1 → ofdkit-0.4.0}/README.md +15 -12
- {ofdkit-0.3.1 → ofdkit-0.4.0}/pyproject.toml +1 -1
- ofdkit-0.4.0/src/ofdkit/_guard.py +82 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/batch.py +70 -32
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/cli.py +12 -4
- ofdkit-0.4.0/src/ofdkit/describe.py +263 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/invoice.py +19 -7
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/mcp_server.py +44 -14
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/rename.py +115 -34
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/report.py +5 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/xlsx.py +22 -12
- ofdkit-0.3.1/src/ofdkit/describe.py +0 -153
- {ofdkit-0.3.1 → ofdkit-0.4.0}/LICENSE +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/__init__.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/__main__.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/_xml.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/document.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/errors.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/layout.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/markdown.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/markitdown_plugin.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/package.py +0 -0
- {ofdkit-0.3.1 → ofdkit-0.4.0}/src/ofdkit/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ofdkit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.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
|
|
@@ -32,8 +32,8 @@ 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.4 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
|
|
36
|
+
> Status: 0.4, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
|
|
37
37
|
|
|
38
38
|
## 能做什么 / What it does
|
|
39
39
|
|
|
@@ -94,8 +94,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
|
|
|
94
94
|
ofdkit batch 发票文件夹 -o 发票汇总.xlsx
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
-
Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"
|
|
98
|
-
The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red
|
|
97
|
+
Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红,有其他提醒的发票(抬头不对、金额缺少或不是数字)标橙,都在"提醒"一栏写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行;不是数字的金额保留原样、不算进合计,合计下面会注明有几张。
|
|
98
|
+
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
99
|
|
|
100
100
|
5. 检查发票抬头:加上 `--buyer`,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次:
|
|
101
101
|
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 +104,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
|
|
|
104
104
|
ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
|
|
105
105
|
```
|
|
106
106
|
|
|
107
|
-
6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML
|
|
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:
|
|
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 (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
109
|
|
|
110
110
|
```bash
|
|
111
111
|
ofdkit rename 发票文件夹 # 预览 / preview
|
|
@@ -161,8 +161,8 @@ Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is
|
|
|
161
161
|
}
|
|
162
162
|
```
|
|
163
163
|
|
|
164
|
-
金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计"
|
|
165
|
-
Amounts are decimal strings, so no precision is lost. `warnings` notes totals that do not add up.
|
|
164
|
+
金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",或者某个金额不是数字(比如"无法识别",这时保留原样),`warnings` 里会提示。汇总时只加真正的数字:0 就是 0,缺少的和不是数字的不算进合计,并单独计数(`not_summed`)。
|
|
165
|
+
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
166
|
|
|
167
167
|
## 在 AI 工具里使用 / Use from AI tools
|
|
168
168
|
|
|
@@ -171,6 +171,9 @@ Amounts are decimal strings, so no precision is lost. `warnings` notes totals th
|
|
|
171
171
|
让 Claude、Codex、Cursor 等 AI 工具直接读取 OFD 文件。需要先安装 [uv](https://docs.astral.sh/uv/)。所有工具都是只读的。
|
|
172
172
|
Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires [uv](https://docs.astral.sh/uv/). All tools are read-only.
|
|
173
173
|
|
|
174
|
+
已在[官方 MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.Edgar-311/ofdkit) 上架,名字是 `io.github.Edgar-311/ofdkit`;支持这个目录的工具可以直接搜索安装。
|
|
175
|
+
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.
|
|
176
|
+
|
|
174
177
|
| 工具 / Tool | 作用 / What it does |
|
|
175
178
|
| --- | --- |
|
|
176
179
|
| `read_ofd_text` | 按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range |
|
|
@@ -205,8 +208,8 @@ command = "uvx"
|
|
|
205
208
|
args = ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
|
|
206
209
|
```
|
|
207
210
|
|
|
208
|
-
加上 `--root 文件夹`
|
|
209
|
-
Add `--root FOLDER` to allow only files inside that folder.
|
|
211
|
+
加上 `--root 文件夹` 可以只允许读取这个文件夹里的文件。判断的是文件的真实位置:文件夹里指向外面的快捷方式式链接(符号链接、Windows 的目录联接)不会被读取,汇总文件夹时会跳过并计数(`skipped_outside_root`)。
|
|
212
|
+
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
213
|
|
|
211
214
|
### Agent Skill
|
|
212
215
|
|
|
@@ -247,8 +250,8 @@ for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["
|
|
|
247
250
|
|
|
248
251
|
## 遇到读不出的文件 / Reporting a problem
|
|
249
252
|
|
|
250
|
-
|
|
251
|
-
Please do not post real invoices. Export the structure
|
|
253
|
+
请不要把真实发票发到网上。用这个命令导出文件结构,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里。文字、文件名和较长的号码会打码(汉字变成"字",数字变成"0",字母变成 x),只保留结构、坐标和 OFD 格式自己的名字(如 `Doc_0`、`Content.xml`)。打码是尽力而为,发出去之前请自己再看一遍:
|
|
254
|
+
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
255
|
|
|
253
256
|
```bash
|
|
254
257
|
ofdkit describe 文件.ofd -o 结构.json
|
|
@@ -6,8 +6,8 @@
|
|
|
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.4 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
|
|
10
|
+
> Status: 0.4, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
|
|
11
11
|
|
|
12
12
|
## 能做什么 / What it does
|
|
13
13
|
|
|
@@ -68,8 +68,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
|
|
|
68
68
|
ofdkit batch 发票文件夹 -o 发票汇总.xlsx
|
|
69
69
|
```
|
|
70
70
|
|
|
71
|
-
Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"
|
|
72
|
-
The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red
|
|
71
|
+
Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红,有其他提醒的发票(抬头不对、金额缺少或不是数字)标橙,都在"提醒"一栏写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行;不是数字的金额保留原样、不算进合计,合计下面会注明有几张。
|
|
72
|
+
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
73
|
|
|
74
74
|
5. 检查发票抬头:加上 `--buyer`,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次:
|
|
75
75
|
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 +78,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
|
|
|
78
78
|
ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
-
6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML
|
|
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:
|
|
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 (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
83
|
|
|
84
84
|
```bash
|
|
85
85
|
ofdkit rename 发票文件夹 # 预览 / preview
|
|
@@ -135,8 +135,8 @@ Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is
|
|
|
135
135
|
}
|
|
136
136
|
```
|
|
137
137
|
|
|
138
|
-
金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计"
|
|
139
|
-
Amounts are decimal strings, so no precision is lost. `warnings` notes totals that do not add up.
|
|
138
|
+
金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",或者某个金额不是数字(比如"无法识别",这时保留原样),`warnings` 里会提示。汇总时只加真正的数字:0 就是 0,缺少的和不是数字的不算进合计,并单独计数(`not_summed`)。
|
|
139
|
+
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
140
|
|
|
141
141
|
## 在 AI 工具里使用 / Use from AI tools
|
|
142
142
|
|
|
@@ -145,6 +145,9 @@ Amounts are decimal strings, so no precision is lost. `warnings` notes totals th
|
|
|
145
145
|
让 Claude、Codex、Cursor 等 AI 工具直接读取 OFD 文件。需要先安装 [uv](https://docs.astral.sh/uv/)。所有工具都是只读的。
|
|
146
146
|
Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires [uv](https://docs.astral.sh/uv/). All tools are read-only.
|
|
147
147
|
|
|
148
|
+
已在[官方 MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.Edgar-311/ofdkit) 上架,名字是 `io.github.Edgar-311/ofdkit`;支持这个目录的工具可以直接搜索安装。
|
|
149
|
+
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.
|
|
150
|
+
|
|
148
151
|
| 工具 / Tool | 作用 / What it does |
|
|
149
152
|
| --- | --- |
|
|
150
153
|
| `read_ofd_text` | 按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range |
|
|
@@ -179,8 +182,8 @@ command = "uvx"
|
|
|
179
182
|
args = ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
|
|
180
183
|
```
|
|
181
184
|
|
|
182
|
-
加上 `--root 文件夹`
|
|
183
|
-
Add `--root FOLDER` to allow only files inside that folder.
|
|
185
|
+
加上 `--root 文件夹` 可以只允许读取这个文件夹里的文件。判断的是文件的真实位置:文件夹里指向外面的快捷方式式链接(符号链接、Windows 的目录联接)不会被读取,汇总文件夹时会跳过并计数(`skipped_outside_root`)。
|
|
186
|
+
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
187
|
|
|
185
188
|
### Agent Skill
|
|
186
189
|
|
|
@@ -221,8 +224,8 @@ for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["
|
|
|
221
224
|
|
|
222
225
|
## 遇到读不出的文件 / Reporting a problem
|
|
223
226
|
|
|
224
|
-
|
|
225
|
-
Please do not post real invoices. Export the structure
|
|
227
|
+
请不要把真实发票发到网上。用这个命令导出文件结构,然后附在 [GitHub issue](https://github.com/Edgar-311/ofdkit/issues/new/choose) 里。文字、文件名和较长的号码会打码(汉字变成"字",数字变成"0",字母变成 x),只保留结构、坐标和 OFD 格式自己的名字(如 `Doc_0`、`Content.xml`)。打码是尽力而为,发出去之前请自己再看一遍:
|
|
228
|
+
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
229
|
|
|
227
230
|
```bash
|
|
228
231
|
ofdkit describe 文件.ofd -o 结构.json
|
|
@@ -4,7 +4,7 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "ofdkit"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.4.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"
|
|
@@ -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
|
|
@@ -13,13 +13,14 @@ import zlib
|
|
|
13
13
|
from collections import Counter
|
|
14
14
|
from collections.abc import Iterable, Sequence
|
|
15
15
|
from dataclasses import dataclass, field
|
|
16
|
-
from decimal import Decimal
|
|
16
|
+
from decimal import Decimal
|
|
17
17
|
from pathlib import Path
|
|
18
|
-
from typing import Any
|
|
18
|
+
from typing import Any, BinaryIO
|
|
19
19
|
|
|
20
|
+
from ._guard import PathGuard
|
|
20
21
|
from .document import OFDDocument
|
|
21
22
|
from .errors import OFDError
|
|
22
|
-
from .invoice import Invoice
|
|
23
|
+
from .invoice import AMOUNT_FIELDS, NOT_A_NUMBER, Invoice, parse_amount
|
|
23
24
|
from .package import MAX_ENTRIES, _entry_name, _normalize
|
|
24
25
|
|
|
25
26
|
COLUMNS = [
|
|
@@ -87,23 +88,30 @@ def read_invoices(
|
|
|
87
88
|
return results
|
|
88
89
|
|
|
89
90
|
|
|
90
|
-
def find_ofd_files(
|
|
91
|
+
def find_ofd_files(
|
|
92
|
+
paths: Iterable[str | Path], recursive: bool = False, guard: PathGuard | None = None
|
|
93
|
+
) -> tuple[list[Path], list[str]]:
|
|
91
94
|
"""Files to read in ``paths``, plus the paths that do not exist.
|
|
92
95
|
|
|
93
96
|
Files given directly are always kept. In folders, ``.ofd`` files are kept, and
|
|
94
|
-
``.zip`` files that contain at least one ``.ofd`` file.
|
|
97
|
+
``.zip`` files that contain at least one ``.ofd`` file. With ``guard``, anything whose
|
|
98
|
+
real location is outside the guard's folder is left out (and noted in
|
|
99
|
+
``guard.refused``), and links to folders outside it are not followed.
|
|
95
100
|
"""
|
|
96
101
|
found: list[Path] = []
|
|
97
102
|
missing: list[str] = []
|
|
98
103
|
for raw in paths:
|
|
99
104
|
path = Path(raw)
|
|
100
|
-
if path.
|
|
101
|
-
|
|
105
|
+
if guard is not None and path.exists() and not guard.inside(path):
|
|
106
|
+
guard.refused.append(str(path))
|
|
107
|
+
elif path.is_dir():
|
|
108
|
+
if guard is not None:
|
|
109
|
+
candidates = list(guard.walk(path, recursive))
|
|
110
|
+
else:
|
|
111
|
+
candidates = [p for p in (path.rglob("*") if recursive else path.glob("*")) if p.is_file()]
|
|
102
112
|
for candidate in sorted(candidates):
|
|
103
|
-
if not candidate.is_file():
|
|
104
|
-
continue
|
|
105
113
|
suffix = candidate.suffix.lower()
|
|
106
|
-
if suffix == ".ofd" or (suffix == ".zip" and _archive_members(candidate)):
|
|
114
|
+
if suffix == ".ofd" or (suffix == ".zip" and _archive_members(candidate, guard)):
|
|
107
115
|
found.append(candidate)
|
|
108
116
|
elif path.exists():
|
|
109
117
|
found.append(path)
|
|
@@ -112,17 +120,21 @@ def find_ofd_files(paths: Iterable[str | Path], recursive: bool = False) -> tupl
|
|
|
112
120
|
return found, missing
|
|
113
121
|
|
|
114
122
|
|
|
115
|
-
def read_invoice_files(
|
|
123
|
+
def read_invoice_files(
|
|
124
|
+
files: Sequence[Path], limit: int | None = None, guard: PathGuard | None = None
|
|
125
|
+
) -> list[InvoiceFile]:
|
|
116
126
|
"""Read the files found by :func:`find_ofd_files`, expanding ZIP archives.
|
|
117
127
|
|
|
118
|
-
With ``limit``, stop after that many OFD files.
|
|
128
|
+
With ``limit``, stop after that many OFD files. With ``guard``, every file is opened
|
|
129
|
+
through it, so one that leads outside its folder is refused even if it changed after
|
|
130
|
+
it was found.
|
|
119
131
|
"""
|
|
120
132
|
results: list[InvoiceFile] = []
|
|
121
133
|
for path in files:
|
|
122
134
|
remaining = None if limit is None else limit - len(results)
|
|
123
135
|
if remaining is not None and remaining <= 0:
|
|
124
136
|
break
|
|
125
|
-
results.extend(_read_path(Path(path), remaining))
|
|
137
|
+
results.extend(_read_path(Path(path), remaining, guard))
|
|
126
138
|
keys = Counter(key for key in map(_duplicate_key, results) if key)
|
|
127
139
|
for result in results:
|
|
128
140
|
key = _duplicate_key(result)
|
|
@@ -222,6 +234,9 @@ def _normal_name(value: str) -> str:
|
|
|
222
234
|
return re.sub(r"\s+", "", value).replace("(", "(").replace(")", ")").casefold()
|
|
223
235
|
|
|
224
236
|
|
|
237
|
+
#: Chinese names of the invoice-level amounts, for people.
|
|
238
|
+
AMOUNT_LABELS = {"amount_without_tax": "金额", "tax_amount": "税额", "total_amount": "价税合计"}
|
|
239
|
+
|
|
225
240
|
_TOTALS_WARNING = re.compile(r"amount_without_tax \+ tax_amount != total_amount \((.*) \+ (.*) != (.*)\)")
|
|
226
241
|
|
|
227
242
|
|
|
@@ -244,7 +259,15 @@ def problems(result: InvoiceFile) -> list[str]:
|
|
|
244
259
|
actual = (invoice.buyer.tax_id if tax_id else invoice.buyer.name) if invoice else None
|
|
245
260
|
label = "购买方税号" if tax_id else "购买方"
|
|
246
261
|
found.append(f"{label}不是 {expected}(发票上是 {actual or '空的'})")
|
|
262
|
+
for attribute in AMOUNT_FIELDS if invoice else []:
|
|
263
|
+
value = getattr(invoice, attribute)
|
|
264
|
+
if value is None:
|
|
265
|
+
found.append(f"缺少{AMOUNT_LABELS[attribute]}")
|
|
266
|
+
elif parse_amount(value) is None:
|
|
267
|
+
found.append(f"{AMOUNT_LABELS[attribute]}不是数字(“{value}”)")
|
|
247
268
|
for warning in invoice.warnings if invoice else []:
|
|
269
|
+
if f" {NOT_A_NUMBER}: " in warning:
|
|
270
|
+
continue # said above, in Chinese
|
|
248
271
|
match = _TOTALS_WARNING.fullmatch(warning)
|
|
249
272
|
found.append(f"金额 + 税额 ≠ 价税合计({match[1]} + {match[2]} ≠ {match[3]})" if match else warning)
|
|
250
273
|
return found
|
|
@@ -254,7 +277,10 @@ def summary(results: Sequence[InvoiceFile | dict[str, Any]]) -> dict[str, Any]:
|
|
|
254
277
|
"""Counts and sums over the results (or rows from :func:`invoice_rows`).
|
|
255
278
|
|
|
256
279
|
``total_amount_sum`` adds every invoice; ``total_amount_sum_without_duplicates``
|
|
257
|
-
counts an invoice that appears in several files only once.
|
|
280
|
+
counts an invoice that appears in several files only once. Sums include only
|
|
281
|
+
amounts that are numbers: ``not_summed`` counts, for each amount, the invoices where
|
|
282
|
+
it is missing and where it is present but not a number (such as "无法识别"), so a
|
|
283
|
+
sum is complete only when both counts are 0.
|
|
258
284
|
"""
|
|
259
285
|
rows = [result if isinstance(result, dict) else invoice_row(result) for result in results]
|
|
260
286
|
invoices = [row for row in rows if not row["error"]]
|
|
@@ -268,7 +294,16 @@ def summary(results: Sequence[InvoiceFile | dict[str, Any]]) -> dict[str, Any]:
|
|
|
268
294
|
unique.append(row)
|
|
269
295
|
|
|
270
296
|
def total(column: str, selected: list[dict[str, Any]]) -> str:
|
|
271
|
-
|
|
297
|
+
values = (parse_amount(str(row[column])) for row in selected if row[column] != "")
|
|
298
|
+
return str(sum((value for value in values if value is not None), Decimal(0)))
|
|
299
|
+
|
|
300
|
+
not_summed = {
|
|
301
|
+
column: {
|
|
302
|
+
"missing": sum(1 for row in invoices if row[column] == ""),
|
|
303
|
+
"invalid": sum(1 for row in invoices if row[column] != "" and parse_amount(str(row[column])) is None),
|
|
304
|
+
}
|
|
305
|
+
for column in AMOUNT_FIELDS
|
|
306
|
+
}
|
|
272
307
|
|
|
273
308
|
return {
|
|
274
309
|
"files": len(rows),
|
|
@@ -281,20 +316,21 @@ def summary(results: Sequence[InvoiceFile | dict[str, Any]]) -> dict[str, Any]:
|
|
|
281
316
|
"tax_amount_sum": total("tax_amount", invoices),
|
|
282
317
|
"total_amount_sum": total("total_amount", invoices),
|
|
283
318
|
"total_amount_sum_without_duplicates": total("total_amount", unique),
|
|
319
|
+
"not_summed": not_summed,
|
|
284
320
|
}
|
|
285
321
|
|
|
286
322
|
|
|
287
|
-
def _read_path(path: Path, limit: int | None = None) -> list[InvoiceFile]:
|
|
323
|
+
def _read_path(path: Path, limit: int | None = None, guard: PathGuard | None = None) -> list[InvoiceFile]:
|
|
288
324
|
if path.suffix.lower() != ".zip":
|
|
289
|
-
return [_read_one(str(path), path)]
|
|
290
|
-
members = _archive_members(path)
|
|
325
|
+
return [_read_one(str(path), path, guard)]
|
|
326
|
+
members = _archive_members(path, guard)
|
|
291
327
|
if members is None: # not a readable archive, or an OFD file named .zip
|
|
292
|
-
return [_read_one(str(path), path)]
|
|
328
|
+
return [_read_one(str(path), path, guard)]
|
|
293
329
|
if not members:
|
|
294
330
|
return [InvoiceFile(str(path), error=EMPTY_ARCHIVE)]
|
|
295
331
|
results = []
|
|
296
332
|
try:
|
|
297
|
-
with zipfile.ZipFile(
|
|
333
|
+
with _open(path, guard) as stream, zipfile.ZipFile(stream) as archive:
|
|
298
334
|
for info in members[:limit]:
|
|
299
335
|
label = str(path / _normalize(_entry_name(info)))
|
|
300
336
|
if info.file_size > MAX_ARCHIVE_MEMBER_SIZE:
|
|
@@ -312,10 +348,10 @@ def _read_path(path: Path, limit: int | None = None) -> list[InvoiceFile]:
|
|
|
312
348
|
return results
|
|
313
349
|
|
|
314
350
|
|
|
315
|
-
def _archive_members(path: Path) -> list[zipfile.ZipInfo] | None:
|
|
351
|
+
def _archive_members(path: Path, guard: PathGuard | None = None) -> list[zipfile.ZipInfo] | None:
|
|
316
352
|
"""The ``.ofd`` entries of a ZIP archive, or None if ``path`` is no archive of OFD files."""
|
|
317
353
|
try:
|
|
318
|
-
with zipfile.ZipFile(
|
|
354
|
+
with _open(path, guard) as stream, zipfile.ZipFile(stream) as archive:
|
|
319
355
|
infos = archive.infolist()
|
|
320
356
|
except (zipfile.BadZipFile, OSError, ValueError, EOFError):
|
|
321
357
|
return None
|
|
@@ -327,10 +363,14 @@ def _archive_members(path: Path) -> list[zipfile.ZipInfo] | None:
|
|
|
327
363
|
return [info for name, info in sorted(names, key=lambda pair: pair[0]) if name.lower().endswith(".ofd")]
|
|
328
364
|
|
|
329
365
|
|
|
330
|
-
def _read_one(label: str, source: Path | bytes) -> InvoiceFile:
|
|
366
|
+
def _read_one(label: str, source: Path | bytes, guard: PathGuard | None = None) -> InvoiceFile:
|
|
331
367
|
try:
|
|
332
|
-
|
|
333
|
-
|
|
368
|
+
if isinstance(source, Path):
|
|
369
|
+
with _open(source, guard) as stream, OFDDocument(stream) as document:
|
|
370
|
+
invoice = document.invoice()
|
|
371
|
+
else:
|
|
372
|
+
with OFDDocument(source) as document:
|
|
373
|
+
invoice = document.invoice()
|
|
334
374
|
except (OFDError, OSError) as exc:
|
|
335
375
|
return InvoiceFile(label, error=str(exc))
|
|
336
376
|
if invoice is None:
|
|
@@ -338,16 +378,14 @@ def _read_one(label: str, source: Path | bytes) -> InvoiceFile:
|
|
|
338
378
|
return InvoiceFile(label, invoice=invoice)
|
|
339
379
|
|
|
340
380
|
|
|
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
|
+
|
|
341
386
|
def _duplicate_key(result: InvoiceFile) -> tuple[str, str] | None:
|
|
342
387
|
"""Older invoices are unique only by code and number together; 数电票 have no code."""
|
|
343
388
|
invoice = result.invoice
|
|
344
389
|
if invoice is None or not invoice.invoice_number:
|
|
345
390
|
return None
|
|
346
391
|
return (invoice.invoice_code or "", invoice.invoice_number)
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
def _decimal(value: str) -> Decimal:
|
|
350
|
-
try:
|
|
351
|
-
return Decimal(value)
|
|
352
|
-
except (InvalidOperation, TypeError):
|
|
353
|
-
return Decimal(0)
|
|
@@ -107,7 +107,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
107
107
|
rename.add_argument("--only-ofd", action="store_true", help="只改 .ofd 文件;不加的话,同名的 PDF、XML 等也一起改")
|
|
108
108
|
rename.add_argument("--undo", metavar="改名记录", help="按改名记录把文件名改回去")
|
|
109
109
|
|
|
110
|
-
describe = commands.add_parser("describe", help="
|
|
110
|
+
describe = commands.add_parser("describe", help="导出文件结构(文字、文件名和号码打码),用于报告问题")
|
|
111
111
|
describe.add_argument("file", metavar="文件", help="OFD 文件")
|
|
112
112
|
describe.add_argument("-o", "--output", metavar="输出文件", help="保存到这个文件(UTF-8),不显示在屏幕上")
|
|
113
113
|
|
|
@@ -291,7 +291,7 @@ def _batch(args: argparse.Namespace) -> int:
|
|
|
291
291
|
|
|
292
292
|
|
|
293
293
|
def _rename(args: argparse.Namespace) -> int:
|
|
294
|
-
from .rename import apply, plan, undo
|
|
294
|
+
from .rename import LogError, apply, plan, undo
|
|
295
295
|
|
|
296
296
|
if args.undo:
|
|
297
297
|
if args.paths:
|
|
@@ -305,6 +305,8 @@ def _rename(args: argparse.Namespace) -> int:
|
|
|
305
305
|
for old, new in outcome.done:
|
|
306
306
|
print(f"{old.name}\n → {new.name}")
|
|
307
307
|
print(f"\n已改回 {len(outcome.done)} 个文件。")
|
|
308
|
+
if outcome.unchanged:
|
|
309
|
+
print(f"另有 {len(outcome.unchanged)} 个文件本来就是原来的名字,不用改。")
|
|
308
310
|
for old, new, reason in outcome.failed:
|
|
309
311
|
_say(f"没能把 {old} 改回 {new.name}:{reason}")
|
|
310
312
|
return EXIT_ERROR if outcome.failed else EXIT_OK
|
|
@@ -352,10 +354,16 @@ def _rename(args: argparse.Namespace) -> int:
|
|
|
352
354
|
print(f"确认没问题的话,加上 --apply 再运行一次:\n{command}")
|
|
353
355
|
return EXIT_OK
|
|
354
356
|
|
|
355
|
-
|
|
357
|
+
try:
|
|
358
|
+
outcome = apply(planned)
|
|
359
|
+
except LogError as exc:
|
|
360
|
+
_say(f"错误:{exc}。为了能改回去,必须先写好改名记录,所以这次没有改任何文件。")
|
|
361
|
+
return EXIT_ERROR
|
|
356
362
|
print(f"\n已改名 {len(outcome.done)} 个文件。")
|
|
357
363
|
for old, new, reason in outcome.failed:
|
|
358
364
|
_say(f"没能把 {old} 改成 {new.name}:{reason}")
|
|
365
|
+
for old, new in outcome.rolled_back:
|
|
366
|
+
_say(f"同一张发票的另一个文件没改成功,所以 {old.name} 保留了原来的名字")
|
|
359
367
|
if outcome.log is not None:
|
|
360
368
|
print(f"改名记录保存在 {outcome.log}\n要改回原来的名字,运行:ofdkit rename --undo {_quote(str(outcome.log))}")
|
|
361
369
|
return EXIT_ERROR if outcome.failed else EXIT_OK
|
|
@@ -367,7 +375,7 @@ def _describe(args: argparse.Namespace) -> int:
|
|
|
367
375
|
text = json.dumps(describe(args.file), ensure_ascii=False, indent=1)
|
|
368
376
|
if args.output:
|
|
369
377
|
Path(args.output).write_text(text + "\n", encoding="utf-8")
|
|
370
|
-
_say(f"已保存到 {args.output}
|
|
378
|
+
_say(f"已保存到 {args.output}。文字、文件名和号码已经打码,但打码不能保证万无一失,分享之前请再检查一遍。")
|
|
371
379
|
else:
|
|
372
380
|
print(text)
|
|
373
381
|
return EXIT_OK
|