md4kb 0.1.0__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.
Files changed (98) hide show
  1. md4kb/__init__.py +1 -0
  2. md4kb/__main__.py +6 -0
  3. md4kb/app/__init__.py +4 -0
  4. md4kb/app/archives.py +380 -0
  5. md4kb/app/cache.py +151 -0
  6. md4kb/app/embedded.py +66 -0
  7. md4kb/app/files.py +156 -0
  8. md4kb/app/files_folder.py +69 -0
  9. md4kb/app/markdown.py +73 -0
  10. md4kb/app/programs.py +68 -0
  11. md4kb/app/readers.py +258 -0
  12. md4kb/app/run.py +381 -0
  13. md4kb/app/settings.py +166 -0
  14. md4kb/app/sources.py +290 -0
  15. md4kb/app/state.py +231 -0
  16. md4kb/app/supervised.py +106 -0
  17. md4kb/app/supervisor.py +348 -0
  18. md4kb/app/unpack.py +400 -0
  19. md4kb/app/worker.py +358 -0
  20. md4kb/cli/__init__.py +5 -0
  21. md4kb/cli/main.py +266 -0
  22. md4kb/cli/manifest.py +179 -0
  23. md4kb/cli/output.py +213 -0
  24. md4kb/core/__init__.py +4 -0
  25. md4kb/core/charts.py +35 -0
  26. md4kb/core/drawings.py +42 -0
  27. md4kb/core/embedded.py +190 -0
  28. md4kb/core/events.py +92 -0
  29. md4kb/core/front_matter.py +212 -0
  30. md4kb/core/gateway.py +37 -0
  31. md4kb/core/kinds.py +276 -0
  32. md4kb/core/markers.py +34 -0
  33. md4kb/core/model.py +227 -0
  34. md4kb/core/number_formats.py +367 -0
  35. md4kb/core/office.py +342 -0
  36. md4kb/core/parts.py +151 -0
  37. md4kb/core/protocol.py +144 -0
  38. md4kb/core/status.py +83 -0
  39. md4kb/core/symbols.py +327 -0
  40. md4kb/core/up_to_date.py +177 -0
  41. md4kb/readers/__init__.py +1 -0
  42. md4kb/readers/diagram.py +376 -0
  43. md4kb/readers/diagram_nets.py +67 -0
  44. md4kb/readers/docling.py +400 -0
  45. md4kb/readers/drawings.py +191 -0
  46. md4kb/readers/drawio.py +240 -0
  47. md4kb/readers/drawio_cells.py +100 -0
  48. md4kb/readers/drawio_page.py +16 -0
  49. md4kb/readers/dxf.py +157 -0
  50. md4kb/readers/embedded.py +275 -0
  51. md4kb/readers/formulas.py +261 -0
  52. md4kb/readers/furniture.py +105 -0
  53. md4kb/readers/gateway.py +393 -0
  54. md4kb/readers/images.py +199 -0
  55. md4kb/readers/kept_files.py +58 -0
  56. md4kb/readers/libreoffice.py +290 -0
  57. md4kb/readers/links.py +366 -0
  58. md4kb/readers/markdown.py +400 -0
  59. md4kb/readers/metafiles.py +273 -0
  60. md4kb/readers/netlist.py +321 -0
  61. md4kb/readers/netlist_tables.py +91 -0
  62. md4kb/readers/office.py +361 -0
  63. md4kb/readers/office_links.py +230 -0
  64. md4kb/readers/ooxml.py +324 -0
  65. md4kb/readers/packages.py +64 -0
  66. md4kb/readers/pages.py +124 -0
  67. md4kb/readers/picture_labels.py +122 -0
  68. md4kb/readers/pool.py +113 -0
  69. md4kb/readers/record.py +69 -0
  70. md4kb/readers/recordings.py +276 -0
  71. md4kb/readers/scanned.py +251 -0
  72. md4kb/readers/scans.py +224 -0
  73. md4kb/readers/shapes.py +46 -0
  74. md4kb/readers/sheet_links.py +109 -0
  75. md4kb/readers/sheet_objects.py +159 -0
  76. md4kb/readers/slide_diagrams.py +330 -0
  77. md4kb/readers/slide_frames.py +146 -0
  78. md4kb/readers/slide_furniture.py +259 -0
  79. md4kb/readers/slide_gaps.py +285 -0
  80. md4kb/readers/slide_order.py +125 -0
  81. md4kb/readers/slide_shapes.py +338 -0
  82. md4kb/readers/slide_texts.py +130 -0
  83. md4kb/readers/slots.py +58 -0
  84. md4kb/readers/speech.py +206 -0
  85. md4kb/readers/spreadsheet.py +202 -0
  86. md4kb/readers/symbols.py +206 -0
  87. md4kb/readers/table_pictures.py +129 -0
  88. md4kb/readers/tables.py +375 -0
  89. md4kb/readers/texts.py +165 -0
  90. md4kb/readers/together.py +81 -0
  91. md4kb/readers/visio.py +105 -0
  92. md4kb/readers/vision.py +400 -0
  93. md4kb/readers/vlm.py +170 -0
  94. md4kb-0.1.0.dist-info/METADATA +118 -0
  95. md4kb-0.1.0.dist-info/RECORD +98 -0
  96. md4kb-0.1.0.dist-info/WHEEL +4 -0
  97. md4kb-0.1.0.dist-info/entry_points.txt +2 -0
  98. md4kb-0.1.0.dist-info/licenses/LICENSE +21 -0
md4kb/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """md4kb: turn documents into Markdown files next to them."""
md4kb/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Run md4kb as `python -m md4kb`, the way callers start it."""
2
+
3
+ from md4kb.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
md4kb/app/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """The run: supervisor, workers, cache, state and settings.
2
+
3
+ Imports `md4kb.core` and `md4kb.readers`.
4
+ """
md4kb/app/archives.py ADDED
@@ -0,0 +1,380 @@
1
+ """Reading archives with libarchive (conversion.md, "Archives"): a listing
2
+ that refuses unsafe members and finds encrypted archives before anything
3
+ is unpacked, then the members streamed one at a time into a temporary
4
+ folder, within caps on the total size, the member count and the
5
+ compression ratio that one archive shares across all its levels.
6
+
7
+ libarchive is imported only inside the functions that read, so a run that
8
+ meets no archive never loads it; without it an archive waits for a run
9
+ that has it (`needs_program`).
10
+ """
11
+
12
+ import contextlib
13
+ import ctypes
14
+ import hashlib
15
+ import re
16
+ import shutil
17
+ import tempfile
18
+ from collections.abc import Generator, Iterable, Iterator
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path, PurePosixPath
21
+ from typing import Any
22
+
23
+ from md4kb.core.protocol import MissingProgramError
24
+
25
+ # How many members one archive may hold, across all its levels. Each member
26
+ # is a job of its own; a bundle of documents holds dozens to hundreds.
27
+ MAX_MEMBERS = 10_000
28
+ # How many bytes one archive may unpack, across all its levels: far beyond
29
+ # the CAD and document bundles found so far, and still within a laptop's
30
+ # disk.
31
+ MAX_TOTAL_SIZE = 4 << 30
32
+ # How many times its own size an archive may unpack to, across all its
33
+ # levels. Documents compress by 2 to 10 and plain text by up to 20, while
34
+ # a zip bomb reaches a thousand and more.
35
+ MAX_RATIO = 100
36
+ # What any archive may unpack to whatever its ratio, so that a small zip of
37
+ # a long log or a padded firmware image is not taken for a bomb.
38
+ RATIO_FLOOR = 64 << 20
39
+ # The library that reads archives, and what its error says to install.
40
+ LIBRARY = "libarchive"
41
+ NEEDED_FOR = "for archives (install libarchive)"
42
+ # Archives inside archives are opened up to this level; the archive md4kb
43
+ # is given is level one.
44
+ MAX_LEVELS = 3
45
+
46
+ # Bytes read from libarchive at a time.
47
+ BLOCK = 1 << 16
48
+ # What a single compressed file (`report.pdf.gz`) loses from its name to
49
+ # give its one member's.
50
+ COMPRESSION_SUFFIXES = (".gz", ".bz2", ".xz", ".zst", ".lz", ".lzma", ".z")
51
+ # A Windows drive at the start of a member's path, such as `C:`.
52
+ DRIVE = re.compile(r"^[A-Za-z]:")
53
+ # The formats libarchive reads archives of; its catch-all would add mtree,
54
+ # which takes plain text for a file list.
55
+ FORMATS = (
56
+ "7zip",
57
+ "ar",
58
+ "cab",
59
+ "cpio",
60
+ "iso9660",
61
+ "lha",
62
+ "rar",
63
+ "rar5",
64
+ "tar",
65
+ "xar",
66
+ "zip",
67
+ )
68
+ # Words libarchive uses when it cannot read an encrypted archive or member.
69
+ ENCRYPTED_WORDS = ("passphrase", "encrypt")
70
+
71
+
72
+ class ArchiveError(Exception):
73
+ """An archive md4kb cannot unpack; the message says why."""
74
+
75
+
76
+ class EncryptedError(ArchiveError):
77
+ """An encrypted archive: listed, not opened."""
78
+
79
+
80
+ class CapError(ArchiveError):
81
+ """An archive over one of the caps."""
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class Caps:
86
+ """The caps one archive shares across all its levels."""
87
+
88
+ members: int = MAX_MEMBERS
89
+ size: int = MAX_TOTAL_SIZE
90
+ ratio: int = MAX_RATIO
91
+ floor: int = RATIO_FLOOR
92
+
93
+
94
+ class Budget:
95
+ """What one archive md4kb is given may still unpack, across all its
96
+ levels: members counted from the listings, bytes declared in them and
97
+ bytes actually written."""
98
+
99
+ def __init__(self, archive_size: int, caps: Caps | None = None) -> None:
100
+ self.caps = caps or Caps()
101
+ by_ratio = max(self.caps.floor, self.caps.ratio * archive_size)
102
+ self.limit = min(self.caps.size, by_ratio)
103
+ self.members = 0
104
+ self.declared = 0
105
+ self.written = 0
106
+
107
+ def count(self) -> None:
108
+ self.members += 1
109
+ if self.members > self.caps.members:
110
+ raise CapError(f"over the cap of {self.caps.members} members")
111
+
112
+ def declare(self, size: int) -> None:
113
+ self.declared += size
114
+ if self.declared > self.limit:
115
+ raise CapError(f"its members declare {self._over()}")
116
+
117
+ def take(self, size: int) -> None:
118
+ self.written += size
119
+ if self.written > self.limit:
120
+ raise CapError(f"it unpacks to {self._over()}")
121
+
122
+ def _over(self) -> str:
123
+ return (
124
+ f"more than {self.limit >> 20} MiB, the cap of {self.caps.ratio} times "
125
+ f"its size (at least {self.caps.floor >> 20} MiB, at most "
126
+ f"{self.caps.size >> 20} MiB)"
127
+ )
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class Refused:
132
+ """A member that is not unpacked, with the reason."""
133
+
134
+ path: str
135
+ reason: str
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class Listing:
140
+ """What an archive's listing holds: the members that will be unpacked,
141
+ in order, and those refused."""
142
+
143
+ members: list[str] = field(default_factory=list)
144
+ refused: list[Refused] = field(default_factory=list)
145
+
146
+
147
+ @dataclass(frozen=True)
148
+ class Unpacked:
149
+ """A member written to a temporary file of its own, named as the member
150
+ is, with its fingerprint."""
151
+
152
+ path: str # its path in the archive
153
+ file: Path
154
+ fingerprint: str
155
+
156
+ def remove(self) -> None:
157
+ shutil.rmtree(self.file.parent, ignore_errors=True)
158
+
159
+
160
+ def member_path(name: str | None) -> tuple[str | None, str | None]:
161
+ """A member's path with `.` parts and slashes tidied, and the reason it
162
+ is refused: `(path, None)`, `(None, reason)`, or `(None, None)` for the
163
+ archive's own top folder."""
164
+ if not name:
165
+ return None, "it has no name"
166
+ name = name.replace("\\", "/")
167
+ if name.startswith("/") or DRIVE.match(name):
168
+ return None, "absolute path"
169
+ parts = [part for part in name.split("/") if part not in ("", ".")]
170
+ if ".." in parts:
171
+ return None, "`..` in its path"
172
+ return ("/".join(parts) or None), None
173
+
174
+
175
+ def hidden(path: str) -> bool:
176
+ """Hidden files and folders and lock files, which are never sources."""
177
+ parts = PurePosixPath(path).parts
178
+ return any(part.startswith(".") for part in parts) or parts[-1].startswith("~$")
179
+
180
+
181
+ def listing(archive: Path, budget: Budget) -> Listing:
182
+ """Read an archive's headers, without its data: the members to unpack
183
+ and those refused. `EncryptedError` when a member is encrypted,
184
+ `CapError` over the member count or the declared size, `ArchiveError`
185
+ when libarchive cannot read it."""
186
+ found = Listing()
187
+ seen: set[str] = set()
188
+ with _reading(archive) as (reader, rename):
189
+ for entry in _entries(reader):
190
+ budget.count()
191
+ if _encrypted(entry):
192
+ raise EncryptedError("encrypted")
193
+ path, refusal = _check(entry, rename, seen)
194
+ if refusal is not None:
195
+ found.refused.append(Refused(path or str(_name(entry)), refusal))
196
+ elif path is not None:
197
+ found.members.append(path)
198
+ budget.declare(entry.size or 0)
199
+ return found
200
+
201
+
202
+ def unpack(archive: Path, scratch: Path, budget: Budget) -> Iterator[Unpacked]:
203
+ """Stream the members a listing accepts one at a time, each into a new
204
+ folder under `scratch`; the caller removes each when done with it.
205
+ `CapError` once the bytes written pass the budget."""
206
+ seen: set[str] = set()
207
+ with _reading(archive) as (reader, rename):
208
+ for entry in _entries(reader):
209
+ path, refusal = _check(entry, rename, seen)
210
+ if path is None or refusal is not None:
211
+ continue
212
+ folder = Path(tempfile.mkdtemp(dir=scratch))
213
+ unpacked = Unpacked(path, folder / PurePosixPath(path).name, "")
214
+ try:
215
+ digest = write(_blocks(entry), unpacked.file, budget)
216
+ except BaseException:
217
+ unpacked.remove()
218
+ raise
219
+ yield Unpacked(path, unpacked.file, digest)
220
+
221
+
222
+ def write(blocks: Iterable[bytes], file: Path, budget: Budget) -> str:
223
+ """Write a member's blocks to `file` within the `budget`; the member's
224
+ fingerprint."""
225
+ digest = hashlib.sha256()
226
+ with file.open("wb") as out:
227
+ for block in blocks:
228
+ budget.take(len(block))
229
+ digest.update(block)
230
+ out.write(block)
231
+ return digest.hexdigest()
232
+
233
+
234
+ def _name(entry: Any) -> str | None:
235
+ """A member's name. libarchive-c gives one that is not UTF-8 as bytes;
236
+ it is read as CP437, which a ZIP's names are in unless it says UTF-8,
237
+ and which has a character for every byte."""
238
+ name = entry.pathname
239
+ return name.decode("cp437") if isinstance(name, bytes) else name
240
+
241
+
242
+ def _check(
243
+ entry: Any, rename: str | None, seen: set[str]
244
+ ) -> tuple[str | None, str | None]:
245
+ """A member's path, or the reason it is refused; `(None, None)` for
246
+ folders, hidden files and lock files, which are left out silently."""
247
+ name = rename if rename is not None else _name(entry)
248
+ path, refusal = member_path(name)
249
+ if refusal is not None:
250
+ return None, refusal
251
+ if entry.isdir or path is None:
252
+ return None, None
253
+ if entry.issym:
254
+ return path, "symbolic link"
255
+ if entry.islnk:
256
+ return path, "hard link"
257
+ if entry.isdev:
258
+ return path, "device file"
259
+ if not entry.isreg:
260
+ return path, "not a regular file"
261
+ if hidden(path):
262
+ return None, None
263
+ if path in seen:
264
+ return path, "it appears twice in the archive"
265
+ seen.add(path)
266
+ return path, None
267
+
268
+
269
+ @contextlib.contextmanager
270
+ def _reading(archive: Path) -> Generator[tuple[Any, str | None]]:
271
+ """An open libarchive reader, and the name of a single compressed
272
+ file's one member (libarchive's `raw` format calls it `data`)."""
273
+ libarchive, ffi = _libarchive()
274
+ pointer = ffi.read_new()
275
+ try:
276
+ ffi.read_support_filter_all(pointer)
277
+ for name in FORMATS:
278
+ ffi.get_read_format_function(name)(pointer)
279
+ # Last, so that every real format bids first; only a compressed
280
+ # stream is taken for a single file (below).
281
+ ffi.read_support_format_raw(pointer)
282
+ with _translated():
283
+ ffi.read_open_filename_w(pointer, str(archive), BLOCK)
284
+ reader = libarchive.read.ArchiveRead(pointer)
285
+ rename = None
286
+ entries = _entries(reader)
287
+ first = next(entries, None)
288
+ if reader.format_name in ("raw", b"raw"):
289
+ if not reader.filter_names:
290
+ raise ArchiveError("not an archive libarchive can read")
291
+ rename = _single_name(archive.name)
292
+ yield _Replay(first, entries), rename
293
+ finally:
294
+ ffi.read_free(pointer)
295
+
296
+
297
+ class _Replay:
298
+ """The entries of a reader whose first entry was already read."""
299
+
300
+ def __init__(self, first: Any, rest: Iterator[Any]) -> None:
301
+ self._first = first
302
+ self._rest = rest
303
+
304
+ def __iter__(self) -> Iterator[Any]:
305
+ if self._first is not None:
306
+ yield self._first
307
+ yield from self._rest
308
+
309
+
310
+ def _entries(reader: Any) -> Iterator[Any]:
311
+ """A reader's entries, with libarchive's errors as `ArchiveError`."""
312
+ iterator = iter(reader)
313
+ while True:
314
+ with _translated():
315
+ entry = next(iterator, None)
316
+ if entry is None:
317
+ return
318
+ yield entry
319
+
320
+
321
+ def _blocks(entry: Any) -> Iterator[bytes]:
322
+ iterator = entry.get_blocks(BLOCK)
323
+ while True:
324
+ with _translated():
325
+ block = next(iterator, None)
326
+ if block is None:
327
+ return
328
+ yield block
329
+
330
+
331
+ @contextlib.contextmanager
332
+ def _translated() -> Generator[None]:
333
+ """libarchive's errors as `ArchiveError`, or `EncryptedError` when they
334
+ say a passphrase is needed."""
335
+ libarchive, _ = _libarchive()
336
+ try:
337
+ yield
338
+ except libarchive.ArchiveError as error:
339
+ message = str(getattr(error, "msg", "") or error)
340
+ if any(word in message.lower() for word in ENCRYPTED_WORDS):
341
+ raise EncryptedError("encrypted") from error
342
+ raise ArchiveError(f"libarchive: {message}") from error
343
+
344
+
345
+ def _single_name(name: str) -> str:
346
+ lower = name.lower()
347
+ for suffix in COMPRESSION_SUFFIXES:
348
+ if lower.endswith(suffix) and len(name) > len(suffix):
349
+ return name[: -len(suffix)]
350
+ return name
351
+
352
+
353
+ def _libarchive() -> tuple[Any, Any]:
354
+ """libarchive-c and its `ffi` module, whose functions it makes at run
355
+ time, so that type checkers cannot see them; `MissingProgramError` when
356
+ the library cannot be loaded."""
357
+ try:
358
+ import libarchive
359
+ from libarchive import ffi
360
+ except (ImportError, OSError, AttributeError) as error:
361
+ raise MissingProgramError(LIBRARY, NEEDED_FOR) from error
362
+ return libarchive, ffi
363
+
364
+
365
+ _IS_ENCRYPTED: Any = None
366
+
367
+
368
+ def _encrypted(entry: Any) -> bool:
369
+ """Whether libarchive marks a member's data or metadata encrypted."""
370
+ global _IS_ENCRYPTED
371
+ if _IS_ENCRYPTED is None:
372
+ _, ffi = _libarchive()
373
+ function: Any = getattr(ffi.libarchive, "archive_entry_is_encrypted", None)
374
+ if function is not None:
375
+ function.argtypes = [ctypes.c_void_p]
376
+ function.restype = ctypes.c_int
377
+ _IS_ENCRYPTED = function or False
378
+ if not _IS_ENCRYPTED:
379
+ return False # an old libarchive; reading the data then says so
380
+ return _IS_ENCRYPTED(entry._entry_p) == 1
md4kb/app/cache.py ADDED
@@ -0,0 +1,151 @@
1
+ """The cache (running.md, "Cache and state"): each reader's full result in
2
+ `$XDG_CACHE_HOME/md4kb/`, keyed by fingerprint, reader, reader version and
3
+ the options that change the result, the reader options of the source's
4
+ file type among them; and in its `answers/` folder every answer the
5
+ gateway client accepted, keyed by its request.
6
+
7
+ An entry keeps the parts of the body, not its Markdown, so md4kb renders
8
+ them again for a new rendering version or new caller keys. Anything the
9
+ cache cannot read is a miss; the cache is disposable.
10
+ """
11
+
12
+ import contextlib
13
+ import gzip
14
+ import hashlib
15
+ import json
16
+ import shutil
17
+ import zlib
18
+ from dataclasses import dataclass
19
+ from datetime import date
20
+ from pathlib import Path
21
+
22
+ from md4kb.app.files import write_atomically
23
+ from md4kb.core.model import ReaderVersion, Status, format_readers, parse_readers
24
+ from md4kb.core.parts import IncompatibleResultError, Part, from_data, to_data
25
+ from md4kb.core.protocol import Options, ResultKey
26
+ from md4kb.readers.gateway import Answer
27
+
28
+ # Raised whenever what every entry holds changes; an entry of another format
29
+ # is a miss. A change to how one file type is read goes into the key of that
30
+ # file type's sources instead (`Reader.result_key`), so only they are
31
+ # converted again. Format 1 kept Docling documents without their pictures;
32
+ # format 2 had no record of the pages the vision model read, so a scan
33
+ # cached by it would never have its pages read; format 3 read drawing pages
34
+ # with Docling's models and kept no picture of them; format 4 kept a
35
+ # spreadsheet's cell values as they are stored, not as the sheet shows them;
36
+ # format 5 kept a PDF's formulas as Docling's own formula model read them,
37
+ # so they would never be sent to the vision model; format 6 kept a workbook
38
+ # cut at the row limit with its hidden sheets shown, and its statuses
39
+ # without counting its data files. Format 8 is never used again, because
40
+ # md4kb wrote entries at 8 while an HTML file's pictures in `data:` URIs
41
+ # raised the format, before they went into the key of HTML files: the next
42
+ # format is 9.
43
+ FORMAT = 7
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Entry:
48
+ """A reader's full result for one fingerprint."""
49
+
50
+ hints: frozenset[Status] # the statuses the conversion gave
51
+ readers: tuple[ReaderVersion, ...] # every reader that took part
52
+ converted: date # when the reader converted it, `md4kb_converted`
53
+ parts: tuple[Part, ...] # what the body is rendered from
54
+
55
+
56
+ def cache_key(
57
+ fingerprint: str,
58
+ reader: str,
59
+ version: str | None,
60
+ options: Options,
61
+ reader_options: ResultKey = (),
62
+ ) -> str:
63
+ """The key of a source's result: its fingerprint, the kind's own reader
64
+ and its version, and the options that change the result, the run's and
65
+ the reader's own for the source's file type (`Reader.result_key`)."""
66
+ changing = [*options.result_key(), *reader_options]
67
+ data = [FORMAT, fingerprint, reader, version, changing]
68
+ return hashlib.sha256(json.dumps(data).encode()).hexdigest()
69
+
70
+
71
+ class Cache:
72
+ """Entries as gzipped JSON files, one per key."""
73
+
74
+ def __init__(self, folder: Path) -> None:
75
+ self.folder = folder
76
+
77
+ def path(self, key: str) -> Path:
78
+ return self.folder / key[:2] / f"{key}.json.gz"
79
+
80
+ def get(self, key: str) -> Entry | None:
81
+ """The entry for a key, or None when there is none or it cannot be
82
+ read."""
83
+ try:
84
+ data = json.loads(gzip.decompress(self.path(key).read_bytes()))
85
+ return _entry(data)
86
+ except (
87
+ OSError, # missing, unreadable, or not gzip
88
+ EOFError,
89
+ zlib.error,
90
+ UnicodeDecodeError,
91
+ ValueError, # not JSON, or not an entry (IncompatibleResultError)
92
+ KeyError,
93
+ TypeError,
94
+ ):
95
+ return None
96
+
97
+ def clear(self) -> None:
98
+ """Remove every entry, with the cache's folder (`--clear-cache`)."""
99
+ with contextlib.suppress(FileNotFoundError):
100
+ shutil.rmtree(self.folder)
101
+
102
+ def put(self, key: str, entry: Entry) -> None:
103
+ """Store an entry, replacing any for the same key."""
104
+ data = {
105
+ "format": FORMAT,
106
+ "hints": sorted(entry.hints),
107
+ "readers": format_readers(entry.readers),
108
+ "converted": entry.converted.isoformat(),
109
+ "parts": to_data(entry.parts),
110
+ }
111
+ text = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
112
+ write_atomically(self.path(key), gzip.compress(text.encode(), mtime=0))
113
+
114
+
115
+ def _entry(data: dict) -> Entry:
116
+ if data["format"] != FORMAT:
117
+ raise IncompatibleResultError(f"cache format {data['format']!r}")
118
+ return Entry(
119
+ hints=frozenset(Status(hint) for hint in data["hints"]),
120
+ readers=parse_readers(data["readers"]),
121
+ converted=date.fromisoformat(data["converted"]),
122
+ parts=from_data(data["parts"]),
123
+ )
124
+
125
+
126
+ class Answers:
127
+ """The answers the gateway client accepted, one JSON file per request
128
+ key (`md4kb.readers.gateway.StoredAnswers`), kept whatever the cache's
129
+ format, so a raised format or `--force` reads Docling again without
130
+ asking the gateway again."""
131
+
132
+ def __init__(self, folder: Path) -> None:
133
+ self.folder = folder
134
+
135
+ def _path(self, key: str) -> Path:
136
+ return self.folder / key[:2] / f"{key}.json"
137
+
138
+ def get(self, key: str) -> Answer | None:
139
+ """The answer stored for a request's key, or None when there is
140
+ none or it cannot be read."""
141
+ try:
142
+ data = json.loads(self._path(key).read_bytes())
143
+ return Answer(str(data["text"]), bool(data["cut"]))
144
+ except (OSError, UnicodeDecodeError, ValueError, KeyError, TypeError):
145
+ return None
146
+
147
+ def put(self, key: str, answer: Answer) -> None:
148
+ """Store an answer, replacing any for the same key."""
149
+ data = {"text": answer.text, "cut": answer.cut}
150
+ text = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
151
+ write_atomically(self._path(key), text.encode())
md4kb/app/embedded.py ADDED
@@ -0,0 +1,66 @@
1
+ """The files embedded in a Word, PowerPoint or Excel file, unpacked like an
2
+ archive's members (conversion.md, "Embedded files"): each that md4kb
3
+ converts, once for each set of the same bytes, streamed into a temporary
4
+ folder of its own within the caps of the archive it is in, or of its own
5
+ (`md4kb.app.archives`).
6
+ """
7
+
8
+ import shutil
9
+ import tempfile
10
+ import zipfile
11
+ from collections.abc import Iterator
12
+ from pathlib import Path, PurePosixPath
13
+
14
+ from md4kb.app.archives import BLOCK, ArchiveError, Budget, Unpacked, write
15
+ from md4kb.app.state import State
16
+ from md4kb.core.embedded import is_host
17
+ from md4kb.core.model import ARCHIVE_FOLDER_SUFFIX
18
+ from md4kb.readers.embedded import Embedded, find
19
+ from md4kb.readers.packages import UNREADABLE
20
+
21
+
22
+ def embedded_files(path: Path, built: bool = False) -> Embedded | None:
23
+ """The embedded files md4kb converts of the file at `path`; None when it
24
+ is no Word or PowerPoint file, or has none and no folder of them that
25
+ md4kb `built`."""
26
+ if not is_host(path.name):
27
+ return None
28
+ found = find(path)
29
+ return found if found.members or built else None
30
+
31
+
32
+ def to_open(path: Path, state: State) -> Embedded | None:
33
+ """The embedded files of a Word, PowerPoint or Excel file given to the run,
34
+ when it has some, or has a folder of them that md4kb built and that
35
+ goes now; None for any other file."""
36
+ if not is_host(path.name):
37
+ return None
38
+ folder = path.with_name(path.name + ARCHIVE_FOLDER_SUFFIX)
39
+ return embedded_files(path, state.built(folder) is not None)
40
+
41
+
42
+ def unpack(
43
+ host: Path, found: Embedded, scratch: Path, budget: Budget
44
+ ) -> Iterator[Unpacked]:
45
+ """Stream the embedded files `found` in `host` one at a time, each into
46
+ a new folder under `scratch`, by its name (`Embedded.members`); the
47
+ caller removes each when done with it. `CapError` over the budget,
48
+ `ArchiveError` when the file cannot be read."""
49
+ try:
50
+ with zipfile.ZipFile(host) as package:
51
+ for name in found.members:
52
+ part = found.part(name)
53
+ budget.count()
54
+ budget.declare(package.getinfo(part).file_size)
55
+ folder = Path(tempfile.mkdtemp(dir=scratch))
56
+ file = folder / PurePosixPath(name).name
57
+ try:
58
+ with package.open(part) as data:
59
+ blocks = iter(lambda: data.read(BLOCK), b"")
60
+ digest = write(blocks, file, budget)
61
+ except BaseException:
62
+ shutil.rmtree(folder, ignore_errors=True)
63
+ raise
64
+ yield Unpacked(name, file, digest)
65
+ except (*UNREADABLE, KeyError) as error:
66
+ raise ArchiveError(f"its embedded files cannot be read: {error}") from error