trimitdown 0.3.0__tar.gz → 0.3.2__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.
- {trimitdown-0.3.0/src/trimitdown.egg-info → trimitdown-0.3.2}/PKG-INFO +66 -3
- {trimitdown-0.3.0 → trimitdown-0.3.2}/README.md +62 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/pyproject.toml +8 -2
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/__init__.py +1 -1
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/cli.py +39 -3
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/convert.py +147 -13
- trimitdown-0.3.2/src/trimitdown/office_inspect.py +868 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2/src/trimitdown.egg-info}/PKG-INFO +66 -3
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown.egg-info/SOURCES.txt +1 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown.egg-info/requires.txt +3 -2
- {trimitdown-0.3.0 → trimitdown-0.3.2}/LICENSE +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/MANIFEST.in +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/setup.cfg +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/__main__.py +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/pdf_route.py +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/review.py +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/review_rule.md +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/text_metrics.py +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/tiktoken_cache/9b5ad71b2ce5302211f9c61530b329a4922fc6a4 +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown/tiktoken_cache/README.md +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown.egg-info/dependency_links.txt +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown.egg-info/entry_points.txt +0 -0
- {trimitdown-0.3.0 → trimitdown-0.3.2}/src/trimitdown.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: trimitdown
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Convert documents to LLM-ready markdown. Per-page checked PDF extraction with a review hand-off for scans, offline, no cloud.
|
|
5
5
|
Author: Sergey Dreizin
|
|
6
6
|
License-Expression: MIT
|
|
@@ -22,15 +22,16 @@ Classifier: Topic :: Utilities
|
|
|
22
22
|
Requires-Python: >=3.10
|
|
23
23
|
Description-Content-Type: text/markdown
|
|
24
24
|
License-File: LICENSE
|
|
25
|
-
Requires-Dist: pdf-inspector==1.
|
|
25
|
+
Requires-Dist: pdf-inspector==1.27.2
|
|
26
26
|
Requires-Dist: pypdf[crypto]<7,>=6.1
|
|
27
27
|
Requires-Dist: pypdfium2<6,>=5
|
|
28
28
|
Requires-Dist: pillow>=10
|
|
29
29
|
Requires-Dist: tiktoken
|
|
30
30
|
Requires-Dist: python-pptx
|
|
31
31
|
Provides-Extra: office
|
|
32
|
-
Requires-Dist: firecrawl-anydoc==0.2.
|
|
32
|
+
Requires-Dist: firecrawl-anydoc==0.2.5; extra == "office"
|
|
33
33
|
Requires-Dist: markdownify>=1.2; extra == "office"
|
|
34
|
+
Requires-Dist: olefile>=0.46; extra == "office"
|
|
34
35
|
Provides-Extra: server
|
|
35
36
|
Requires-Dist: fastapi; extra == "server"
|
|
36
37
|
Requires-Dist: uvicorn; extra == "server"
|
|
@@ -114,6 +115,68 @@ through unchanged, as UTF-8. Outlook `.msg`, JSON, XML, ZIP, images and audio ar
|
|
|
114
115
|
Documents are never sent anywhere: scanned pages in an office file are refused, not OCR-ed in a
|
|
115
116
|
cloud.
|
|
116
117
|
|
|
118
|
+
## Word and RTF: tracked changes and what the text leaves out
|
|
119
|
+
|
|
120
|
+
A converter that drops a struck-out wording, or prints it next to the new one, makes a document
|
|
121
|
+
read the wrong way. Before anydoc reads a DOCX, DOC or RTF, trimitdown looks at the file itself
|
|
122
|
+
and counts what Markdown cannot carry.
|
|
123
|
+
|
|
124
|
+
- **Unresolved tracked changes are refused** (non-zero exit, `ConversionError` in Python), and the
|
|
125
|
+
message names the counts: `1 insertion, 1 deletion`. Accept or reject the changes in Word and
|
|
126
|
+
save the file again, or convert with every change accepted:
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
trimitdown convert contract.docx --accept-changes -o contract.md
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
convert_path("contract.docx", accept_changes=True)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
The flag works for **DOCX only**, because only there is anydoc's output the accepted reading
|
|
137
|
+
(checked on files made in Word). A **DOC or RTF** with tracked changes is refused even with the
|
|
138
|
+
flag: it would print the deleted wording as if it were in force. Save it as DOCX in Word and
|
|
139
|
+
convert that. Even for a DOCX the flag declines the few constructs where anydoc's text is not
|
|
140
|
+
what Word's "accept all" gives (a deleted table row or cell, a deleted list item, a deleted
|
|
141
|
+
paragraph break that joins two paragraphs); the message names which. Formatting-only changes
|
|
142
|
+
(bold, alignment) are not tracked changes here: they leave every character as it was.
|
|
143
|
+
- **What the Markdown leaves out is said, not hidden.** When a document has header or footer
|
|
144
|
+
parts with text, comments or images, the output starts with one line, listing only the non-zero
|
|
145
|
+
parts, and the same words go to stderr:
|
|
146
|
+
|
|
147
|
+
```
|
|
148
|
+
<!-- trimitdown: accepted 1 insertion, 1 deletion; omitted 2 header/footer parts, 1 comment, 1 image -->
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Nothing is written when there is nothing to say. A header or footer part counts when it holds
|
|
152
|
+
printable text (a page number is text); the empty first-page and even-page headers Word writes
|
|
153
|
+
into every file do not. RTF repeats headers for every section, so a many-section RTF counts more
|
|
154
|
+
parts than the same document as DOCX. Footnotes and endnotes are carried and are not
|
|
155
|
+
"omitted". Images inside headers, footers and comments go with them.
|
|
156
|
+
- **`--report PATH`** writes a JSON report for a program that wants the same facts (only when the
|
|
157
|
+
conversion succeeded; a refusal writes nothing):
|
|
158
|
+
|
|
159
|
+
```json
|
|
160
|
+
{
|
|
161
|
+
"schema": 1,
|
|
162
|
+
"format": "docx",
|
|
163
|
+
"tracked_changes": {"present": true, "insertions": 1, "deletions": 1, "accepted": true},
|
|
164
|
+
"omitted": {"headers_footers": 2, "comments": 1, "images": 1}
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`format` is the format found in the file's content (`docx`, `doc`, `rtf`, `pdf`, `html`, `txt`,
|
|
169
|
+
`xlsx`, ...). `tracked_changes` and `omitted` appear for DOCX, DOC and RTF only; `accepted` is
|
|
170
|
+
true when `--accept-changes` was given and there were changes to accept. For a PDF the report
|
|
171
|
+
has `format` and `pages`, the per-route counts the command already prints
|
|
172
|
+
(`{"total": 7, "accept": 5, "substitute": 1, "scan": 1, "corrupt": 0, "blank": 0}`); the
|
|
173
|
+
Python result carries the same dictionary as `result.report`. Counts of insertions and
|
|
174
|
+
deletions are runs of changes, as Word counts revisions: text typed together with its paragraph
|
|
175
|
+
break is one insertion.
|
|
176
|
+
- **ODT is refused** until anydoc reads it correctly: measured on a document saved from Word,
|
|
177
|
+
second-level numbering does not restart (`2.1.` became `2.3.`) and a comment is pasted into the
|
|
178
|
+
middle of a word. Save the document as DOCX. ODS and ODP are converted as before.
|
|
179
|
+
|
|
117
180
|
## How PDFs are handled
|
|
118
181
|
|
|
119
182
|
PDFs go through [pdf-inspector](https://pypi.org/project/pdf-inspector/), which gave the best
|
|
@@ -75,6 +75,68 @@ through unchanged, as UTF-8. Outlook `.msg`, JSON, XML, ZIP, images and audio ar
|
|
|
75
75
|
Documents are never sent anywhere: scanned pages in an office file are refused, not OCR-ed in a
|
|
76
76
|
cloud.
|
|
77
77
|
|
|
78
|
+
## Word and RTF: tracked changes and what the text leaves out
|
|
79
|
+
|
|
80
|
+
A converter that drops a struck-out wording, or prints it next to the new one, makes a document
|
|
81
|
+
read the wrong way. Before anydoc reads a DOCX, DOC or RTF, trimitdown looks at the file itself
|
|
82
|
+
and counts what Markdown cannot carry.
|
|
83
|
+
|
|
84
|
+
- **Unresolved tracked changes are refused** (non-zero exit, `ConversionError` in Python), and the
|
|
85
|
+
message names the counts: `1 insertion, 1 deletion`. Accept or reject the changes in Word and
|
|
86
|
+
save the file again, or convert with every change accepted:
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
trimitdown convert contract.docx --accept-changes -o contract.md
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
convert_path("contract.docx", accept_changes=True)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The flag works for **DOCX only**, because only there is anydoc's output the accepted reading
|
|
97
|
+
(checked on files made in Word). A **DOC or RTF** with tracked changes is refused even with the
|
|
98
|
+
flag: it would print the deleted wording as if it were in force. Save it as DOCX in Word and
|
|
99
|
+
convert that. Even for a DOCX the flag declines the few constructs where anydoc's text is not
|
|
100
|
+
what Word's "accept all" gives (a deleted table row or cell, a deleted list item, a deleted
|
|
101
|
+
paragraph break that joins two paragraphs); the message names which. Formatting-only changes
|
|
102
|
+
(bold, alignment) are not tracked changes here: they leave every character as it was.
|
|
103
|
+
- **What the Markdown leaves out is said, not hidden.** When a document has header or footer
|
|
104
|
+
parts with text, comments or images, the output starts with one line, listing only the non-zero
|
|
105
|
+
parts, and the same words go to stderr:
|
|
106
|
+
|
|
107
|
+
```
|
|
108
|
+
<!-- trimitdown: accepted 1 insertion, 1 deletion; omitted 2 header/footer parts, 1 comment, 1 image -->
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Nothing is written when there is nothing to say. A header or footer part counts when it holds
|
|
112
|
+
printable text (a page number is text); the empty first-page and even-page headers Word writes
|
|
113
|
+
into every file do not. RTF repeats headers for every section, so a many-section RTF counts more
|
|
114
|
+
parts than the same document as DOCX. Footnotes and endnotes are carried and are not
|
|
115
|
+
"omitted". Images inside headers, footers and comments go with them.
|
|
116
|
+
- **`--report PATH`** writes a JSON report for a program that wants the same facts (only when the
|
|
117
|
+
conversion succeeded; a refusal writes nothing):
|
|
118
|
+
|
|
119
|
+
```json
|
|
120
|
+
{
|
|
121
|
+
"schema": 1,
|
|
122
|
+
"format": "docx",
|
|
123
|
+
"tracked_changes": {"present": true, "insertions": 1, "deletions": 1, "accepted": true},
|
|
124
|
+
"omitted": {"headers_footers": 2, "comments": 1, "images": 1}
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`format` is the format found in the file's content (`docx`, `doc`, `rtf`, `pdf`, `html`, `txt`,
|
|
129
|
+
`xlsx`, ...). `tracked_changes` and `omitted` appear for DOCX, DOC and RTF only; `accepted` is
|
|
130
|
+
true when `--accept-changes` was given and there were changes to accept. For a PDF the report
|
|
131
|
+
has `format` and `pages`, the per-route counts the command already prints
|
|
132
|
+
(`{"total": 7, "accept": 5, "substitute": 1, "scan": 1, "corrupt": 0, "blank": 0}`); the
|
|
133
|
+
Python result carries the same dictionary as `result.report`. Counts of insertions and
|
|
134
|
+
deletions are runs of changes, as Word counts revisions: text typed together with its paragraph
|
|
135
|
+
break is one insertion.
|
|
136
|
+
- **ODT is refused** until anydoc reads it correctly: measured on a document saved from Word,
|
|
137
|
+
second-level numbering does not restart (`2.1.` became `2.3.`) and a comment is pasted into the
|
|
138
|
+
middle of a word. Save the document as DOCX. ODS and ODP are converted as before.
|
|
139
|
+
|
|
78
140
|
## How PDFs are handled
|
|
79
141
|
|
|
80
142
|
PDFs go through [pdf-inspector](https://pypi.org/project/pdf-inspector/), which gave the best
|
|
@@ -43,7 +43,7 @@ classifiers = [
|
|
|
43
43
|
# FastAPI/uvicorn are NOT here: this is a CLI package, the web stack lives in
|
|
44
44
|
# the "server" extra.
|
|
45
45
|
dependencies = [
|
|
46
|
-
"pdf-inspector==1.
|
|
46
|
+
"pdf-inspector==1.27.2",
|
|
47
47
|
# The independent decoder the per-page gate measures pdf-inspector against,
|
|
48
48
|
# and the text a page falls back to. [crypto] because AES-encrypted files
|
|
49
49
|
# otherwise raise DependencyError; cryptography used to arrive only
|
|
@@ -78,7 +78,13 @@ dependencies = [
|
|
|
78
78
|
# silently. Raising the pin is its own commit, after the measurement is rerun.
|
|
79
79
|
# markdownify (a range: it only renders HTML we have already cleaned) reads
|
|
80
80
|
# .html/.htm; anydoc does not.
|
|
81
|
-
|
|
81
|
+
#
|
|
82
|
+
# olefile (BSD-2-Clause, pure Python) is for trimitdown.office_inspect: anydoc
|
|
83
|
+
# drops tracked changes, comments and headers without a word and cannot be
|
|
84
|
+
# asked about them, so for a DOC the compound file is read here to count them.
|
|
85
|
+
# A range: it only locates streams; the counts are checked by tests on files
|
|
86
|
+
# made in Word.
|
|
87
|
+
office = ["firecrawl-anydoc==0.2.5", "markdownify>=1.2", "olefile>=0.46"]
|
|
82
88
|
# Нужен только тому, кто поднимает HTTP-слой (Docker-образ, десктопная сборка).
|
|
83
89
|
server = ["fastapi", "uvicorn", "python-multipart"]
|
|
84
90
|
|
|
@@ -10,6 +10,7 @@ pages it cannot vouch for), `assemble` (putting reviewed pages back) and
|
|
|
10
10
|
`render` (page images on demand, for checking digits on text-layer pages).
|
|
11
11
|
"""
|
|
12
12
|
import argparse
|
|
13
|
+
import json
|
|
13
14
|
import os
|
|
14
15
|
import sys
|
|
15
16
|
import tempfile
|
|
@@ -17,6 +18,7 @@ from pathlib import Path
|
|
|
17
18
|
|
|
18
19
|
from trimitdown import __version__
|
|
19
20
|
from trimitdown.convert import ConversionError, convert_bytes, convert_path
|
|
21
|
+
from trimitdown.office_inspect import summary_phrase
|
|
20
22
|
from trimitdown.pdf_route import render_markdown, summary_line
|
|
21
23
|
|
|
22
24
|
|
|
@@ -38,6 +40,18 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
|
38
40
|
dest="suffix",
|
|
39
41
|
help='file extension for stdin input, e.g. ".pdf" -- required with "-"',
|
|
40
42
|
)
|
|
43
|
+
convert.add_argument(
|
|
44
|
+
"--accept-changes",
|
|
45
|
+
action="store_true",
|
|
46
|
+
help="DOCX only: convert a document with unresolved tracked changes anyway and "
|
|
47
|
+
"print the text with every change accepted (the default is to refuse). "
|
|
48
|
+
"DOC and RTF with tracked changes are refused either way",
|
|
49
|
+
)
|
|
50
|
+
convert.add_argument(
|
|
51
|
+
"--report", metavar="PATH",
|
|
52
|
+
help="write a JSON report (format, tracked changes, what the Markdown leaves out; "
|
|
53
|
+
"for a PDF, page counts per route) to PATH when the conversion succeeds",
|
|
54
|
+
)
|
|
41
55
|
review = convert.add_argument_group(
|
|
42
56
|
"review (PDF only)",
|
|
43
57
|
"Write the pages that need checking -- scans, unverified OCR layers, "
|
|
@@ -153,9 +167,9 @@ def _run_convert(args) -> int:
|
|
|
153
167
|
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
|
154
168
|
tmp.write(data)
|
|
155
169
|
temp_path = Path(tmp.name)
|
|
156
|
-
result = convert_path(temp_path)
|
|
170
|
+
result = convert_path(temp_path, accept_changes=args.accept_changes)
|
|
157
171
|
else:
|
|
158
|
-
result = convert_bytes(data, suffix)
|
|
172
|
+
result = convert_bytes(data, suffix, accept_changes=args.accept_changes)
|
|
159
173
|
except ConversionError as e:
|
|
160
174
|
if temp_path is not None:
|
|
161
175
|
temp_path.unlink(missing_ok=True)
|
|
@@ -168,13 +182,19 @@ def _run_convert(args) -> int:
|
|
|
168
182
|
print(f"no such file: {path}", file=sys.stderr)
|
|
169
183
|
return 1
|
|
170
184
|
try:
|
|
171
|
-
result = convert_path(path)
|
|
185
|
+
result = convert_path(path, accept_changes=args.accept_changes)
|
|
172
186
|
except ConversionError as e:
|
|
173
187
|
print(f"could not convert {path}: {e}", file=sys.stderr)
|
|
174
188
|
return 1
|
|
175
189
|
source = path
|
|
176
190
|
|
|
177
191
|
try:
|
|
192
|
+
if args.report:
|
|
193
|
+
try:
|
|
194
|
+
_write_report(result, args.report)
|
|
195
|
+
except OSError as e:
|
|
196
|
+
print(f"could not write the report: {e}", file=sys.stderr)
|
|
197
|
+
return 1
|
|
178
198
|
if args.review_dir:
|
|
179
199
|
return _review(args, source, result)
|
|
180
200
|
finally:
|
|
@@ -185,10 +205,26 @@ def _run_convert(args) -> int:
|
|
|
185
205
|
# Silent on a clean document; one line when some page did not come from
|
|
186
206
|
# pdf-inspector, so the change in the output is never invisible.
|
|
187
207
|
print(summary_line(list(result.pages)), file=sys.stderr)
|
|
208
|
+
_print_office_summary(result)
|
|
188
209
|
_write(_document_text(args, result), args.output)
|
|
189
210
|
return 0
|
|
190
211
|
|
|
191
212
|
|
|
213
|
+
def _print_office_summary(result) -> None:
|
|
214
|
+
# The same words as the <!-- trimitdown: ... --> line at the top of the
|
|
215
|
+
# Markdown, built from the same report. Silent when there is nothing to say.
|
|
216
|
+
phrase = summary_phrase(result.report or {})
|
|
217
|
+
if phrase:
|
|
218
|
+
print(f"trimitdown: {phrase}", file=sys.stderr)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _write_report(result, path: str) -> None:
|
|
222
|
+
report = result.report if result.report is not None else {"schema": 1}
|
|
223
|
+
Path(path).write_text(
|
|
224
|
+
json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
192
228
|
def _document_text(args, result) -> str:
|
|
193
229
|
# --page-anchors only means something for a PDF, the one format with pages.
|
|
194
230
|
if getattr(args, "page_anchors", False) and result.pages:
|
|
@@ -18,7 +18,8 @@ import tiktoken
|
|
|
18
18
|
|
|
19
19
|
from pptx import Presentation
|
|
20
20
|
|
|
21
|
-
from trimitdown
|
|
21
|
+
from trimitdown import office_inspect
|
|
22
|
+
from trimitdown.pdf_route import PageRoute, path_counts, render_markdown, route_pdf
|
|
22
23
|
|
|
23
24
|
# Кэш едет внутри пакета как package data. Path(__file__) сработал бы для обычной
|
|
24
25
|
# установки, но не переживает упаковку; resources.files находит его и там, и в
|
|
@@ -56,6 +57,10 @@ class ConversionResult:
|
|
|
56
57
|
# / blank) and why. Last and defaulted, so the web layer, which builds
|
|
57
58
|
# nothing from it, keeps working unchanged.
|
|
58
59
|
pages: tuple[PageRoute, ...] | None = None
|
|
60
|
+
# What the conversion found out about the file, for machines (schema 1, see
|
|
61
|
+
# README "--report"). Always set by convert_path; None only for a result
|
|
62
|
+
# built by hand. Last and defaulted for the same reason as `pages`.
|
|
63
|
+
report: dict | None = None
|
|
59
64
|
|
|
60
65
|
|
|
61
66
|
def _get_encoding():
|
|
@@ -125,8 +130,11 @@ _TEXT_SUFFIXES = frozenset({".txt", ".md"})
|
|
|
125
130
|
_HTML_SUFFIXES = frozenset({".html", ".htm"})
|
|
126
131
|
|
|
127
132
|
|
|
128
|
-
def _convert_other(
|
|
133
|
+
def _convert_other(
|
|
134
|
+
path: Path, suffix: str, head: bytes, accept_changes: bool = False
|
|
135
|
+
) -> tuple[str, dict]:
|
|
129
136
|
"""Everything that is not a PDF: plain text, HTML, or the office formats.
|
|
137
|
+
Returns the Markdown and the report that goes with it.
|
|
130
138
|
|
|
131
139
|
Plain text and HTML are handled here because anydoc reads neither, and
|
|
132
140
|
markitdown, which did, passed `.txt` and `.md` through unchanged; dropping
|
|
@@ -139,10 +147,10 @@ def _convert_other(path: Path, suffix: str, head: bytes) -> str:
|
|
|
139
147
|
markdown file that quotes an <html> tag is still markdown.
|
|
140
148
|
"""
|
|
141
149
|
if suffix in _TEXT_SUFFIXES:
|
|
142
|
-
return _decode_text(path.read_bytes(), path.name)
|
|
150
|
+
return _decode_text(path.read_bytes(), path.name), _report(suffix.lstrip("."))
|
|
143
151
|
if suffix in _HTML_SUFFIXES or _sniffs_as_html(head):
|
|
144
|
-
return _html_to_markdown(_decode_html(path.read_bytes()))
|
|
145
|
-
return _anydoc_to_markdown(path)
|
|
152
|
+
return _html_to_markdown(_decode_html(path.read_bytes())), _report("html")
|
|
153
|
+
return _anydoc_to_markdown(path, suffix, accept_changes)
|
|
146
154
|
|
|
147
155
|
|
|
148
156
|
def _sniffs_as_html(head: bytes) -> bool:
|
|
@@ -278,25 +286,150 @@ def _describe_anydoc_error(error: Exception) -> str:
|
|
|
278
286
|
return f"the document could not be converted ({detail})"
|
|
279
287
|
|
|
280
288
|
|
|
281
|
-
def
|
|
289
|
+
def _report(fmt: str, **parts) -> dict:
|
|
290
|
+
"""The machine-readable report, schema 1. See README, "--report"."""
|
|
291
|
+
return {"schema": 1, "format": fmt, **parts}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _count_phrase(inspection: "office_inspect.Inspection") -> str:
|
|
295
|
+
said = []
|
|
296
|
+
if inspection.insertions:
|
|
297
|
+
said.append(f"{inspection.insertions} insertion{'s' * (inspection.insertions != 1)}")
|
|
298
|
+
if inspection.deletions:
|
|
299
|
+
said.append(f"{inspection.deletions} deletion{'s' * (inspection.deletions != 1)}")
|
|
300
|
+
return ", ".join(said)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
# ODT is refused until anydoc reads it correctly. Measured on a document saved
|
|
304
|
+
# from Word as ODT: a list restarted at the second level keeps counting
|
|
305
|
+
# ("2.1." became "2.3.", "a)" became "c)"), and a comment is pasted into the
|
|
306
|
+
# middle of a word with its author and date. Both are the kind of damage a
|
|
307
|
+
# reader cannot see. ODS and ODP are not affected by either and are not refused.
|
|
308
|
+
_ODT_REFUSAL = (
|
|
309
|
+
"ODT is not converted: the numbering of nested lists and the comments are "
|
|
310
|
+
"not read correctly (a nested list continues the previous count instead of "
|
|
311
|
+
"restarting, and a comment is pasted into the text with its author and date). "
|
|
312
|
+
"Save the document as DOCX and convert that"
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _refuse_tracked_changes(inspection: "office_inspect.Inspection", accept_changes: bool) -> None:
|
|
317
|
+
"""Raise unless the document may be printed. No-op when it has no changes."""
|
|
318
|
+
if not inspection.has_changes:
|
|
319
|
+
return
|
|
320
|
+
counts = _count_phrase(inspection)
|
|
321
|
+
shout = inspection.format.upper()
|
|
322
|
+
if inspection.format != "docx":
|
|
323
|
+
# anydoc prints a DOC or RTF with the deleted wording in place and no
|
|
324
|
+
# marks, so there is no accepted reading to hand over. Measured, not
|
|
325
|
+
# assumed: the deleted word sits next to the inserted one in the output.
|
|
326
|
+
raise ConversionError(
|
|
327
|
+
f"the {shout} document has unresolved tracked changes ({counts}); the {shout} "
|
|
328
|
+
"reader prints the deleted wording in place with no marks, and "
|
|
329
|
+
"--accept-changes cannot repair that for this format. Save the file "
|
|
330
|
+
"as DOCX in Word and convert that with --accept-changes, or accept or "
|
|
331
|
+
"reject the changes in Word and save it again"
|
|
332
|
+
)
|
|
333
|
+
if not accept_changes:
|
|
334
|
+
raise ConversionError(
|
|
335
|
+
f"the document has unresolved tracked changes ({counts}); printing it "
|
|
336
|
+
"as it is would drop the struck-out wording without a trace. Accept or "
|
|
337
|
+
"reject the changes in Word and save it again, or convert it with every "
|
|
338
|
+
"change accepted: --accept-changes (accept_changes=True in Python)"
|
|
339
|
+
)
|
|
340
|
+
if inspection.accept_blockers:
|
|
341
|
+
raise ConversionError(
|
|
342
|
+
f"the document has tracked changes ({counts}) that --accept-changes cannot "
|
|
343
|
+
f"apply faithfully: {'; '.join(inspection.accept_blockers)}. Accept or "
|
|
344
|
+
"reject the changes in Word and save it again"
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _anydoc_to_markdown(
|
|
349
|
+
path: Path, suffix: str = "", accept_changes: bool = False
|
|
350
|
+
) -> tuple[str, dict]:
|
|
282
351
|
# Imported here, never at module level: a PDF must not pay for it, and the
|
|
283
352
|
# base install does not have it.
|
|
284
353
|
try:
|
|
285
354
|
import anydoc
|
|
286
355
|
except ImportError:
|
|
287
356
|
raise ConversionError(_NEEDS_OFFICE_EXTRA) from None
|
|
357
|
+
|
|
358
|
+
data = path.read_bytes()
|
|
359
|
+
# The format is anydoc's own reading of the content, so the inspection below
|
|
360
|
+
# looks at exactly what anydoc will convert; the extension is its fallback too.
|
|
361
|
+
fmt = anydoc.format_from_bytes(data) or anydoc.format_from_extension(suffix)
|
|
362
|
+
|
|
363
|
+
inspection = None
|
|
364
|
+
inspection_failure = None
|
|
365
|
+
if fmt == "odt":
|
|
366
|
+
raise ConversionError(_ODT_REFUSAL)
|
|
367
|
+
if fmt in office_inspect.INSPECTED_FORMATS:
|
|
368
|
+
# anydoc drops tracked changes, comments and headers without a word and
|
|
369
|
+
# cannot be asked about them, so this module looks at the file first
|
|
370
|
+
# (see office_inspect). Do not route around it.
|
|
371
|
+
try:
|
|
372
|
+
inspection = office_inspect.inspect(data, fmt)
|
|
373
|
+
except office_inspect.InspectionFailed as e:
|
|
374
|
+
inspection_failure = e
|
|
375
|
+
else:
|
|
376
|
+
_refuse_tracked_changes(inspection, accept_changes)
|
|
377
|
+
|
|
288
378
|
try:
|
|
289
379
|
# ocr="reject" is the privacy guarantee, not a default to be tidied up.
|
|
290
380
|
# anydoc's other mode, "hosted", uploads the whole document to
|
|
291
381
|
# Firecrawl; with an api_key or api_url it would do so quietly. Nothing
|
|
292
382
|
# here passes either, and tests/test_convert_pure.py fails if anyone does.
|
|
293
|
-
|
|
383
|
+
text = anydoc.to_markdown(str(path), ocr="reject")
|
|
294
384
|
except anydoc.ConvertError as e:
|
|
385
|
+
# A file anydoc cannot read is reported as anydoc says, whatever the
|
|
386
|
+
# inspection made of it.
|
|
295
387
|
raise ConversionError(_describe_anydoc_error(e)) from e
|
|
296
388
|
|
|
389
|
+
if fmt not in office_inspect.INSPECTED_FORMATS:
|
|
390
|
+
return text, _report(fmt or suffix.lstrip(".").lower() or "unknown")
|
|
391
|
+
if inspection is None:
|
|
392
|
+
# anydoc read a file that could not be examined. Printing it would be
|
|
393
|
+
# printing it unchecked: refuse, and say why.
|
|
394
|
+
raise ConversionError(
|
|
395
|
+
f"the {fmt.upper()} document could not be checked for tracked changes, "
|
|
396
|
+
f"comments and headers ({inspection_failure}); it is not printed unchecked"
|
|
397
|
+
)
|
|
297
398
|
|
|
298
|
-
|
|
299
|
-
|
|
399
|
+
try:
|
|
400
|
+
images = office_inspect.count_images(anydoc.to_document(data))
|
|
401
|
+
except anydoc.ConvertError as e:
|
|
402
|
+
raise ConversionError(_describe_anydoc_error(e)) from e
|
|
403
|
+
|
|
404
|
+
report = _report(
|
|
405
|
+
fmt,
|
|
406
|
+
tracked_changes={
|
|
407
|
+
"present": inspection.has_changes,
|
|
408
|
+
"insertions": inspection.insertions,
|
|
409
|
+
"deletions": inspection.deletions,
|
|
410
|
+
"accepted": inspection.has_changes and accept_changes,
|
|
411
|
+
},
|
|
412
|
+
omitted={
|
|
413
|
+
"headers_footers": inspection.headers_footers,
|
|
414
|
+
"comments": inspection.comments,
|
|
415
|
+
"images": images,
|
|
416
|
+
},
|
|
417
|
+
)
|
|
418
|
+
phrase = office_inspect.summary_phrase(report)
|
|
419
|
+
if phrase:
|
|
420
|
+
# The line is an HTML comment: Markdown renderers hide it and a reader
|
|
421
|
+
# of the raw text (an LLM) sees what was left out.
|
|
422
|
+
text = f"<!-- trimitdown: {phrase} -->\n\n{text}"
|
|
423
|
+
return text, report
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def convert_path(path: Path | str, *, accept_changes: bool = False) -> ConversionResult:
|
|
427
|
+
"""Сконвертировать файл на диске. Синхронно: асинхронность -- забота веб-слоя.
|
|
428
|
+
|
|
429
|
+
A DOCX, DOC or RTF with unresolved tracked changes is refused (ConversionError);
|
|
430
|
+
`accept_changes=True` converts a DOCX anyway and prints the accepted text. DOC
|
|
431
|
+
and RTF are refused either way. The flag means nothing to any other format.
|
|
432
|
+
"""
|
|
300
433
|
path = Path(path)
|
|
301
434
|
suffix = path.suffix.lower()
|
|
302
435
|
|
|
@@ -327,8 +460,9 @@ def convert_path(path: Path | str) -> ConversionResult:
|
|
|
327
460
|
if suffix == ".pdf" and head.find(b"%PDF") != -1:
|
|
328
461
|
pages = tuple(route_pdf(path))
|
|
329
462
|
text = render_markdown(list(pages))
|
|
463
|
+
report = _report("pdf", pages={"total": len(pages), **path_counts(list(pages))})
|
|
330
464
|
else:
|
|
331
|
-
text = _convert_other(path, suffix, head)
|
|
465
|
+
text, report = _convert_other(path, suffix, head, accept_changes)
|
|
332
466
|
except Exception as e:
|
|
333
467
|
raise ConversionError(str(e)) from e
|
|
334
468
|
|
|
@@ -345,11 +479,11 @@ def convert_path(path: Path | str) -> ConversionResult:
|
|
|
345
479
|
|
|
346
480
|
return ConversionResult(
|
|
347
481
|
text=text, tokens_after=after, tokens_before=before, unit=unit, units=units,
|
|
348
|
-
pages=pages,
|
|
482
|
+
pages=pages, report=report,
|
|
349
483
|
)
|
|
350
484
|
|
|
351
485
|
|
|
352
|
-
def convert_bytes(data: bytes, suffix: str) -> ConversionResult:
|
|
486
|
+
def convert_bytes(data: bytes, suffix: str, *, accept_changes: bool = False) -> ConversionResult:
|
|
353
487
|
"""Сконвертировать содержимое в памяти.
|
|
354
488
|
|
|
355
489
|
Существует ради веб-слоя, где вход -- UploadFile, а не путь. Временный файл
|
|
@@ -359,6 +493,6 @@ def convert_bytes(data: bytes, suffix: str) -> ConversionResult:
|
|
|
359
493
|
tmp.write(data)
|
|
360
494
|
tmp_path = tmp.name
|
|
361
495
|
try:
|
|
362
|
-
return convert_path(tmp_path)
|
|
496
|
+
return convert_path(tmp_path, accept_changes=accept_changes)
|
|
363
497
|
finally:
|
|
364
498
|
Path(tmp_path).unlink(missing_ok=True)
|