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.
nutcracker/archive.py ADDED
@@ -0,0 +1,166 @@
1
+ """Extract the members of archives, including split and nested archives, and repair their names."""
2
+
3
+ import shutil
4
+ import tempfile
5
+ import zipfile
6
+ from pathlib import Path, PurePosixPath
7
+
8
+ from nutcracker.exceptions import ConversionError
9
+ from nutcracker.util import ARCHIVES, CONVERTIBLE, run, which
10
+
11
+ # Only a guard against filling the disk: skipping a nested archive would lose everything in it.
12
+ MAX_MEMBER_BYTES = 2_000_000_000
13
+ # Archives in Polish tender documents nest at most 4 deep.
14
+ MAX_DEPTH = 5
15
+ POLISH_LETTERS = set("ąćęłńóśźżĄĆĘŁŃÓŚŹŻ")
16
+
17
+
18
+ def seven_zip():
19
+ """Return 7-Zip's command: ``7zz`` (7-Zip's own build), else ``7z`` (p7zip, or 7-Zip on Windows)."""
20
+ return which("7zz", "7z") or "7zz"
21
+
22
+
23
+ def safe_member(name):
24
+ p = PurePosixPath(name.replace("\\", "/"))
25
+ return not p.is_absolute() and ".." not in p.parts
26
+
27
+
28
+ def zip_name(info):
29
+ """Decode a ZIP member's name; ZIPs without the UTF-8 flag are usually from Polish Windows (cp852)."""
30
+ if info.flag_bits & 0x800:
31
+ return info.filename
32
+ try:
33
+ return info.filename.encode("cp437").decode("cp852")
34
+ except UnicodeError:
35
+ return info.filename
36
+
37
+
38
+ def member_title(name):
39
+ """
40
+ Repair a member name stored without the UTF-8 flag, as listed by :func:`zip_name` or :func:`list_7z`.
41
+
42
+ 7-Zip maps each byte it can't decode to U+EF00 + byte; :func:`zip_name` reads UTF-8 names from macOS archivers as
43
+ cp852. The bytes are cp852 in ZIPs from Polish Windows, but ISO-8859-2 or Windows-1250 in names that another tool
44
+ mangled before packing (7z stores names in Unicode): the encoding that yields the most Polish letters wins.
45
+ """
46
+ if any(0xEF80 <= ord(c) <= 0xEFFF for c in name):
47
+ raw = b"".join(bytes([ord(c) - 0xEF00]) if 0xEF80 <= ord(c) <= 0xEFFF else c.encode() for c in name)
48
+ try:
49
+ return raw.decode("utf-8")
50
+ except UnicodeDecodeError:
51
+ decoded = [raw.decode(encoding, "replace") for encoding in ("cp852", "iso-8859-2", "cp1250")]
52
+ return max(decoded, key=lambda s: sum(c in POLISH_LETTERS for c in s))
53
+ try:
54
+ return name.encode("cp852").decode("utf-8")
55
+ except UnicodeError:
56
+ return name
57
+
58
+
59
+ def zip_listing(z):
60
+ """Return ``(name, size, CRC, ZipInfo)`` for each file in a :class:`zipfile.ZipFile`, in directory order."""
61
+ return [
62
+ (zip_name(i), i.file_size, f"{i.CRC:08X}", i)
63
+ for i in z.infolist()
64
+ if not i.is_dir() and not i.filename.endswith("\\") # Windows archivers' directories
65
+ ]
66
+
67
+
68
+ def list_7z(entry):
69
+ """
70
+ List an archive's files with 7-Zip.
71
+
72
+ :returns: a list of ``(name, size, name as listed, CRC)`` and a description of 7-Zip's exit status
73
+ """
74
+ result = run([seven_zip(), "l", "-ba", "-slt", "-pnone", str(entry)])
75
+ members, block = [], {}
76
+ for line in [*result.stdout.decode("utf-8", "replace").splitlines(), ""]:
77
+ if not line.strip():
78
+ if block.get("Path") and block.get("Folder") != "+":
79
+ members.append((block["Path"], int(block.get("Size") or 0), block["Path"], block.get("CRC") or ""))
80
+ block = {}
81
+ elif " = " in line:
82
+ key, value = line.split(" = ", 1)
83
+ block[key] = value
84
+ return members, f"7zz exit {result.returncode}"
85
+
86
+
87
+ def wanted_member(name, size, state, prefix):
88
+ base = PurePosixPath(name.replace("\\", "/")).name
89
+ suffix = PurePosixPath(base).suffix.lower()
90
+ if not safe_member(name):
91
+ state["errors"].append(f"{prefix}{name}: unsafe path")
92
+ elif base.startswith(("~$", "._")) or "__MACOSX/" in name:
93
+ pass
94
+ elif suffix not in CONVERTIBLE and suffix not in ARCHIVES:
95
+ state["skipped"].append(f"{prefix}{name}")
96
+ elif size > MAX_MEMBER_BYTES:
97
+ state["errors"].append(f"{prefix}{name}: over {MAX_MEMBER_BYTES // 1_000_000} MB")
98
+ else:
99
+ return True
100
+ return False
101
+
102
+
103
+ def extract_members(entry, out, state, prefix, split):
104
+ """Extract the wanted members of an archive as out/<n><suffix>, returning (display name, path) pairs."""
105
+ if entry.suffix.lower() == ".zip" and not split:
106
+ try:
107
+ with zipfile.ZipFile(entry) as z:
108
+ infos = [i for i in z.infolist() if not i.is_dir()]
109
+ pairs = []
110
+ for n, info in enumerate(infos):
111
+ name = zip_name(info)
112
+ if not wanted_member(name, info.file_size, state, prefix):
113
+ continue
114
+ path = out / f"{n}{PurePosixPath(name).suffix.lower()}"
115
+ try:
116
+ with z.open(info) as src, path.open("wb") as dst:
117
+ shutil.copyfileobj(src, dst)
118
+ except (RuntimeError, NotImplementedError, zipfile.BadZipFile, OSError) as e:
119
+ state["errors"].append(f"{prefix}{name}: {type(e).__name__}: {e}"[:300])
120
+ continue
121
+ pairs.append((name, path))
122
+ return pairs
123
+ except (zipfile.BadZipFile, NotImplementedError, OSError):
124
+ pass # e.g. Deflate64 or a damaged directory: let 7-Zip try
125
+ members, error = list_7z(entry)
126
+ if not members:
127
+ state["errors"].append(f"{prefix or entry.name}: unreadable archive ({error})")
128
+ return []
129
+ wanted = [(name, raw) for name, size, raw, _ in members if wanted_member(name, size, state, prefix)]
130
+ if not wanted:
131
+ return []
132
+ listfile = out / ".members"
133
+ listfile.write_text("\n".join(raw for _, raw in wanted), encoding="utf-8")
134
+ target = out / ".x"
135
+ command = [seven_zip(), "x", "-y", "-bd", "-pnone", "-spd", f"-o{target}", str(entry), f"@{listfile}"]
136
+ result = run(command, timeout=1800)
137
+ if result.returncode:
138
+ # 7-Zip can't decompress RAR 7's compression method; The Unarchiver can.
139
+ try:
140
+ fallback = run(["unar", "-q", "-f", "-D", "-p", "none", "-o", str(target), str(entry)], timeout=1800)
141
+ unar = f"unar exit {fallback.returncode}" if fallback.returncode else None
142
+ except ConversionError as e:
143
+ unar = str(e)
144
+ if unar:
145
+ state["errors"].append(f"{prefix or entry.name}: 7zz exit {result.returncode}, {unar}")
146
+ pairs = []
147
+ for n, (name, raw) in enumerate(wanted):
148
+ extracted = target / raw
149
+ if extracted.is_file():
150
+ path = out / f"{n}{PurePosixPath(name).suffix.lower()}"
151
+ extracted.rename(path)
152
+ pairs.append((name, path))
153
+ return pairs
154
+
155
+
156
+ def expand_archive(entry, tmp, state, depth, prefix, *, split=False):
157
+ """Yield (member name, path) for convertible members, recursing into nested archives."""
158
+ out = Path(tempfile.mkdtemp(dir=tmp))
159
+ for name, path in extract_members(entry, out, state, prefix, split):
160
+ if path.suffix.lower() in ARCHIVES:
161
+ if depth < MAX_DEPTH:
162
+ yield from expand_archive(path, tmp, state, depth + 1, f"{prefix}{name}/")
163
+ else:
164
+ state["errors"].append(f"{prefix}{name}: nested too deep")
165
+ else:
166
+ yield f"{prefix}{name}", path
@@ -0,0 +1,9 @@
1
+ """Exceptions raised by this package."""
2
+
3
+
4
+ class NutcrackerError(Exception):
5
+ """Base class for exceptions from within this package."""
6
+
7
+
8
+ class ConversionError(NutcrackerError):
9
+ """Raised if a converter fails, or isn't installed."""
nutcracker/pdf.py ADDED
@@ -0,0 +1,207 @@
1
+ """Convert PDFs and images, with OCR. This module requires the ``pdf`` extra (PyMuPDF)."""
2
+
3
+ import functools
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import warnings
8
+ from pathlib import Path
9
+
10
+ # PyMuPDF warns on import (its SWIG bindings crash if the warning is an error, as with -W error).
11
+ with warnings.catch_warnings():
12
+ warnings.simplefilter("ignore", DeprecationWarning)
13
+ import pymupdf
14
+
15
+ from nutcracker.util import WORD_RE, file_digest, run, words
16
+
17
+ # A text layer under this many characters counts as none.
18
+ MIN_PAGE_CHARS = 40
19
+ # A page covered by one image whose text layer is under this many characters is a scan under a stamp (an e-signature
20
+ # box, a filing number), so it is OCR'd too, and the text with more words is kept.
21
+ THIN_LAYER_CHARS = 400
22
+ # OCR output with fewer words than this is from a blank page or a photo.
23
+ MIN_OCR_WORDS = 3
24
+ # Pages larger than A3 (1191 pt) are drawings or maps, which aren't worth OCR.
25
+ DRAWING_POINTS = 1300
26
+ # Part of the OCR store's key, with the tools' versions: bump it when the resolution or the steps change.
27
+ # 1: Tesseract with the Polish model, 300 dpi greyscale, both readings when orientation detection suggests a rotation.
28
+ OCR_VERSION = 1
29
+
30
+
31
+ @functools.cache
32
+ def ocr_tools():
33
+ """
34
+ Return the OCR store's folder name and the tools that shape OCR output.
35
+
36
+ The folder name is OCR_VERSION and a digest of the tools: Tesseract and Leptonica (by version), the Polish and
37
+ orientation models (by content) and MuPDF, which renders the pages. Other versions give other text.
38
+
39
+ The folder name must stay the same for the same tools, so that existing OCR stores remain valid.
40
+ """
41
+ version = run(["tesseract", "--version"]).stdout.decode().splitlines()[:2]
42
+ tessdata = re.search(r'"(.+?)"', run(["tesseract", "--list-langs"]).stdout.decode())[1]
43
+ models = [file_digest(Path(tessdata) / f"{lang}.traineddata") for lang in ("pol", "osd")]
44
+ tools = {"tesseract": [line.strip() for line in version], "models": models, "mupdf": pymupdf.VersionFitz}
45
+ return f"v{OCR_VERSION}-{hashlib.sha256(json.dumps(tools).encode()).hexdigest()[:12]}", tools
46
+
47
+
48
+ def render_page(page, png, rotate=0):
49
+ """Render a page at 300 dpi in greyscale (at most 6,000 pixels long, for large images), rotated clockwise."""
50
+ scale = min(300 / 72, 6000 / max(page.rect.width, page.rect.height))
51
+ page.get_pixmap(matrix=pymupdf.Matrix(scale, scale).prerotate(rotate), colorspace=pymupdf.csGRAY).save(png)
52
+
53
+
54
+ def rotation(png):
55
+ """Return the clockwise rotation, in degrees, that Tesseract's orientation detection gives a rendered page."""
56
+ osd = run(["tesseract", str(png), "-", "--psm", "0"], timeout=300).stdout.decode("utf-8", "replace")
57
+ rotate = re.search(r"Rotate: (\d+)", osd)
58
+ confidence = re.search(r"Orientation confidence: ([\d.]+)", osd)
59
+ return int(rotate[1]) if rotate and confidence and float(confidence[1]) > 2 else 0
60
+
61
+
62
+ def tesseract(png, tmp):
63
+ """Return a rendered page's text and its confidence: the sum of the confidences (0-1) of its words."""
64
+ run(["tesseract", str(png), str(tmp / "ocr"), "-l", "pol", "txt", "tsv"], timeout=300)
65
+ confidence = 0.0
66
+ for line in (tmp / "ocr.tsv").read_text(encoding="utf-8", errors="replace").splitlines()[1:]:
67
+ fields = line.split("\t")
68
+ if len(fields) == 12 and float(fields[10]) > 0 and WORD_RE.search(fields[11]):
69
+ confidence += float(fields[10]) / 100
70
+ return (tmp / "ocr.txt").read_text(encoding="utf-8", errors="replace"), confidence
71
+
72
+
73
+ def ocr_page(page, tmp):
74
+ """Return the OCR text of a page."""
75
+ png = tmp / "page.png"
76
+ render_page(page, png)
77
+ text, confidence = tesseract(png, tmp)
78
+ # Tesseract reads a rotated page as garbage (7 of 60 sampled pages without a text layer were rotated), but its
79
+ # orientation detection also turns upright pages, so the reading Tesseract is more confident of is kept.
80
+ if rotate := rotation(png):
81
+ render_page(page, png, rotate)
82
+ rotated, rotated_confidence = tesseract(png, tmp)
83
+ if rotated_confidence > confidence:
84
+ text = rotated
85
+ return text
86
+
87
+
88
+ def ocr_pages(path, indexes, tmp):
89
+ """Return ``{page index: OCR text}`` for pages of a PDF or image."""
90
+ with pymupdf.open(path) as doc:
91
+ return {i: ocr_page(doc[i], tmp) for i in indexes}
92
+
93
+
94
+ def covered_by_image(page):
95
+ area = page.rect.width * page.rect.height
96
+ return any(abs(pymupdf.Rect(info["bbox"]) & page.rect) > 0.85 * area for info in page.get_image_info())
97
+
98
+
99
+ def strike_lines(page):
100
+ """Return (x0, x1, y) of each horizontal line or hairline drawn on the page, and of each strike-out annotation."""
101
+ lines = []
102
+ for drawing in page.get_drawings():
103
+ for item in drawing["items"]:
104
+ if item[0] == "l":
105
+ p, q = item[1], item[2]
106
+ if abs(p.y - q.y) < 1 and abs(q.x - p.x) > 2:
107
+ lines.append((min(p.x, q.x), max(p.x, q.x), (p.y + q.y) / 2))
108
+ elif item[0] == "re" and item[1].height < 2 and item[1].width > 2:
109
+ lines.append((item[1].x0, item[1].x1, (item[1].y0 + item[1].y1) / 2))
110
+ lines.extend(
111
+ (a.rect.x0, a.rect.x1, (a.rect.y0 + a.rect.y1) / 2) for a in page.annots() or [] if a.type[1] == "StrikeOut"
112
+ )
113
+ return lines
114
+
115
+
116
+ def wordlike(word):
117
+ """Return whether a word can be struck through: not punctuation, a formula (with fraction bars) or a footer."""
118
+ if word == "Page" or not any(ch.isalnum() for ch in word):
119
+ return False
120
+ # Mathematical alphanumerics, and the asterisk operator, summation and square root.
121
+ return not any(0x1D400 <= ord(ch) <= 0x1D7FF or ord(ch) in {0x2217, 0x2211, 0x221A} for ch in word)
122
+
123
+
124
+ def struck_text(page):
125
+ """Return the page's text with struck-through words wrapped in "[skreślono: …]", or None if none are struck."""
126
+ if max(page.rect.width, page.rect.height) > DRAWING_POINTS or not (lines := strike_lines(page)):
127
+ return None
128
+
129
+ # A strike crosses the middle of a word; an underline sits below it.
130
+ def struck(x0, y0, x1, y1):
131
+ h = y1 - y0
132
+ return any(
133
+ y0 + 0.3 * h <= y <= y1 - 0.25 * h and min(x1, lx1) - max(x0, lx0) >= 0.6 * (x1 - x0)
134
+ for lx0, lx1, y in lines
135
+ )
136
+
137
+ # Rotated text (e.g. levels on a drawing) is crossed by the drawing's horizontal lines, not struck through.
138
+ rotated = [
139
+ pymupdf.Rect(line["bbox"])
140
+ for block in page.get_text("dict")["blocks"]
141
+ for line in block.get("lines", [])
142
+ if abs(line["dir"][1]) > 0.1
143
+ ]
144
+
145
+ def upright(x0, y0, x1, y1):
146
+ centre = pymupdf.Point((x0 + x1) / 2, (y0 + y1) / 2)
147
+ return not any(centre in r for r in rotated)
148
+
149
+ words = page.get_text("words", sort=False)
150
+ flags = [upright(*w[:4]) and struck(*w[:4]) and wordlike(w[4]) for w in words]
151
+ if not any(flags):
152
+ return None
153
+ out, line, open_ = [], None, False
154
+ for w, flag in zip(words, flags, strict=True):
155
+ if line is not None and (w[5], w[6]) != line:
156
+ out.append("\n\n" if w[5] != line[0] else "\n")
157
+ elif line is not None:
158
+ out.append(" ")
159
+ if flag and not open_:
160
+ out.append("[skreślono: ")
161
+ elif not flag and open_:
162
+ out[-1:] = ["]", out[-1]]
163
+ out.append(w[4])
164
+ open_, line = flag, (w[5], w[6])
165
+ return "".join(out) + ("]" if open_ else "") + "\n"
166
+
167
+
168
+ def convert_pdf(path, tmp, ocr_texts):
169
+ """Convert a PDF, OCR'ing pages without a text layer with ``ocr_texts``, unless it's ``None``."""
170
+ with pymupdf.open(path) as pdf:
171
+ layers = [page.get_text() for page in pdf]
172
+ big = [max(page.rect.width, page.rect.height) > DRAWING_POINTS for page in pdf]
173
+ # Every page without a text layer up to A3 is OCR'd, with no budget and no skip test: most such pages are scans
174
+ # holding text, and tests for blanks and drawings also skipped faint scans and text drawn as outlines.
175
+ wanted = [
176
+ i
177
+ for i, (text, page) in enumerate(zip(layers, pdf, strict=True))
178
+ if ocr_texts
179
+ and not big[i]
180
+ and (
181
+ len(text.strip()) < MIN_PAGE_CHARS or (len(text.strip()) < THIN_LAYER_CHARS and covered_by_image(page))
182
+ )
183
+ ]
184
+ ocr = ocr_texts(path, pdf, wanted, tmp) if ocr_texts else {}
185
+ pages, flags = [], []
186
+ for i, (layer, page) in enumerate(zip(layers, pdf, strict=True)):
187
+ text, flag = layer, ""
188
+ if i in ocr and words(ocr[i]) >= MIN_OCR_WORDS and words(ocr[i]) > words(layer):
189
+ text, flag = ocr[i], "ocr"
190
+ elif len(layer.strip()) < MIN_PAGE_CHARS:
191
+ flag = "drawing" if big[i] else "no text"
192
+ else:
193
+ text = struck_text(page) or layer
194
+ pages.append(text)
195
+ flags.append(flag)
196
+ return pages, flags
197
+
198
+
199
+ def convert_image(path, tmp, ocr_texts):
200
+ """Convert an image with ``ocr_texts``, unless it's ``None``."""
201
+ with pymupdf.open(path) as doc:
202
+ ocr = ocr_texts(path, doc, list(range(len(doc))), tmp) if ocr_texts else {}
203
+ texts = [ocr.get(i, "") for i in range(len(doc))]
204
+ return (
205
+ [text if words(text) >= MIN_OCR_WORDS else "" for text in texts],
206
+ ["ocr" if words(text) >= MIN_OCR_WORDS else "no text" for text in texts],
207
+ )
nutcracker/util.py ADDED
@@ -0,0 +1,57 @@
1
+ """Helpers, and the formats that this package converts."""
2
+
3
+ import hashlib
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+
8
+ from nutcracker.exceptions import ConversionError
9
+
10
+ ARCHIVES = {".zip", ".7z", ".rar", ".001"}
11
+ #: Images are OCR'd like pages without a text layer.
12
+ IMAGES = {".jpg", ".jpeg", ".png", ".tif", ".tiff", ".bmp"}
13
+ #: The suffixes of the files that :meth:`nutcracker.Converter.convert` converts, other than archives.
14
+ CONVERTIBLE = {".pdf", ".docx", ".docm", ".doc", ".rtf", ".odt", ".xlsx", ".xlsm", ".xls", ".ods", ".html", ".htm"}
15
+ CONVERTIBLE |= {".xml", ".txt", ".pptx"} | IMAGES
16
+
17
+ WORD_RE = re.compile(r"[^\W\d_]{3,}")
18
+
19
+
20
+ def run(args, timeout=600, **kwargs):
21
+ """Run a command and return its result, or raise :class:`~nutcracker.exceptions.ConversionError` if missing."""
22
+ try:
23
+ return subprocess.run( # noqa: S603 # converters called in this package
24
+ args, capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL, check=False, **kwargs
25
+ )
26
+ except FileNotFoundError as e:
27
+ raise ConversionError(f"{args[0]} is not installed") from e
28
+
29
+
30
+ def which(*commands):
31
+ """Return the first of the commands that is installed, or ``None``."""
32
+ return next((command for command in commands if shutil.which(command)), None)
33
+
34
+
35
+ def words(text):
36
+ """Return the number of words of three or more letters."""
37
+ return len(WORD_RE.findall(text))
38
+
39
+
40
+ def file_digest(path):
41
+ """Return a file's SHA-256 as a hexadecimal string."""
42
+ digest = hashlib.sha256()
43
+ with path.open("rb") as f:
44
+ while chunk := f.read(1 << 20):
45
+ digest.update(chunk)
46
+ return digest.hexdigest()
47
+
48
+
49
+ def link(source, destination):
50
+ """Make ``destination`` a symbolic link to ``source``, or a hard link or copy if symbolic links are disallowed."""
51
+ try:
52
+ destination.symlink_to(source.absolute())
53
+ except OSError:
54
+ try:
55
+ destination.hardlink_to(source)
56
+ except OSError:
57
+ shutil.copyfile(source, destination)