Skip to content

comicbox.process ¶

Parallel processing for large-scale comic metadata reading.

ReadResult ¶

Bases: TypedDict

Result of reading metadata from a single comic archive.

The envelope fields (metadata_mtime, page_count, file_type) are populated cheaply on every successful read and are the source of truth for archive-level state tracking. tags carries the parsed metadata payload and is None when extraction was skipped — either because the embedded metadata mtime hadn’t advanced past old_mtime or because the caller passed full_metadata=False.

Distinguishing “skip” from “extracted-but-empty” is the contract that lets callers preserve existing tag links when the archive’s tags haven’t changed; an empty {} would mean “extracted, no tags found”, which would force the caller to clear those links.

Source code in comicbox/process.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class ReadResult(TypedDict):
    """
    Result of reading metadata from a single comic archive.

    The envelope fields (``metadata_mtime``, ``page_count``, ``file_type``)
    are populated cheaply on every successful read and are the source of
    truth for archive-level state tracking. ``tags`` carries the parsed
    metadata payload and is ``None`` when extraction was skipped — either
    because the embedded metadata mtime hadn't advanced past ``old_mtime``
    or because the caller passed ``full_metadata=False``.

    Distinguishing "skip" from "extracted-but-empty" is the contract that
    lets callers preserve existing tag links when the archive's tags
    haven't changed; an empty ``{}`` would mean "extracted, no tags
    found", which would force the caller to clear those links.
    """

    metadata_mtime: dt.datetime | None
    page_count: int | None
    file_type: str | None
    tags: dict[str, Any] | None

aread_metadata(path, config=None, fmt=MetadataFormats.COMICBOX_YAML) async ¶

Read metadata from a single comic file in a thread executor.

Source code in comicbox/process.py
372
373
374
375
376
377
378
379
async def aread_metadata(
    path: Path | str,
    config: ComicboxSettings | Mapping | None = None,
    fmt: MetadataFormats = MetadataFormats.COMICBOX_YAML,
) -> ReadResult:
    """Read metadata from a single comic file in a thread executor."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(None, _read_one, path, config, fmt)

iter_process_files(paths, config=None, logger=None, fmt=MetadataFormats.COMICBOX_YAML, max_workers=None, old_mtime_map=None, worker_log_config=None, *, full_metadata=True, on_event=None) ¶

Yield (path, (ReadResult, exception_or_None)) as each file completes.

All per-path failures — submit-time, worker-raised, or pool-broken — are delivered as the second element of the tuple rather than raised, so a single bad path cannot abort the whole run. On failure the ReadResult is the empty sentinel (all fields None); inspect the exception, not the result, to detect failure.

worker_log_config: optional dict of {"level", "format", "sink"} used to re-initialize loguru inside each worker so subprocess log output matches the caller’s format. Must be picklable; pass sink as "stdout" / "stderr" / path string, not a file object.

on_event: optional handler invoked on the orchestrator thread with each :class:comicbox.events.Event. Fires :class:BatchStarted once before the first submit, one of :class:FileParsed / :class:FileShortCircuited / :class:FileError per delivered result, and :class:BatchFinished once with totals. Handler runs on the orchestrator thread and must be thread-safe and quick.

Source code in comicbox/process.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def iter_process_files(  # noqa: PLR0913
    paths: Iterable[Path | str],
    config: ComicboxSettings | Mapping | None = None,
    logger: Any = None,
    fmt: MetadataFormats = MetadataFormats.COMICBOX_YAML,
    max_workers: int | None = None,
    old_mtime_map: Mapping[str, dt.datetime] | None = None,
    worker_log_config: Mapping | None = None,
    *,
    full_metadata: bool = True,
    on_event: EventHandler | None = None,
) -> Generator[tuple[Path, tuple[ReadResult, BaseException | None]], None, None]:
    """
    Yield (path, (ReadResult, exception_or_None)) as each file completes.

    All per-path failures — submit-time, worker-raised, or pool-broken —
    are delivered as the second element of the tuple rather than raised,
    so a single bad path cannot abort the whole run. On failure the
    ReadResult is the empty sentinel (all fields ``None``); inspect the
    exception, not the result, to detect failure.

    ``worker_log_config``: optional dict of ``{"level", "format", "sink"}``
        used to re-initialize loguru inside each worker so subprocess log
        output matches the caller's format. Must be picklable; pass sink
        as ``"stdout"`` / ``"stderr"`` / path string, not a file object.

    ``on_event``: optional handler invoked on the orchestrator thread with
        each :class:`comicbox.events.Event`. Fires :class:`BatchStarted`
        once before the first submit, one of :class:`FileParsed` /
        :class:`FileShortCircuited` / :class:`FileError` per delivered
        result, and :class:`BatchFinished` once with totals. Handler runs
        on the orchestrator thread and must be thread-safe and quick.
    """
    if not logger:
        from loguru import logger
    if not old_mtime_map:
        old_mtime_map = {}
    path_list = [Path(p) for p in paths]
    total = len(path_list)

    if on_event is not None:
        on_event(BatchStarted(total=total))

    executor_kwargs: dict[str, Any] = {"max_workers": max_workers}
    if worker_log_config:
        executor_kwargs["initializer"] = _worker_log_init
        executor_kwargs["initargs"] = (dict(worker_log_config),)
    executor = ProcessPoolExecutor(**executor_kwargs)
    try:
        futures: dict = {}
        submit_failures: list[tuple[Path, BaseException]] = []
        for path in path_list:
            old_mtime = old_mtime_map.get(str(path), EPOCH_START)
            try:
                future = executor.submit(
                    _read_one,
                    path,
                    config,
                    fmt,
                    old_mtime,
                    full_metadata=full_metadata,
                )
            except Exception as exc:
                logger.exception(f"Failed to submit {path}")
                submit_failures.append((path, exc))
                continue
            futures[future] = path

        # Surface submit-time failures up front so the index sequence in
        # events matches the yield order seen by the caller. They seed the
        # counters and starting index that _iter_completed continues from,
        # keeping the BatchFinished invariant intact.
        counters: _OutcomeCounters = {"parsed": 0, "short_circuited": 0, "errored": 0}
        for index, (path, exc) in enumerate(submit_failures):
            counters["errored"] += 1
            if on_event is not None:
                on_event(FileError(path=path, index=index, total=total, error=str(exc)))
            yield path, (_empty_read_result(), exc)

        yield from _iter_completed(
            futures,
            logger,
            on_event,
            total,
            counters=counters,
            start_index=len(submit_failures),
        )
    finally:
        executor.shutdown(wait=False, cancel_futures=True)

process_files(paths, config=None, logger=None, fmt=MetadataFormats.COMICBOX_YAML, max_workers=None, worker_log_config=None, *, on_event=None) ¶

Process multiple comic files in parallel via ProcessPoolExecutor.

Source code in comicbox/process.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def process_files(
    paths: Iterable[Path | str],
    config: ComicboxSettings | Mapping | None = None,
    logger: Any = None,
    fmt: MetadataFormats = MetadataFormats.COMICBOX_YAML,
    max_workers: int | None = None,
    worker_log_config: Mapping | None = None,
    *,
    on_event: EventHandler | None = None,
) -> dict[Path, tuple[ReadResult, BaseException | None]]:
    """Process multiple comic files in parallel via ProcessPoolExecutor."""
    return dict(
        iter_process_files(
            paths,
            config,
            logger,
            fmt,
            max_workers,
            worker_log_config=worker_log_config,
            on_event=on_event,
        )
    )