pypdftomd 0.4.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 (61) hide show
  1. pypdftomd/__init__.py +150 -0
  2. pypdftomd/__main__.py +10 -0
  3. pypdftomd/_version.py +5 -0
  4. pypdftomd/artefacts.py +403 -0
  5. pypdftomd/banded_tables.py +498 -0
  6. pypdftomd/cache.py +528 -0
  7. pypdftomd/cli.py +946 -0
  8. pypdftomd/column_stage.py +500 -0
  9. pypdftomd/concurrency.py +327 -0
  10. pypdftomd/contents_page.py +208 -0
  11. pypdftomd/core.py +551 -0
  12. pypdftomd/embedded.py +353 -0
  13. pypdftomd/flow_headings.py +2452 -0
  14. pypdftomd/font_semantics.py +1187 -0
  15. pypdftomd/fonts.py +173 -0
  16. pypdftomd/fontstats.py +929 -0
  17. pypdftomd/geometry.py +63 -0
  18. pypdftomd/glyphs.py +163 -0
  19. pypdftomd/heading_sequences.py +2033 -0
  20. pypdftomd/heading_veto.py +198 -0
  21. pypdftomd/layout.py +284 -0
  22. pypdftomd/layout_cuts.py +146 -0
  23. pypdftomd/line_typing.py +377 -0
  24. pypdftomd/links.py +293 -0
  25. pypdftomd/markers.py +352 -0
  26. pypdftomd/metadata.py +576 -0
  27. pypdftomd/ocr.py +740 -0
  28. pypdftomd/open_edge_header.py +677 -0
  29. pypdftomd/ownership.py +336 -0
  30. pypdftomd/page_analysis.py +300 -0
  31. pypdftomd/page_assembly.py +862 -0
  32. pypdftomd/page_geometry.py +770 -0
  33. pypdftomd/page_model.py +662 -0
  34. pypdftomd/paragraphs.py +234 -0
  35. pypdftomd/prose_rules.py +296 -0
  36. pypdftomd/quality.py +239 -0
  37. pypdftomd/reading_order.py +142 -0
  38. pypdftomd/region_interpretation.py +228 -0
  39. pypdftomd/regions.py +2146 -0
  40. pypdftomd/rendering.py +615 -0
  41. pypdftomd/row_text.py +133 -0
  42. pypdftomd/stderr_warnings.py +101 -0
  43. pypdftomd/table_continuations.py +212 -0
  44. pypdftomd/table_format.py +269 -0
  45. pypdftomd/table_hypotheses.py +2256 -0
  46. pypdftomd/table_tracks.py +794 -0
  47. pypdftomd/tables.py +145 -0
  48. pypdftomd/tesseract.py +322 -0
  49. pypdftomd/text_flow.py +1901 -0
  50. pypdftomd/text_lines.py +491 -0
  51. pypdftomd/track_runs.py +700 -0
  52. pypdftomd/types.py +138 -0
  53. pypdftomd/vector_art.py +295 -0
  54. pypdftomd/vector_grid.py +618 -0
  55. pypdftomd/visual_lines.py +755 -0
  56. pypdftomd-0.4.0.dist-info/METADATA +327 -0
  57. pypdftomd-0.4.0.dist-info/RECORD +61 -0
  58. pypdftomd-0.4.0.dist-info/WHEEL +4 -0
  59. pypdftomd-0.4.0.dist-info/entry_points.txt +2 -0
  60. pypdftomd-0.4.0.dist-info/licenses/LICENSE +661 -0
  61. pypdftomd-0.4.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +417 -0
pypdftomd/__init__.py ADDED
@@ -0,0 +1,150 @@
1
+ """pypdftomd - A versatile PDF text extraction library and CLI tool."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from pypdftomd._version import __version__ as __version__
8
+
9
+ if TYPE_CHECKING:
10
+ from pypdftomd.cli import main, parse_args
11
+ from pypdftomd.core import (
12
+ extract_text_from_pdf,
13
+ extract_text_from_pdf as extract_pdf_text,
14
+ )
15
+ from pypdftomd.embedded import (
16
+ extract_embedded_pages,
17
+ extract_embedded_text,
18
+ )
19
+ from pypdftomd.markers import (
20
+ format_extraction_summary,
21
+ summarize_page_warnings,
22
+ )
23
+ from pypdftomd.metadata import (
24
+ classify_pdf,
25
+ get_pdf_metadata,
26
+ )
27
+ from pypdftomd.ocr import (
28
+ extract_ocr_pages,
29
+ extract_ocr_text,
30
+ extract_rapid_pages,
31
+ )
32
+ from pypdftomd.rendering import (
33
+ extract_page_images,
34
+ list_page_images,
35
+ render_page_images,
36
+ write_contact_sheets,
37
+ )
38
+ from pypdftomd.table_format import (
39
+ sanitize_cell,
40
+ to_markdown_table,
41
+ write_extracted_tables,
42
+ )
43
+ from pypdftomd.tables import (
44
+ DetectedTable,
45
+ extract_tables_from_pdf,
46
+ extract_tables_with_bboxes,
47
+ )
48
+ from pypdftomd.tesseract import probe_ocr_backend
49
+ from pypdftomd.types import (
50
+ ExtractionOptions,
51
+ PageResult,
52
+ )
53
+
54
+ # Lazily re-exported public API so agents can rely on the obvious import:
55
+ # from pypdftomd import extract_text_from_pdf, get_pdf_metadata, ...
56
+ # Lazy (PEP 562) rather than eager to avoid circular imports — the
57
+ # submodules import each other, never this package's attributes.
58
+ _LAZY_EXPORTS: dict[str, str] = {
59
+ # Public types & core orchestration
60
+ "ExtractionOptions": "pypdftomd.types",
61
+ "PageResult": "pypdftomd.types",
62
+ "DetectedTable": "pypdftomd.tables",
63
+ "TableProvenance": "pypdftomd.tables",
64
+ "extract_text_from_pdf": "pypdftomd.core",
65
+ "extract_pdf_text": "pypdftomd.core",
66
+ # CLI
67
+ "main": "pypdftomd.cli",
68
+ "parse_args": "pypdftomd.cli",
69
+ # Metadata & preflight classification
70
+ "classify_pdf": "pypdftomd.metadata",
71
+ "get_pdf_metadata": "pypdftomd.metadata",
72
+ # Embedded extraction & font statistics
73
+ "extract_embedded_pages": "pypdftomd.embedded",
74
+ "extract_embedded_text": "pypdftomd.embedded",
75
+ "cluster_heading_tiers": "pypdftomd.fontstats",
76
+ "discover_base_font_size": "pypdftomd.fontstats",
77
+ "extract_document_font_stats": "pypdftomd.fontstats",
78
+ # OCR & Tesseract backend
79
+ "OCR_DPI": "pypdftomd.ocr",
80
+ "OCR_PROVENANCE": "pypdftomd.ocr",
81
+ "extract_ocr_pages": "pypdftomd.ocr",
82
+ "extract_ocr_text": "pypdftomd.ocr",
83
+ "extract_rapid_pages": "pypdftomd.ocr",
84
+ "probe_ocr_backend": "pypdftomd.tesseract",
85
+ # Rendering & image extraction
86
+ "render_page_images": "pypdftomd.rendering",
87
+ "extract_page_images": "pypdftomd.rendering",
88
+ "list_page_images": "pypdftomd.rendering",
89
+ "write_contact_sheets": "pypdftomd.rendering",
90
+ # Tables, formatting, and geometry
91
+ "extract_tables_from_pdf": "pypdftomd.tables",
92
+ "extract_tables_with_bboxes": "pypdftomd.tables",
93
+ "to_markdown_table": "pypdftomd.table_format",
94
+ "write_extracted_tables": "pypdftomd.table_format",
95
+ "sanitize_cell": "pypdftomd.table_format",
96
+ "table_quality_issues": "pypdftomd.table_format",
97
+ "intersection_area": "pypdftomd.geometry",
98
+ # Markers & diagnostics
99
+ "TYPE3_FONT_WARNING": "pypdftomd.markers",
100
+ "OCR_BACKEND_UNAVAILABLE_WARNING": "pypdftomd.markers",
101
+ "OCR_TIMEOUT_WARNING": "pypdftomd.markers",
102
+ "CHART_GRID_TABLE_WARNING": "pypdftomd.markers",
103
+ "format_extraction_summary": "pypdftomd.markers",
104
+ "summarize_page_warnings": "pypdftomd.markers",
105
+ }
106
+
107
+ __all__ = [
108
+ "ExtractionOptions",
109
+ "PageResult",
110
+ "DetectedTable",
111
+ "extract_text_from_pdf",
112
+ "extract_pdf_text",
113
+ "classify_pdf",
114
+ "get_pdf_metadata",
115
+ "extract_embedded_pages",
116
+ "extract_embedded_text",
117
+ "extract_ocr_pages",
118
+ "extract_ocr_text",
119
+ "extract_rapid_pages",
120
+ "probe_ocr_backend",
121
+ "render_page_images",
122
+ "extract_page_images",
123
+ "list_page_images",
124
+ "write_contact_sheets",
125
+ "extract_tables_from_pdf",
126
+ "extract_tables_with_bboxes",
127
+ "to_markdown_table",
128
+ "write_extracted_tables",
129
+ "sanitize_cell",
130
+ "format_extraction_summary",
131
+ "summarize_page_warnings",
132
+ "main",
133
+ "parse_args",
134
+ "__version__",
135
+ ]
136
+
137
+
138
+ def __getattr__(name: str) -> Any:
139
+ """Resolve public API names from their defining submodules on first use.
140
+
141
+ Raises:
142
+ AttributeError: If name is not a recognized lazy export.
143
+ """
144
+ module_name = _LAZY_EXPORTS.get(name)
145
+ if module_name is None:
146
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
147
+ import importlib
148
+
149
+ target_attr = "extract_text_from_pdf" if name == "extract_pdf_text" else name
150
+ return getattr(importlib.import_module(module_name), target_attr)
pypdftomd/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Executable module entry point for python -m pypdftomd."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from pypdftomd.cli import main
8
+
9
+ if __name__ == "__main__":
10
+ sys.exit(main())
pypdftomd/_version.py ADDED
@@ -0,0 +1,5 @@
1
+ """Package version single source of truth."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__: str = "0.4.0"
pypdftomd/artefacts.py ADDED
@@ -0,0 +1,403 @@
1
+ """Run-owned output publication and cleanup, including process workers.
2
+
3
+ This module is a leaf: it imports only the standard library.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextlib
9
+ import errno
10
+ import json
11
+ import os
12
+ import stat
13
+ import sys
14
+ import tempfile
15
+ import uuid
16
+ from contextvars import ContextVar
17
+ from pathlib import Path
18
+ from typing import TYPE_CHECKING, TypedDict
19
+
20
+ if TYPE_CHECKING:
21
+ from collections.abc import Iterator
22
+
23
+ _JOURNAL: ContextVar[Path | None] = ContextVar("output_journal", default=None)
24
+
25
+
26
+ if sys.platform == "win32":
27
+
28
+ @contextlib.contextmanager
29
+ def _windows_directory_mutex(identity: tuple[int, int]) -> Iterator[None]:
30
+ """Hold the same directory mutex across Windows accounts and sessions.
31
+
32
+ Raises:
33
+ OSError: If the security descriptor, mutex or wait fails.
34
+ """
35
+ import ctypes
36
+ from ctypes import wintypes
37
+
38
+ class SecurityAttributes(ctypes.Structure):
39
+ _fields_ = [
40
+ ("length", wintypes.DWORD),
41
+ ("descriptor", wintypes.LPVOID),
42
+ ("inherit", wintypes.BOOL),
43
+ ]
44
+
45
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
46
+ security_api = ctypes.WinDLL("advapi32", use_last_error=True)
47
+ convert = security_api.ConvertStringSecurityDescriptorToSecurityDescriptorW
48
+ convert.argtypes = (
49
+ wintypes.LPCWSTR,
50
+ wintypes.DWORD,
51
+ ctypes.POINTER(wintypes.LPVOID),
52
+ ctypes.POINTER(wintypes.DWORD),
53
+ )
54
+ convert.restype = wintypes.BOOL
55
+ create = kernel.CreateMutexExW
56
+ create.argtypes = (
57
+ wintypes.LPVOID,
58
+ wintypes.LPCWSTR,
59
+ wintypes.DWORD,
60
+ wintypes.DWORD,
61
+ )
62
+ create.restype = wintypes.HANDLE
63
+ wait = kernel.WaitForSingleObject
64
+ wait.argtypes = (wintypes.HANDLE, wintypes.DWORD)
65
+ wait.restype = wintypes.DWORD
66
+ for close in (kernel.ReleaseMutex, kernel.CloseHandle, kernel.LocalFree):
67
+ close.argtypes = (wintypes.HANDLE,)
68
+ kernel.LocalFree.restype = wintypes.HANDLE
69
+
70
+ # SYNCHRONIZE | MUTEX_MODIFY_STATE for authenticated users and SYSTEM.
71
+ access = 0x00100001
72
+ descriptor = wintypes.LPVOID()
73
+ if not convert(
74
+ "D:P(A;;0x00100001;;;AU)(A;;0x00100001;;;SY)",
75
+ 1,
76
+ ctypes.byref(descriptor),
77
+ None,
78
+ ):
79
+ raise ctypes.WinError(ctypes.get_last_error())
80
+ try:
81
+ security = SecurityAttributes(
82
+ ctypes.sizeof(SecurityAttributes), descriptor, False
83
+ )
84
+ volume, file_index = identity
85
+ name = f"Global\\pypdftomd-output-{volume:x}-{file_index:x}"
86
+ mutex = create(ctypes.byref(security), name, 0, access)
87
+ if not mutex:
88
+ raise ctypes.WinError(ctypes.get_last_error())
89
+ finally:
90
+ kernel.LocalFree(descriptor)
91
+
92
+ try:
93
+ result = wait(mutex, 30_000)
94
+ if result == 0x102: # WAIT_TIMEOUT
95
+ raise TimeoutError(
96
+ errno.ETIMEDOUT, "Timed out locking output directory"
97
+ )
98
+ if result not in (0, 0x80): # WAIT_OBJECT_0, WAIT_ABANDONED
99
+ raise ctypes.WinError(ctypes.get_last_error())
100
+ try:
101
+ yield
102
+ finally:
103
+ # Wait, use and release are synchronous on the same thread.
104
+ kernel.ReleaseMutex(mutex)
105
+ finally:
106
+ kernel.CloseHandle(mutex)
107
+
108
+
109
+ def _directory_identity(directory: Path) -> tuple[int, int]:
110
+ """Return the identity of a live directory.
111
+
112
+ Raises:
113
+ OSError: If the directory cannot be identified.
114
+ """
115
+ info = directory.stat()
116
+ if not stat.S_ISDIR(info.st_mode) or not info.st_ino:
117
+ raise OSError(errno.ENOTSUP, "Cannot identify output directory", directory)
118
+ return info.st_dev, info.st_ino
119
+
120
+
121
+ @contextlib.contextmanager
122
+ def _directory_lock(directory: Path) -> Iterator[bool]:
123
+ """Lock a live directory across cooperating processes on the same host."""
124
+ while True:
125
+ with contextlib.ExitStack() as stack:
126
+ try:
127
+ if sys.platform == "win32":
128
+ identity = _directory_identity(directory)
129
+ stack.enter_context(_windows_directory_mutex(identity))
130
+ else:
131
+ import fcntl
132
+
133
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
134
+ stack.callback(os.close, fd)
135
+ fcntl.flock(fd, fcntl.LOCK_EX)
136
+ # Release explicitly in case a forked worker inherited the fd.
137
+ stack.callback(fcntl.flock, fd, fcntl.LOCK_UN)
138
+ info = os.fstat(fd)
139
+ identity = (info.st_dev, info.st_ino)
140
+ # A waiter may have opened a directory since removed by rollback.
141
+ if identity != _directory_identity(directory):
142
+ continue
143
+ except (OSError, ImportError, AttributeError, NotImplementedError):
144
+ stack.close()
145
+ locked = False
146
+ else:
147
+ locked = True
148
+ yield locked
149
+ return
150
+
151
+
152
+ class _Event(TypedDict):
153
+ path: str
154
+ before: list[int] | None
155
+ after: list[int]
156
+ kind: str
157
+
158
+
159
+ def _identity(path: Path) -> list[int] | None:
160
+ """Identify a publication without following a replacement symlink."""
161
+ try:
162
+ stat = path.lstat()
163
+ except FileNotFoundError:
164
+ return None
165
+ return [stat.st_dev, stat.st_ino, stat.st_mtime_ns, stat.st_size]
166
+
167
+
168
+ def _record(path: Path, before: list[int] | None, after: list[int], kind: str) -> None:
169
+ """Persist one ownership event before publishing, using a unique worker name."""
170
+ journal = _JOURNAL.get()
171
+ if journal is None:
172
+ return
173
+ entry = {
174
+ "path": str(path.absolute()),
175
+ "before": before,
176
+ "after": after,
177
+ "kind": kind,
178
+ }
179
+ record = journal / uuid.uuid4().hex
180
+ try:
181
+ with record.open("w", encoding="utf-8") as output:
182
+ json.dump(entry, output)
183
+ except BaseException:
184
+ record.unlink(missing_ok=True)
185
+ raise
186
+
187
+
188
+ def make_output_directory(directory: Path) -> None:
189
+ """Create and record only the directories this invocation actually makes.
190
+
191
+ Raises:
192
+ OSError: If a directory cannot be created.
193
+ """
194
+ directory = directory.absolute()
195
+ if directory.parent == directory:
196
+ directory.mkdir(exist_ok=True)
197
+ return
198
+
199
+ while True:
200
+ needed = [directory]
201
+ parent = directory.parent
202
+ while not parent.exists() and parent.parent != parent:
203
+ needed.append(parent)
204
+ parent = parent.parent
205
+ for current in reversed(needed):
206
+ parent = current.parent
207
+ with _directory_lock(parent) as locked:
208
+ try:
209
+ current.mkdir()
210
+ except FileExistsError:
211
+ if not current.is_dir():
212
+ raise
213
+ except FileNotFoundError:
214
+ if locked or parent.exists() or parent == parent.parent:
215
+ raise
216
+ break # Retry if rollback removed a parent before we opened it.
217
+ else:
218
+ identity = _identity(current)
219
+ if identity is None:
220
+ raise FileNotFoundError(current)
221
+ try:
222
+ _record(current, None, identity, "directory")
223
+ except BaseException:
224
+ if locked:
225
+ _remove_owned_directory(current, identity)
226
+ raise
227
+ else:
228
+ return
229
+
230
+
231
+ def _remove_owned_directory(directory: Path, owned: list[int]) -> None:
232
+ """Remove an owned empty directory while its parent's lock is held."""
233
+ with _directory_lock(directory) as locked, contextlib.suppress(OSError):
234
+ if locked:
235
+ identity = _identity(directory)
236
+ if identity is not None and identity[:2] == owned[:2]:
237
+ directory.rmdir()
238
+
239
+
240
+ def _publish_new_output(stage: Path, target: Path) -> None:
241
+ """Publish into an absent name using a no-clobber filesystem operation.
242
+
243
+ Raises:
244
+ OSError: If safe publication cannot create the target.
245
+ """
246
+ try:
247
+ if sys.platform == "win32":
248
+ os.rename(stage, target)
249
+ else:
250
+ os.link(stage, target)
251
+ except (OSError, NotImplementedError) as exc:
252
+ code = errno.ENOTSUP
253
+ if isinstance(exc, OSError):
254
+ code = exc.errno
255
+ if code not in (
256
+ errno.EEXIST,
257
+ errno.ENOSYS,
258
+ errno.ENOTSUP,
259
+ errno.EOPNOTSUPP,
260
+ ):
261
+ # ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED, ERROR_CALL_NOT_IMPLEMENTED
262
+ if getattr(exc, "winerror", None) not in (1, 50, 120):
263
+ raise
264
+ raise OSError(
265
+ code, "Output destination is in use or could not be locked", target
266
+ ) from exc
267
+
268
+
269
+ @contextlib.contextmanager
270
+ def publish_output(
271
+ path: Path, *, follow_symlinks: bool = False, preserve_mode: bool = False
272
+ ) -> Iterator[Path]:
273
+ """Write a sibling and atomically publish it, cleaning up partial writes.
274
+
275
+ Existing files are replaced under the directory lock after the write succeeds.
276
+ If locking fails, publication can only create a new target. When requested,
277
+ publication follows the destination symlink, preserving the link.
278
+
279
+ Raises:
280
+ OSError: If directory creation, writing or publication fails.
281
+ """
282
+ target = path.resolve() if follow_symlinks else path.absolute()
283
+ temporary = target.parent / f".pdf-output-{uuid.uuid4().hex}{target.suffix}"
284
+ # Once staged, the directory is nonempty until publication or stage cleanup.
285
+ while True:
286
+ make_output_directory(target.parent)
287
+ with _directory_lock(target.parent) as locked:
288
+ try:
289
+ descriptor = os.open(
290
+ temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o666
291
+ )
292
+ except FileNotFoundError:
293
+ if locked or target.parent.exists():
294
+ raise
295
+ continue
296
+ os.close(descriptor)
297
+ break
298
+ try:
299
+ yield temporary
300
+ with _directory_lock(target.parent) as locked:
301
+ if locked and preserve_mode and target.is_file():
302
+ temporary.chmod(stat.S_IMODE(target.stat().st_mode))
303
+ identity = _identity(temporary)
304
+ if identity is None:
305
+ raise FileNotFoundError(temporary)
306
+ _record(target, _identity(target) if locked else None, identity, "file")
307
+ if locked:
308
+ temporary.replace(target)
309
+ else:
310
+ _publish_new_output(temporary, target)
311
+ finally:
312
+ temporary.unlink(missing_ok=True)
313
+
314
+
315
+ def current_artefact_journal() -> Path | None:
316
+ """Return the current scope's journal for explicit worker propagation."""
317
+ return _JOURNAL.get()
318
+
319
+
320
+ @contextlib.contextmanager
321
+ def use_artefact_journal(journal: Path | None) -> Iterator[None]:
322
+ """Attach a process worker to its caller's ownership journal."""
323
+ token = _JOURNAL.set(journal)
324
+ try:
325
+ yield
326
+ finally:
327
+ _JOURNAL.reset(token)
328
+
329
+
330
+ def _discard(journal: Path) -> None:
331
+ """Remove only current file identities descended from this run's creations."""
332
+ files: dict[Path, list[_Event]] = {}
333
+ directories: dict[Path, list[int]] = {}
334
+ for entry in journal.iterdir():
335
+ with entry.open(encoding="utf-8") as source:
336
+ event: _Event = json.load(source)
337
+ path = Path(event["path"])
338
+ if event["kind"] == "directory":
339
+ directories[path] = event["after"]
340
+ else:
341
+ files.setdefault(path, []).append(event)
342
+ for path, events in files.items():
343
+ owned = {tuple(event["after"]) for event in events if event["before"] is None}
344
+ # Rewrites of a file created by this scope remain owned, even across
345
+ # nested calls and worker journals. An unrelated run breaks the chain.
346
+ for _ in events:
347
+ for event in events:
348
+ before = event["before"]
349
+ if before is not None and tuple(before) in owned:
350
+ owned.add(tuple(event["after"]))
351
+ if not owned:
352
+ continue
353
+ with _directory_lock(path.parent) as locked, contextlib.suppress(OSError):
354
+ if locked:
355
+ identity = _identity(path)
356
+ if identity is not None and tuple(identity) in owned:
357
+ path.unlink(missing_ok=True)
358
+ for directory in sorted(
359
+ directories, key=lambda path: len(path.parts), reverse=True
360
+ ):
361
+ with _directory_lock(directory.parent) as locked:
362
+ if locked:
363
+ _remove_owned_directory(directory, directories[directory])
364
+
365
+
366
+ @contextlib.contextmanager
367
+ def discard_new_artefacts_on_error(
368
+ *,
369
+ images_output: Path | None = None,
370
+ output_file: Path | None = None,
371
+ tables_output: Path | None = None,
372
+ contact_sheet: Path | None = None,
373
+ independent: bool = False,
374
+ ) -> Iterator[None]:
375
+ """Discard this call's actual creations on failure, preserving other runs.
376
+
377
+ Write sites record ownership through ``publish_output`` and
378
+ ``make_output_directory``. Successful nested scopes transfer their journals
379
+ to the caller; CLI invocations start independent scopes. Workers receive the
380
+ journal explicitly, so both completed and failed chunks are accounted for.
381
+ Destination arguments remain accepted for the existing internal callers;
382
+ ownership is never inferred from directory contents.
383
+ """
384
+ parent = None if independent else _JOURNAL.get()
385
+ if all(
386
+ path is None
387
+ for path in (images_output, output_file, tables_output, contact_sheet)
388
+ ):
389
+ with use_artefact_journal(parent):
390
+ yield
391
+ return
392
+ with tempfile.TemporaryDirectory(prefix="pdf-output-") as temporary:
393
+ journal = Path(temporary)
394
+ with use_artefact_journal(journal):
395
+ try:
396
+ yield
397
+ except BaseException:
398
+ _discard(journal)
399
+ raise
400
+ else:
401
+ if parent is not None:
402
+ for entry in journal.iterdir():
403
+ entry.replace(parent / entry.name)