opencontracting-nutcracker 0.0.1__py3-none-any.whl

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.
docs/Makefile ADDED
@@ -0,0 +1,20 @@
1
+ # Minimal makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line, and also
5
+ # from the environment for the first two.
6
+ SPHINXOPTS ?=
7
+ SPHINXBUILD ?= sphinx-build
8
+ SOURCEDIR = .
9
+ BUILDDIR = _build
10
+
11
+ # Put it first so that "make" without argument is like "make help".
12
+ help:
13
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14
+
15
+ .PHONY: help Makefile
16
+
17
+ # Catch-all target: route all unknown targets to Sphinx using the new
18
+ # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19
+ %: Makefile
20
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
docs/api/index.rst ADDED
@@ -0,0 +1,10 @@
1
+ API reference
2
+ =============
3
+
4
+ .. automodule:: nutcracker
5
+ :members: Converter, render, ARCHIVES, CONVERTIBLE, IMAGES
6
+
7
+ .. automodule:: nutcracker.archive
8
+ :members: list_7z, member_title, zip_listing, zip_name
9
+
10
+ .. automodule:: nutcracker.exceptions
docs/changelog.rst ADDED
@@ -0,0 +1,13 @@
1
+ Changelog
2
+ =========
3
+
4
+ 0.0.1 (2026-11-29)
5
+ ------------------
6
+
7
+ First release, with the per-file conversion of ``evals/scripts/build_corpus.py`` in the oecd-poland repository. Its output is the same, except:
8
+
9
+ - A failure of pandoc or ``textutil`` is reported as ``ConversionError``, not ``RuntimeError``.
10
+ - An error message names the file instead of giving its path, and has no temporary paths, so that it doesn't vary between machines or runs.
11
+ - Without ``textutil``, .doc, .rtf, .odt and .ods files are converted with LibreOffice, else pandoc (.rtf and .odt).
12
+ - If 7-Zip's ``7zz`` command isn't installed, ``7z`` is used.
13
+ - If ``unar`` isn't installed, its absence is reported, instead of stopping the conversion.
docs/conf.py ADDED
@@ -0,0 +1,50 @@
1
+ # Configuration file for the Sphinx documentation builder.
2
+ #
3
+ # For the full list of built-in configuration values, see the documentation:
4
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html
5
+
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ sys.path.insert(0, str(Path(__file__).parent.parent))
10
+
11
+ # -- Project information -----------------------------------------------------
12
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
13
+
14
+ project = "Nutcracker"
15
+ copyright = "2026, Open Contracting Partnership"
16
+ author = "Open Contracting Partnership"
17
+
18
+ version = "0.0.1"
19
+ release = version
20
+
21
+ # -- General configuration ---------------------------------------------------
22
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
23
+
24
+ extensions = [
25
+ "sphinx.ext.autodoc",
26
+ "sphinx.ext.intersphinx",
27
+ "sphinx.ext.viewcode",
28
+ ]
29
+
30
+ templates_path = ["_templates"]
31
+ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
32
+
33
+ # -- Options for HTML output -------------------------------------------------
34
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
35
+
36
+ html_theme = "furo"
37
+ html_static_path = []
38
+
39
+ # -- Extension configuration -------------------------------------------------
40
+
41
+ autodoc_default_options = {
42
+ "members": None,
43
+ "member-order": "bysource",
44
+ }
45
+ autodoc_typehints = "description"
46
+ autodoc_type_aliases = {}
47
+
48
+ intersphinx_mapping = {
49
+ "python": ("https://docs.python.org/3", None),
50
+ }
@@ -0,0 +1,28 @@
1
+ Contributing
2
+ ============
3
+
4
+ Setup
5
+ -----
6
+
7
+ Set up the git pre-commit hook:
8
+
9
+ .. code-block:: bash
10
+
11
+ pip install pre-commit
12
+ pre-commit install
13
+
14
+ Install the command-line tools listed in :doc:`../index`. Tests that need a missing tool are skipped.
15
+
16
+ Run the tests:
17
+
18
+ .. code-block:: bash
19
+
20
+ pip install -e .[pdf,test]
21
+ pytest -W error
22
+
23
+ Change the output
24
+ -----------------
25
+
26
+ A change to how files are converted changes the output of :meth:`~nutcracker.Converter.convert`. Release it as a new version, so that cached conversions are invalidated.
27
+
28
+ A change to how pages are OCR'd (like the resolution) must increment ``OCR_VERSION`` in ``nutcracker/pdf.py``, which invalidates the OCR store. Otherwise, the OCR store's folder name must stay the same for the same tools.
docs/index.rst ADDED
@@ -0,0 +1,105 @@
1
+ Nutcracker |release|
2
+ ====================
3
+
4
+ .. include:: ../README.rst
5
+
6
+ Installation
7
+ ------------
8
+
9
+ .. code-block:: bash
10
+
11
+ pip install opencontracting-nutcracker[pdf]
12
+
13
+ The ``pdf`` extra installs `PyMuPDF <https://pymupdf.readthedocs.io/>`__, which is needed to convert PDFs and images. PyMuPDF is licensed under the AGPL, so it is optional.
14
+
15
+ Nutcracker calls these command-line tools, if installed:
16
+
17
+ .. list-table::
18
+ :header-rows: 1
19
+
20
+ * - Tool
21
+ - Converts
22
+ * - `pandoc <https://pandoc.org>`__
23
+ - .docx, .docm, .pptx, .html, .htm (and .odt, .rtf, as below)
24
+ * - `Tesseract <https://tesseract-ocr.github.io>`__, with the Polish (``pol``) and orientation (``osd``) models
25
+ - PDF pages without a text layer, and images
26
+ * - `7-Zip <https://www.7-zip.org>`__ (``7zz`` or ``7z``)
27
+ - .7z, .rar, split archives, and ZIPs that Python can't read
28
+ * - `The Unarchiver <https://theunarchiver.com/command-line>`__ (``unar``)
29
+ - RAR archives that 7-Zip can't decompress
30
+ * - ``textutil`` (macOS)
31
+ - .doc, .rtf, .odt, .ods
32
+ * - `LibreOffice <https://www.libreoffice.org>`__ (``soffice``)
33
+ - .doc, .rtf, .odt, .ods, without ``textutil``
34
+
35
+ Without ``textutil`` or LibreOffice, .rtf and .odt files are converted with pandoc, and .doc and .ods files fail to convert. The output of ``textutil`` and of LibreOffice differ, so the same .doc file can yield different text on macOS and Linux.
36
+
37
+ Usage
38
+ -----
39
+
40
+ From the command line, print a file's text:
41
+
42
+ .. code-block:: bash
43
+
44
+ nutcracker path/to/file.pdf
45
+
46
+ Or an archive's text, with a ``# member`` line before each member:
47
+
48
+ .. code-block:: bash
49
+
50
+ nutcracker path/to/archive.zip
51
+
52
+ Run ``nutcracker --help`` for options.
53
+
54
+ From Python:
55
+
56
+ .. code-block:: python
57
+
58
+ from nutcracker import Converter, render
59
+
60
+ converter = Converter(cache_dir="cache", ocr_dir="cache/ocr")
61
+ data = converter.convert("archive.zip")
62
+ for item in data["items"]:
63
+ print(render(item["pages"], item["flags"], header=f"# {item['member']}"))
64
+ for error in data["errors"]:
65
+ print(error)
66
+
67
+ A file that fails to convert is left out of ``items``, and its error is reported in ``errors``. Members of archives in formats that aren't converted (like CAD drawings) are reported in ``skipped``.
68
+
69
+ How files are converted
70
+ ~~~~~~~~~~~~~~~~~~~~~~~
71
+
72
+ PDF
73
+ Each page's text layer is extracted. A page up to A3 without a text layer, or with little text under an image that covers it (a scan under a stamp), is OCR'd at 300 dpi; if Tesseract's orientation detection suggests a rotation, the more confident reading is kept. Struck-through words are wrapped in ``[skreślono: …]``. A larger page without text is flagged as a ``drawing``, and a page without text as ``no text``.
74
+ Images
75
+ OCR'd like PDF pages.
76
+ Word (.docx, .docm)
77
+ Converted by pandoc, after list numbers are made literal (as Word displays them) and struck-through text is wrapped in ``[skreślono: …]``.
78
+ Word (.doc), RTF, OpenDocument text (.odt)
79
+ Converted by ``textutil``, unless it has struck-through text, in which case it is converted to .docx first.
80
+ Spreadsheets (.xlsx, .xlsm, .xls, .ods)
81
+ One page per sheet, with tab-separated cells. Runs of identical rows are collapsed, and sheets are truncated after 5,000 rows.
82
+ XML
83
+ The text content, joined by spaces.
84
+ Text
85
+ Decoded as UTF-8, else Windows-1250, else ISO-8859-1.
86
+
87
+ A file whose content doesn't match its extension (like a PDF named .doc) is converted according to its content.
88
+
89
+ Caching
90
+ ~~~~~~~
91
+
92
+ With ``cache_dir``, a conversion is cached by the files' names and contents (SHA-256), whether OCR is on, and the versions of Nutcracker and of the tools and libraries that shape its output. A new version of any of these is a cache miss.
93
+
94
+ With ``ocr_dir``, OCR text is stored by page, by the file's content and by the versions of Tesseract, its models and MuPDF. A file keeps its OCR text if it is renamed or repacked in another archive.
95
+
96
+ To OCR many files in parallel, set ``ocr_queue_dir`` and convert the files: pages missing from the OCR store are queued in :attr:`~nutcracker.Converter.ocr_queue` instead of OCR'd. Then, OCR them in parallel with :meth:`~nutcracker.Converter.ocr_pages` and :meth:`~nutcracker.Converter.save_ocr`, and convert the files again without ``ocr_queue_dir``.
97
+
98
+ .. toctree::
99
+ :caption: Contents
100
+
101
+ api/index
102
+ contributing/index
103
+ changelog
104
+
105
+ Copyright (c) 2026 Open Contracting Partnership, released under the BSD license
docs/requirements.txt ADDED
@@ -0,0 +1 @@
1
+ furo
nutcracker/__init__.py ADDED
@@ -0,0 +1,380 @@
1
+ """Convert tender documents, including archives and scans, to text."""
2
+
3
+ import functools
4
+ import hashlib
5
+ import importlib.metadata
6
+ import json
7
+ import os
8
+ import platform
9
+ import re
10
+ import shutil
11
+ import tempfile
12
+ import xml.etree.ElementTree as ET
13
+ from pathlib import Path
14
+
15
+ import openpyxl
16
+ import xlrd
17
+
18
+ from nutcracker import archive, word
19
+ from nutcracker.exceptions import ConversionError
20
+ from nutcracker.util import ARCHIVES, CONVERTIBLE, IMAGES, file_digest, link, run, which
21
+
22
+ try:
23
+ from nutcracker import pdf
24
+ except ModuleNotFoundError as e: # the "pdf" extra isn't installed
25
+ if e.name != "pymupdf":
26
+ raise
27
+ pdf = None
28
+
29
+ __all__ = ["ARCHIVES", "CONVERTIBLE", "IMAGES", "Converter", "render"]
30
+
31
+ # Counted after collapsing repeated rows. Sheets longer than this are data (traffic counts, address lists), and the
32
+ # marker gives the total.
33
+ MAX_SHEET_ROWS = 5000
34
+
35
+
36
+ def render(pages, flags, header=None):
37
+ """
38
+ Return a converted file's text, with a ``[page N]`` marker before each page if it has many, and its flag if any.
39
+
40
+ :param pages: the text of each page
41
+ :param flags: the flag of each page: ``"ocr"``, ``"no text"``, ``"drawing"`` or ``""``
42
+ :param header: a first line
43
+ """
44
+ lines = [] if header is None else [header]
45
+ for i, (text, flag) in enumerate(zip(pages, flags, strict=True), 1):
46
+ if len(pages) > 1 or flag:
47
+ lines.append(f"\n[page {i}{': ' + flag if flag else ''}]")
48
+ lines.append(text.strip())
49
+ return "\n".join(lines) + "\n"
50
+
51
+
52
+ def sheet_text(name, rows):
53
+ """Return a sheet as tab-separated lines, with runs of identical rows collapsed and at most MAX_SHEET_ROWS rows."""
54
+ lines = [f"## Sheet: {name}"]
55
+ kept = total = repeats = 0
56
+ last = None
57
+ for row in rows:
58
+ cells = ["" if v is None else str(v).strip() for v in row]
59
+ if not any(cells):
60
+ continue
61
+ line = "\t".join(cells).rstrip()
62
+ if line == last:
63
+ repeats += 1
64
+ continue
65
+ if repeats and kept < MAX_SHEET_ROWS:
66
+ lines.append(f"[previous row repeated {repeats} times]")
67
+ repeats = 0
68
+ last = line
69
+ total += 1
70
+ if kept < MAX_SHEET_ROWS:
71
+ lines.append(line)
72
+ kept += 1
73
+ if repeats and kept < MAX_SHEET_ROWS:
74
+ lines.append(f"[previous row repeated {repeats} times]")
75
+ if total > kept:
76
+ lines.append(f"[truncated after {kept} of {total} rows]")
77
+ return "\n".join(lines)
78
+
79
+
80
+ def convert_xlsx(path):
81
+ wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
82
+ try:
83
+ return [sheet_text(ws.title, ws.iter_rows(values_only=True)) for ws in wb.worksheets], [""] * len(
84
+ wb.sheetnames
85
+ )
86
+ finally:
87
+ wb.close()
88
+
89
+
90
+ def convert_xls(path):
91
+ wb = xlrd.open_workbook(path)
92
+ sheets = [sheet_text(sh.name, (sh.row_values(i) for i in range(sh.nrows))) for sh in wb.sheets()]
93
+ return sheets, [""] * len(sheets)
94
+
95
+
96
+ def convert_ods(path, tmp):
97
+ if which("textutil"):
98
+ return word.convert_textutil(path)
99
+ return convert_xlsx(word.convert_libreoffice(path, tmp, "xlsx"))
100
+
101
+
102
+ def convert_xml(path):
103
+ root = ET.parse(path).getroot() # noqa: S314 # stdlib parser doesn't expand external entities
104
+ return [" ".join(t.strip() for t in root.itertext() if t.strip())], [""]
105
+
106
+
107
+ def convert_txt(path):
108
+ raw = path.read_bytes()
109
+ for encoding in ("utf-8", "cp1250"):
110
+ try:
111
+ return [raw.decode(encoding)], [""]
112
+ except UnicodeDecodeError:
113
+ continue
114
+ return [raw.decode("latin-1")], [""]
115
+
116
+
117
+ def sniff(path):
118
+ """Return the real type of files whose extension doesn't match their content."""
119
+ head = path.read_bytes()[:8]
120
+ if head.startswith(b"%PDF"):
121
+ return ".pdf"
122
+ if head.startswith(b"PK\x03\x04"):
123
+ return None # zip container: docx, xlsx, odt or zip; trust the extension
124
+ if head.startswith(b"\xd0\xcf\x11\xe0"):
125
+ return ".doc" if path.suffix.lower() not in {".xls", ".doc"} else None
126
+ if head.startswith(b"{\\rtf"):
127
+ return ".rtf"
128
+ return None
129
+
130
+
131
+ def first_line(args):
132
+ """Return the first non-empty line of a command's output, or ``None`` if the command isn't installed."""
133
+ try:
134
+ result = run(args, timeout=60)
135
+ except ConversionError:
136
+ return None
137
+ return next((line.strip() for line in result.stdout.decode("utf-8", "replace").splitlines() if line.strip()), None)
138
+
139
+
140
+ def package_version(name):
141
+ try:
142
+ return importlib.metadata.version(name)
143
+ except importlib.metadata.PackageNotFoundError:
144
+ return None
145
+
146
+
147
+ def ocr_version():
148
+ """Return the OCR store's folder name, or ``None`` if OCR is unavailable."""
149
+ try:
150
+ return pdf.ocr_tools()[0] if pdf else None
151
+ except (ConversionError, OSError, TypeError): # Tesseract or its models aren't installed
152
+ return None
153
+
154
+
155
+ @functools.cache
156
+ def tools(ocr):
157
+ """Return the versions of this package and of the tools and libraries that shape its output."""
158
+ return {
159
+ "nutcracker": package_version("opencontracting-nutcracker"),
160
+ "ocr": ocr_version() if ocr else None,
161
+ "pandoc": first_line(["pandoc", "--version"]),
162
+ "7-zip": first_line([archive.seven_zip()]),
163
+ "unar": first_line(["unar", "-v"]),
164
+ # textutil has no version option.
165
+ "textutil": platform.mac_ver()[0] if which("textutil") else None,
166
+ "libreoffice": first_line([which("soffice", "libreoffice") or "soffice", "--version"]),
167
+ "pymupdf": package_version("pymupdf"),
168
+ "openpyxl": package_version("openpyxl"),
169
+ "xlrd": package_version("xlrd"),
170
+ }
171
+
172
+
173
+ def spellings(path):
174
+ """Return the ways a path can appear in an error message: as is, and with backslashes escaped, as in a repr."""
175
+ return sorted({str(path).replace("\\", "\\\\"), str(path)}, key=len, reverse=True)
176
+
177
+
178
+ def write_atomic(path, text):
179
+ """Write a file via a temporary file, so that parallel processes writing the same file don't interleave."""
180
+ path.parent.mkdir(parents=True, exist_ok=True)
181
+ partial = path.with_suffix(f".{os.getpid()}.tmp")
182
+ partial.write_text(text, encoding="utf-8")
183
+ partial.replace(path)
184
+
185
+
186
+ class Converter:
187
+ """
188
+ Convert files and archives to text, page by page.
189
+
190
+ :param cache_dir: a directory in which to cache conversions, by the files' names and contents, and the versions of
191
+ this package and of the tools and libraries that shape its output
192
+ :param ocr_dir: a directory in which to store OCR text, by the file's contents and the OCR tools' versions
193
+ :param ocr: whether to OCR pages without a text layer, and images
194
+ :param tmp_dir: a directory for temporary files, like extracted archive members (default: the system's)
195
+ :param ocr_queue_dir: if set, the pages missing from the OCR store aren't OCR'd. Instead, their files are copied
196
+ to this directory, named by digest, and ``(path, page indexes)`` is appended to :attr:`ocr_queue`. Use
197
+ :meth:`ocr_pages` and :meth:`save_ocr` to OCR them in parallel, then convert the files again.
198
+ """
199
+
200
+ def __init__(self, *, cache_dir=None, ocr_dir=None, ocr=True, tmp_dir=None, ocr_queue_dir=None):
201
+ self.cache_dir = None if cache_dir is None else Path(cache_dir)
202
+ self.ocr_dir = None if ocr_dir is None else Path(ocr_dir)
203
+ self.ocr = ocr
204
+ self.tmp_dir = None if tmp_dir is None else Path(tmp_dir)
205
+ self.ocr_queue_dir = None if ocr_queue_dir is None else Path(ocr_queue_dir)
206
+ #: ``(path, page indexes)`` for each file whose pages are missing from the OCR store
207
+ self.ocr_queue = []
208
+
209
+ def convert(self, path, parts=(), *, names=None, digests=None):
210
+ """
211
+ Convert a file, or an archive's convertible members.
212
+
213
+ Errors don't stop the conversion: a file that fails is left out, and its error is reported.
214
+
215
+ :param path: the file, or the entry point of a split archive (like ``.zip`` or ``.001``)
216
+ :param parts: the other volumes of a split archive. If two parts have the same name, the first is used.
217
+ :param names: the filename of each file (default: its own), if the files on disk are named otherwise. Split
218
+ archives' volumes must be named alike.
219
+ :param digests: the SHA-256 of each file, if known
220
+ :returns: a dict with keys ``items`` (for each converted file, a dict with keys ``member`` (its path in the
221
+ archive, or ``None``), ``pages`` (the text of each page) and ``flags`` (the flag of each page, as for
222
+ :func:`render`)), ``errors`` and ``skipped`` (unconvertible members' paths)
223
+ """
224
+ path = Path(path)
225
+ parts = [Path(p) for p in parts]
226
+ names = {Path(k): v for k, v in (names or {}).items()}
227
+ cache = self._cache_path([path, *parts], names, digests or {})
228
+ if cache and cache.exists():
229
+ return json.loads(cache.read_text(encoding="utf-8"))
230
+ queued = len(self.ocr_queue)
231
+ data = self._convert(path, parts, names)
232
+ if cache and len(self.ocr_queue) == queued: # otherwise, it lacks the queued pages' OCR
233
+ write_atomic(cache, json.dumps(data, ensure_ascii=False))
234
+ return data
235
+
236
+ def ocr_pages(self, path, indexes):
237
+ """Return ``{page index: OCR text}`` for pages of a PDF or image, without using the OCR store."""
238
+ with self._tmp() as tmp:
239
+ return self._pdf().ocr_pages(path, indexes, Path(tmp))
240
+
241
+ def save_ocr(self, digest, texts):
242
+ """Add ``{page index: OCR text}`` to the OCR store's entry for a file, by its SHA-256."""
243
+ store = self._ocr_store(digest)
244
+ stored = json.loads(store.read_text(encoding="utf-8")) if store.exists() else {}
245
+ write_atomic(store, json.dumps(stored | {str(i): text for i, text in texts.items()}, ensure_ascii=False))
246
+
247
+ def _convert(self, path, parts, names):
248
+ state = {"errors": [], "skipped": []}
249
+ results = []
250
+ name = names.get(path, path.name)
251
+ with self._tmp() as tmpdir:
252
+ tmp = Path(tmpdir)
253
+ if Path(name).suffix.lower() in ARCHIVES:
254
+ links = tmp / "parts"
255
+ links.mkdir()
256
+ for p in [path, *parts]:
257
+ destination = links / names.get(p, p.name)
258
+ if not destination.exists():
259
+ link(p, destination)
260
+ items = archive.expand_archive(links / name, tmp, state, 1, "", split=bool(parts))
261
+ else:
262
+ items = [(None, path)]
263
+ for member, item in items:
264
+ try:
265
+ pages, flags = self._convert_file(item, tmp)
266
+ except Exception as e: # noqa: BLE001 # one bad file mustn't stop the others
267
+ display = member or path.name
268
+ message = str(e)
269
+ for spelling in spellings(item):
270
+ message = message.replace(spelling, display)
271
+ state["errors"].append(f"{display}: {type(e).__name__}: {message}"[:300])
272
+ continue
273
+ results.append({"member": member, "pages": pages, "flags": flags})
274
+ # Error messages mustn't vary between runs, so temporary paths are removed.
275
+ temporary = re.compile("(?:" + "|".join(map(re.escape, spellings(tmp))) + r")[^\s'\"]*")
276
+ errors = [temporary.sub("[temporary file]", error) for error in state["errors"]]
277
+ return {"items": results, "errors": errors, "skipped": state["skipped"]}
278
+
279
+ def _convert_file(self, path, tmp):
280
+ suffix = sniff(path) or path.suffix.lower()
281
+ if suffix == ".pdf":
282
+ return self._pdf().convert_pdf(path, tmp, self._ocr_texts if self.ocr else None)
283
+ if suffix in IMAGES:
284
+ return self._pdf().convert_image(path, tmp, self._ocr_texts if self.ocr else None)
285
+ if suffix == ".pptx":
286
+ return word.convert_pandoc(path, "pptx")
287
+ if suffix in {".docx", ".docm"}:
288
+ return word.convert_docx(path, tmp)
289
+ if suffix == ".odt":
290
+ return word.convert_word(
291
+ path,
292
+ tmp,
293
+ fallback=lambda: word.convert_pandoc(path, "odt"),
294
+ portable=lambda: word.convert_pandoc(path, "odt"),
295
+ )
296
+ if suffix in {".html", ".htm"}:
297
+ return word.convert_pandoc(path, "html")
298
+ if suffix == ".rtf":
299
+ return word.convert_word(path, tmp, portable=lambda: word.convert_pandoc(path, "rtf"))
300
+ if suffix == ".doc":
301
+ return word.convert_word(path, tmp)
302
+ if suffix in {".xlsx", ".xlsm"}:
303
+ return convert_xlsx(path)
304
+ if suffix == ".xls":
305
+ return convert_xls(path)
306
+ if suffix == ".ods":
307
+ return convert_ods(path, tmp)
308
+ if suffix == ".xml":
309
+ return convert_xml(path)
310
+ return convert_txt(path)
311
+
312
+ def _ocr_texts(self, path, doc, indexes, tmp):
313
+ """
314
+ Return {page index: OCR text} for pages of a PDF or image, from the OCR store or by OCR'ing and storing them.
315
+
316
+ The store is keyed by the file's bytes, so a file keeps its OCR when its archive is repacked or renamed.
317
+ """
318
+ if not indexes:
319
+ return {}
320
+ if self.ocr_dir is None:
321
+ return {i: pdf.ocr_page(doc[i], tmp) for i in indexes}
322
+ digest = file_digest(path)
323
+ store = self._ocr_store(digest)
324
+ stored = json.loads(store.read_text(encoding="utf-8")) if store.exists() else {}
325
+ missing = [i for i in indexes if str(i) not in stored]
326
+ if missing and self.ocr_queue_dir is not None:
327
+ # The file is copied, as an archive member's extracted file is deleted after conversion.
328
+ queued = self.ocr_queue_dir / f"{digest}{path.suffix.lower()}"
329
+ if not queued.exists():
330
+ queued.parent.mkdir(parents=True, exist_ok=True)
331
+ partial = queued.with_suffix(f".{os.getpid()}.tmp")
332
+ shutil.copyfile(path, partial)
333
+ partial.replace(queued)
334
+ self.ocr_queue.append((queued, missing))
335
+ return {i: stored[str(i)] for i in indexes if str(i) in stored}
336
+ for i in missing:
337
+ stored[str(i)] = pdf.ocr_page(doc[i], tmp)
338
+ if missing:
339
+ # Another process can write the same file's entry, so replace it atomically.
340
+ write_atomic(store, json.dumps(stored, ensure_ascii=False))
341
+ return {i: stored[str(i)] for i in indexes}
342
+
343
+ def _ocr_store(self, digest):
344
+ name, ocr_tools = self._pdf().ocr_tools()
345
+ folder = self.ocr_dir / name
346
+ if not (folder / "tools.json").exists():
347
+ write_atomic(folder / "tools.json", json.dumps(ocr_tools, indent=2))
348
+ return folder / digest[:2] / f"{digest}.json"
349
+
350
+ def _cache_path(self, paths, names, digests):
351
+ if self.cache_dir is None:
352
+ return None
353
+ files = [[names.get(p, p.name), digests.get(p) or self._digest(p)] for p in paths]
354
+ key = json.dumps({"files": files, "ocr": self.ocr, "tools": tools(self.ocr)}, ensure_ascii=False)
355
+ key = hashlib.sha256(key.encode()).hexdigest()
356
+ return self.cache_dir / "conversion" / key[:2] / f"{key}.json"
357
+
358
+ def _digest(self, path):
359
+ """Return a file's SHA-256, remembered by its path, size and modification time."""
360
+ stat = path.stat()
361
+ key = hashlib.sha256(f"{path.absolute()}|{stat.st_size}|{stat.st_mtime_ns}".encode()).hexdigest()
362
+ memo = self.cache_dir / "digest" / key[:2] / key
363
+ if memo.exists():
364
+ return memo.read_text(encoding="utf-8")
365
+ digest = file_digest(path)
366
+ write_atomic(memo, digest)
367
+ return digest
368
+
369
+ def _tmp(self):
370
+ if self.tmp_dir:
371
+ self.tmp_dir.mkdir(parents=True, exist_ok=True)
372
+ return tempfile.TemporaryDirectory(dir=self.tmp_dir)
373
+
374
+ @staticmethod
375
+ def _pdf():
376
+ if pdf is None:
377
+ raise ConversionError(
378
+ "PyMuPDF is needed to convert PDFs and images: pip install opencontracting-nutcracker[pdf]"
379
+ )
380
+ return pdf
nutcracker/__main__.py ADDED
@@ -0,0 +1,37 @@
1
+ """Command-line interface."""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import click
7
+
8
+ from nutcracker import Converter, render
9
+
10
+
11
+ @click.command()
12
+ @click.argument("file", type=click.Path(exists=True, dir_okay=False, path_type=Path))
13
+ @click.argument("parts", nargs=-1, type=click.Path(exists=True, dir_okay=False, path_type=Path))
14
+ @click.option("--no-ocr", is_flag=True, help="Don't OCR pages without a text layer, or images.")
15
+ @click.option("--cache-dir", type=click.Path(file_okay=False, path_type=Path), help="Cache conversions here.")
16
+ @click.option("--ocr-dir", type=click.Path(file_okay=False, path_type=Path), help="Store OCR text here.")
17
+ def main(file, parts, no_ocr, cache_dir, ocr_dir):
18
+ """
19
+ Convert FILE to text, and print it.
20
+
21
+ If FILE is an archive, print each member's text after a "# member" line. If FILE is the entry point of a split
22
+ archive, PARTS are its other volumes. Errors are printed to standard error.
23
+ """
24
+ converter = Converter(cache_dir=cache_dir, ocr_dir=ocr_dir, ocr=not no_ocr)
25
+ data = converter.convert(file, parts)
26
+ for item in data["items"]:
27
+ header = f"# {item['member']}" if item["member"] else None
28
+ click.echo(render(item["pages"], item["flags"], header), nl=False)
29
+ for error in data["errors"]:
30
+ click.echo(f"error: {error}", err=True)
31
+ for skipped in data["skipped"]:
32
+ click.echo(f"skipped: {skipped}", err=True)
33
+ sys.exit(1 if data["errors"] else 0)
34
+
35
+
36
+ if __name__ == "__main__":
37
+ main()