File size: 33,839 Bytes
e58f9dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
"""Convert the raw IMF PDF corpus into page-grounded Markdown and visual assets.

The processor is deliberately separate from structured extraction. It creates a
stable, auditable interim representation while preserving page boundaries,
source hashes, PDF metadata, detected tables, and normalized visual hashes.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import datetime as dt
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable, Sequence

import imagehash
import pymupdf
import pymupdf4llm
from PIL import Image, ImageOps

PROCESSOR_VERSION = "1.0.1"
EXTRACTION_METHOD = "pymupdf4llm+pymupdf-layout"
IMAGE_DPI = 120
PHASH_BITS = 256

IMAGE_REF_RE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
GENERATED_IMAGE_RE = re.compile(
    r"\.pdf-(\d+)-(\d+|full)\.(?:png|jpe?g)$", re.I
)
HEADING_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*$", re.M)


def utc_now() -> str:
    return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()


def load_jsonl(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        return []
    with path.open(encoding="utf-8") as source:
        return [json.loads(line) for line in source if line.strip()]


def write_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(
        json.dumps(value, ensure_ascii=False, indent=2, default=str) + "\n",
        encoding="utf-8",
    )
    os.replace(temporary, path)


def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8") as output:
        for row in rows:
            output.write(json.dumps(row, ensure_ascii=False, sort_keys=True, default=str))
            output.write("\n")
    os.replace(temporary, path)


def markdown_to_plain(markdown: str) -> str:
    text = IMAGE_REF_RE.sub("", markdown)
    text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
    text = re.sub(r"<br\s*/?>", " ", text, flags=re.I)
    text = re.sub(r"</?[^>]+>", " ", text)
    text = re.sub(r"^\s*#{1,6}\s*", "", text, flags=re.M)
    text = re.sub(r"\*\*|__|`", "", text)
    text = re.sub(r"^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$", "", text, flags=re.M)
    text = text.replace("|", " ")
    text = re.sub(r"[ \t]+", " ", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()


def content_metrics(text: str) -> dict[str, Any]:
    compact = re.sub(r"\s+", "", text)
    words = re.findall(r"\b\w+\b", text, flags=re.UNICODE)
    return {
        "characters": len(text),
        "non_whitespace_characters": len(compact),
        "words": len(words),
        "replacement_characters": text.count("\ufffd"),
        "headings": len(HEADING_RE.findall(text)),
        "markdown_table_rows": sum(
            1 for line in text.splitlines() if line.count("|") >= 2
        ),
    }


def choose_benchmark_sample(
    inventory: list[dict[str, Any]],
    manifest: list[dict[str, Any]],
    count: int,
) -> list[str]:
    by_id = {row["report_id"]: row for row in inventory}
    manifest = [row for row in manifest if row["report_id"] in by_id]
    selected: list[str] = []

    def add(report_id: str) -> None:
        if report_id in by_id and report_id not in selected:
            selected.append(report_id)

    ordered = sorted(inventory, key=lambda row: row.get("publication_date") or "")
    for row in ordered[:2] + ordered[-2:]:
        add(row["report_id"])
    for series_prefix in ("cr-", "tar-", "legacy-"):
        group = [row for row in ordered if row["report_id"].startswith(series_prefix)]
        if group:
            for index in (0, len(group) // 2, len(group) - 1):
                add(group[index]["report_id"])
    for row in inventory:
        languages = {value.lower() for value in row.get("language", [])}
        if languages - {"english"}:
            add(row["report_id"])
    by_size = sorted(manifest, key=lambda row: row.get("bytes", 0))
    if by_size:
        for quantile in (0.0, 0.25, 0.5, 0.75, 1.0):
            add(by_size[round((len(by_size) - 1) * quantile)]["report_id"])
    return selected[:count]


def _pymupdf4llm_chunks(pdf_path: str, *, write_images: bool, image_path: str = "") -> list[dict[str, Any]]:
    with pymupdf.open(pdf_path) as document:
        chunks = pymupdf4llm.to_markdown(
            document,
            page_chunks=True,
            write_images=write_images,
            image_path=image_path,
            image_format="png",
            image_size_limit=0.03,
            force_text=True,
            margins=0,
            dpi=IMAGE_DPI,
            table_strategy="lines_strict",
            graphics_limit=5000,
            ignore_code=True,
            extract_words=False,
            show_progress=False,
        )
        if not isinstance(chunks, list) or len(chunks) != len(document):
            raise RuntimeError(
                f"unexpected page chunks: got {type(chunks).__name__}/"
                f"{len(chunks) if isinstance(chunks, list) else '?'} for {len(document)} pages"
            )
        return chunks


def benchmark_one(args: tuple[str, str]) -> dict[str, Any]:
    report_id, pdf_path = args
    started = time.perf_counter()
    chunks = _pymupdf4llm_chunks(pdf_path, write_images=False)
    layout_seconds = time.perf_counter() - started
    markdown = "\n\n".join(chunk.get("text", "") for chunk in chunks)

    started = time.perf_counter()
    completed = subprocess.run(
        ["pdftotext", "-layout", pdf_path, "-"],
        check=True,
        capture_output=True,
    )
    poppler_text = completed.stdout.decode("utf-8", errors="replace")
    poppler_seconds = time.perf_counter() - started

    started = time.perf_counter()
    with pymupdf.open(pdf_path) as document:
        pymupdf_text = "\n\n".join(page.get_text("text", sort=True) for page in document)
        page_count = len(document)
    pymupdf_seconds = time.perf_counter() - started

    tables = sum(len(chunk.get("tables", [])) for chunk in chunks)
    return {
        "report_id": report_id,
        "pdf_path": pdf_path,
        "page_count": page_count,
        "pymupdf4llm": {
            "seconds": round(layout_seconds, 3),
            "detected_tables": tables,
            **content_metrics(markdown),
        },
        "pdftotext_layout": {
            "seconds": round(poppler_seconds, 3),
            **content_metrics(poppler_text),
        },
        "pymupdf_text": {
            "seconds": round(pymupdf_seconds, 3),
            **content_metrics(pymupdf_text),
        },
    }


def run_benchmark(
    inventory: list[dict[str, Any]],
    manifest: list[dict[str, Any]],
    *,
    interim_dir: Path,
    workers: int,
    sample_count: int,
) -> dict[str, Any]:
    paths = {row["report_id"]: row["local_path"] for row in manifest}
    selected = choose_benchmark_sample(inventory, manifest, sample_count)
    jobs = [(report_id, paths[report_id]) for report_id in selected]
    results: list[dict[str, Any]] = []
    with concurrent.futures.ProcessPoolExecutor(max_workers=max(1, workers)) as pool:
        for result in pool.map(benchmark_one, jobs):
            results.append(result)
            print(
                f"benchmark: {len(results)}/{len(jobs)} {result['report_id']}",
                file=sys.stderr,
            )
    ratios = []
    for result in results:
        baseline = result["pdftotext_layout"]["non_whitespace_characters"]
        layout = result["pymupdf4llm"]["non_whitespace_characters"]
        if baseline:
            ratios.append(layout / baseline)
    summary = {
        "created_at": utc_now(),
        "sample_count": len(results),
        "sample_selection": "stratified by year, series, language, and PDF size",
        "results": results,
        "aggregate": {
            "pymupdf4llm_detected_tables": sum(
                result["pymupdf4llm"]["detected_tables"] for result in results
            ),
            "median_layout_to_pdftotext_non_whitespace_ratio": (
                sorted(ratios)[len(ratios) // 2] if ratios else None
            ),
            "pymupdf4llm_seconds": round(
                sum(result["pymupdf4llm"]["seconds"] for result in results), 3
            ),
            "pdftotext_seconds": round(
                sum(result["pdftotext_layout"]["seconds"] for result in results), 3
            ),
        },
        "selected_method": EXTRACTION_METHOD,
        "selection_rationale": (
            "PyMuPDF4LLM with PyMuPDF Layout preserves page boundaries, headings, "
            "reading order, detected tables, and visual regions. pdftotext -layout "
            "is retained as an independent coverage baseline, not as the canonical format."
        ),
        "limitation": (
            "The benchmark compares structural and coverage diagnostics without a "
            "human-transcribed ground truth; downstream extraction remains unreviewed."
        ),
    }
    write_json(interim_dir / "_benchmark" / "benchmark.json", summary)
    return summary


def image_caption(page_markdown: str, source_name: str) -> str | None:
    lines = page_markdown.splitlines()
    target_index = next(
        (index for index, line in enumerate(lines) if source_name in line), None
    )
    if target_index is None:
        return None
    caption_pattern = re.compile(
        r"^(?:#{1,6}\s*)?(?:\*\*)?\s*(Figure|Chart|Box|Table|Graph)\s+\w+",
        re.I,
    )
    for distance in range(1, 7):
        for index in (target_index - distance, target_index + distance):
            if 0 <= index < len(lines):
                candidate = markdown_to_plain(lines[index]).strip()
                if caption_pattern.search(candidate):
                    return candidate[:1000]
    return None


def normalize_and_hash_image(
    source: Path, destination: Path
) -> tuple[dict[str, Any], tuple[int, int]]:
    with Image.open(source) as opened:
        image = ImageOps.exif_transpose(opened)
        if getattr(image, "is_animated", False):
            image.seek(0)
        if image.mode in {"RGBA", "LA"}:
            rgba = image.convert("RGBA")
            background = Image.new("RGBA", rgba.size, "white")
            background.alpha_composite(rgba)
            image = background.convert("RGB")
        else:
            image = image.convert("RGB")
        width, height = image.size
        destination.parent.mkdir(parents=True, exist_ok=True)
        image.save(destination, format="PNG", optimize=True)
        phash = str(imagehash.phash(image, hash_size=16))
        dhash = str(imagehash.dhash(image, hash_size=8))
    digest = hashlib.sha256(destination.read_bytes()).hexdigest()
    return (
        {
            "sha256_normalized_png": digest,
            "phash_256": phash,
            "dhash_64": dhash,
            "width": width,
            "height": height,
            "color_mode": "RGB",
        },
        (width, height),
    )


def classify_visual(
    *,
    page_number: int,
    image_size: tuple[int, int],
    page_size_points: tuple[float, float],
    caption: str | None,
    page_tables: list[dict[str, Any]],
) -> str:
    width, height = image_size
    rendered_width = page_size_points[0] * IMAGE_DPI / 72
    rendered_height = page_size_points[1] * IMAGE_DPI / 72
    coverage = (width * height) / max(1.0, rendered_width * rendered_height)
    if page_number == 1 and coverage >= 0.35:
        return "cover"
    if coverage >= 0.82:
        return "page_scan_or_full_page_visual"
    if caption:
        lowered = caption.lower()
        if lowered.startswith("table"):
            return "table_snapshot"
        if lowered.startswith("box"):
            return "box"
        return "figure"
    if page_tables and width >= 400:
        return "table_or_graphic"
    return "visual"


def rewrite_and_catalog_images(
    *,
    report_id: str,
    chunks: list[dict[str, Any]],
    generated_dir: Path,
    figure_dir: Path,
    document: pymupdf.Document,
    final_report_dir: Path,
) -> tuple[list[dict[str, Any]], dict[int, list[str]]]:
    source_files = {path.name: path for path in generated_dir.glob("*") if path.is_file()}
    figures: list[dict[str, Any]] = []
    page_assets: dict[int, list[str]] = defaultdict(list)
    replacement: dict[str, str] = {}

    ordered_sources = []
    for name, source in source_files.items():
        match = GENERATED_IMAGE_RE.search(name)
        if match:
            visual_order = (
                int(match.group(2)) if match.group(2).isdigit() else 1_000_000
            )
            ordered_sources.append((int(match.group(1)), visual_order, name, source))
    ordered_sources.sort()

    per_page_counter: Counter[int] = Counter()
    for page_index, _, source_name, source in ordered_sources:
        page_number = page_index + 1
        per_page_counter[page_number] += 1
        figure_id = f"{report_id}-fig-p{page_number:04d}-{per_page_counter[page_number]:03d}"
        destination_name = f"{figure_id}.png"
        destination = figure_dir / destination_name
        hashes, dimensions = normalize_and_hash_image(source, destination)
        page_markdown = chunks[page_index].get("text", "") if page_index < len(chunks) else ""
        caption = image_caption(page_markdown, source_name)
        page = document[page_index]
        classification = classify_visual(
            page_number=page_number,
            image_size=dimensions,
            page_size_points=(page.rect.width, page.rect.height),
            caption=caption,
            page_tables=chunks[page_index].get("tables", []),
        )
        relative_asset_path = f"assets/figures/{destination_name}"
        replacement[source_name] = relative_asset_path
        page_assets[page_number].append(figure_id)
        figures.append(
            {
                "figure_id": figure_id,
                "report_id": report_id,
                "page": page_number,
                "asset_path": (final_report_dir / relative_asset_path).as_posix(),
                "caption": caption,
                "classification": classification,
                "render_dpi": IMAGE_DPI,
                "extraction_method": EXTRACTION_METHOD,
                **hashes,
            }
        )

    def replace_reference(match: re.Match[str]) -> str:
        alt, target = match.groups()
        basename = Path(target).name
        return f"![{alt}]({replacement.get(basename, target)})"

    for chunk in chunks:
        chunk["text"] = IMAGE_REF_RE.sub(replace_reference, chunk.get("text", ""))
    return figures, page_assets


def ocr_page(page: pymupdf.Page) -> str:
    """OCR one raster page with Tesseract without modifying the source PDF."""
    pixmap = page.get_pixmap(dpi=300, colorspace=pymupdf.csRGB, alpha=False)
    completed = subprocess.run(
        ["tesseract", "stdin", "stdout", "-l", "eng", "--psm", "3"],
        input=pixmap.tobytes("png"),
        capture_output=True,
        check=True,
        timeout=180,
    )
    return completed.stdout.decode("utf-8", errors="replace").strip()


def page_scan_metrics(document: pymupdf.Document, page_number: int, plain_text: str) -> dict[str, Any]:
    page = document[page_number - 1]
    page_area = max(1.0, page.rect.width * page.rect.height)
    image_coverage = 0.0
    for info in page.get_image_info():
        bbox = pymupdf.Rect(info.get("bbox", (0, 0, 0, 0)))
        image_coverage = max(image_coverage, bbox.get_area() / page_area)
    text_characters = len(re.sub(r"\s+", "", plain_text))
    return {
        "text_characters": text_characters,
        "maximum_raster_image_page_coverage": round(image_coverage, 4),
        "needs_ocr": text_characters < 30 and image_coverage >= 0.75,
    }


def fallback_chunks(pdf_path: str) -> list[dict[str, Any]]:
    chunks: list[dict[str, Any]] = []
    with pymupdf.open(pdf_path) as document:
        for page_index, page in enumerate(document):
            text = page.get_text("text", sort=True)
            chunks.append(
                {
                    "metadata": {
                        **document.metadata,
                        "page_count": len(document),
                        "page": page_index + 1,
                    },
                    "toc_items": [],
                    "tables": [],
                    "images": page.get_image_info(),
                    "graphics": [],
                    "text": text,
                    "words": [],
                }
            )
    return chunks


def process_one_document(job: dict[str, Any]) -> dict[str, Any]:
    report = job["report"]
    source = job["manifest"]
    report_id = report["report_id"]
    pdf_path = Path(source["local_path"])
    interim_dir = Path(job["interim_dir"])
    final_dir = interim_dir / report_id
    refresh = bool(job.get("refresh"))

    existing_metadata = final_dir / "document.json"
    if existing_metadata.exists() and not refresh:
        metadata = json.loads(existing_metadata.read_text(encoding="utf-8"))
        if (
            metadata.get("source_sha256") == source["sha256"]
            and metadata.get("processor_version") == PROCESSOR_VERSION
        ):
            return {
                "report_id": report_id,
                "status": "existing",
                "page_count": metadata["page_count"],
                "figure_count": metadata["figure_count"],
                "table_count": metadata["table_count"],
                "needs_ocr_pages": metadata["needs_ocr_pages"],
                "ocr_applied_pages": metadata.get("ocr_applied_pages", []),
                "duration_seconds": 0.0,
            }

    started = time.perf_counter()
    work_parent = interim_dir / ".work"
    work_parent.mkdir(parents=True, exist_ok=True)
    work_dir = Path(tempfile.mkdtemp(prefix=f"{report_id}-", dir=work_parent))
    generated_dir = work_dir / "generated"
    figure_dir = work_dir / "assets" / "figures"
    generated_dir.mkdir(parents=True)
    extraction_method = EXTRACTION_METHOD
    extraction_warnings: list[str] = []

    try:
        try:
            chunks = _pymupdf4llm_chunks(
                str(pdf_path), write_images=True, image_path=str(generated_dir)
            )
        except Exception as exc:
            extraction_method = "pymupdf-sorted-text-fallback"
            extraction_warnings.append(f"layout extraction failed: {type(exc).__name__}: {exc}")
            chunks = fallback_chunks(str(pdf_path))

        with pymupdf.open(pdf_path) as document:
            figures, page_assets = rewrite_and_catalog_images(
                report_id=report_id,
                chunks=chunks,
                generated_dir=generated_dir,
                figure_dir=figure_dir,
                document=document,
                final_report_dir=final_dir,
            )
            pages: list[dict[str, Any]] = []
            markdown_pages: list[str] = []
            total_tables = 0
            needs_ocr_pages: list[int] = []
            ocr_applied_pages: list[int] = []
            headings: list[dict[str, Any]] = []
            for page_index, chunk in enumerate(chunks):
                page_number = page_index + 1
                markdown = chunk.get("text", "").strip()
                plain = markdown_to_plain(markdown)
                # Layout extraction may intentionally render a cover as one image.
                # Retain its embedded text layer in pages.jsonl for metadata and
                # evidence extraction, without duplicating it in the Markdown.
                source_text = document[page_index].get_text("text", sort=True).strip()
                if len(re.sub(r"\s+", "", plain)) < 30 and len(source_text) > len(plain):
                    plain = source_text
                scan = page_scan_metrics(document, page_number, plain)
                if scan["needs_ocr"]:
                    try:
                        ocr_text = ocr_page(document[page_index])
                        if len(re.sub(r"\s+", "", ocr_text)) >= 30:
                            plain = ocr_text
                            markdown = (
                                markdown
                                + "\n\n<!-- OCR: Tesseract 5, eng, 300 DPI -->\n\n"
                                + ocr_text
                            ).strip()
                            scan["needs_ocr"] = False
                            scan["text_characters"] = len(re.sub(r"\s+", "", plain))
                            scan["ocr_applied"] = True
                            ocr_applied_pages.append(page_number)
                        else:
                            needs_ocr_pages.append(page_number)
                    except Exception as exc:
                        needs_ocr_pages.append(page_number)
                        extraction_warnings.append(
                            f"OCR failed on page {page_number}: {type(exc).__name__}: {exc}"
                        )
                page_tables = chunk.get("tables", [])
                total_tables += len(page_tables)
                for level, title in HEADING_RE.findall(markdown):
                    headings.append(
                        {
                            "page": page_number,
                            "level": len(level),
                            "title": markdown_to_plain(title),
                        }
                    )
                pages.append(
                    {
                        "report_id": report_id,
                        "page": page_number,
                        "markdown": markdown,
                        "text": plain,
                        "tables": page_tables,
                        "source_images": chunk.get("images", []),
                        "source_graphics": chunk.get("graphics", []),
                        "figure_ids": page_assets.get(page_number, []),
                        **scan,
                    }
                )
                markdown_pages.append(f"<!-- page: {page_number} -->\n\n{markdown}\n")

            metadata = {
                "report_id": report_id,
                "title": report.get("title"),
                "source_pdf": pdf_path.as_posix(),
                "source_sha256": source["sha256"],
                "source_bytes": source["bytes"],
                "source_page_url": report.get("source_page_url"),
                "processor_version": PROCESSOR_VERSION,
                "extraction_method": extraction_method,
                "pymupdf_version": pymupdf.version[0],
                "pymupdf4llm_version": getattr(pymupdf4llm, "__version__", None),
                "processed_at": utc_now(),
                "duration_seconds": round(time.perf_counter() - started, 3),
                "page_count": len(document),
                "text_characters": sum(len(page["text"]) for page in pages),
                "table_count": total_tables,
                "figure_count": len(figures),
                "needs_ocr_pages": needs_ocr_pages,
                "ocr_applied_pages": ocr_applied_pages,
                "ocr_engine": "Tesseract 5 (eng, 300 DPI)" if ocr_applied_pages else None,
                "headings": headings,
                "pdf_metadata": document.metadata,
                "warnings": extraction_warnings,
            }

        (work_dir / "document.md").write_text(
            "\n".join(markdown_pages), encoding="utf-8"
        )
        write_jsonl(work_dir / "pages.jsonl", pages)
        write_jsonl(work_dir / "figures.jsonl", figures)
        write_json(work_dir / "document.json", metadata)
        shutil.rmtree(generated_dir, ignore_errors=True)
        if final_dir.exists():
            shutil.rmtree(final_dir)
        os.replace(work_dir, final_dir)
        return {
            "report_id": report_id,
            "status": "processed",
            "page_count": metadata["page_count"],
            "figure_count": metadata["figure_count"],
            "table_count": metadata["table_count"],
            "needs_ocr_pages": needs_ocr_pages,
            "ocr_applied_pages": ocr_applied_pages,
            "duration_seconds": metadata["duration_seconds"],
        }
    except Exception:
        shutil.rmtree(work_dir, ignore_errors=True)
        raise


def build_global_figure_index(interim_dir: Path) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    figures: list[dict[str, Any]] = []
    for path in sorted(interim_dir.glob("*/figures.jsonl")):
        figures.extend(load_jsonl(path))

    parent = list(range(len(figures)))

    def find(index: int) -> int:
        while parent[index] != index:
            parent[index] = parent[parent[index]]
            index = parent[index]
        return index

    def union(left: int, right: int) -> None:
        left_root, right_root = find(left), find(right)
        if left_root != right_root:
            parent[right_root] = left_root

    exact: dict[str, int] = {}
    phash_buckets: dict[str, list[int]] = defaultdict(list)
    for index, figure in enumerate(figures):
        digest = figure["sha256_normalized_png"]
        if digest in exact:
            union(index, exact[digest])
        else:
            exact[digest] = index
        phash = figure.get("phash_256", "")
        if phash:
            phash_buckets[phash[:2]].append(index)

    # Compare perceptual hashes within a coarse prefix and adjacent first-byte
    # buckets. This bounds work while catching ordinary resize/re-encode variants.
    bucket_keys = sorted(phash_buckets)
    for key in bucket_keys:
        candidates = list(phash_buckets[key])
        key_value = int(key, 16)
        for other_key in bucket_keys:
            if other_key <= key or abs(int(other_key, 16) - key_value) > 16:
                continue
            candidates.extend(phash_buckets[other_key])
        own = phash_buckets[key]
        for left_pos, left in enumerate(own):
            left_hash = int(figures[left]["phash_256"], 16)
            left_ratio = figures[left]["width"] / max(1, figures[left]["height"])
            for right in candidates:
                if right <= left:
                    continue
                right_ratio = figures[right]["width"] / max(1, figures[right]["height"])
                if max(left_ratio, right_ratio) / max(0.01, min(left_ratio, right_ratio)) > 1.2:
                    continue
                distance = (left_hash ^ int(figures[right]["phash_256"], 16)).bit_count()
                if distance <= 12:
                    union(left, right)

    groups: dict[int, list[int]] = defaultdict(list)
    for index in range(len(figures)):
        groups[find(index)].append(index)
    clusters: list[dict[str, Any]] = []
    for indices in groups.values():
        if len(indices) < 2:
            continue
        figure_ids = [figures[index]["figure_id"] for index in indices]
        cluster_id = "visual-cluster-" + hashlib.sha256(
            "|".join(sorted(figure_ids)).encode("utf-8")
        ).hexdigest()[:12]
        exact_cluster = len(
            {figures[index]["sha256_normalized_png"] for index in indices}
        ) == 1
        clusters.append(
            {
                "cluster_id": cluster_id,
                "figure_ids": figure_ids,
                "size": len(indices),
                "match_type": "exact" if exact_cluster else "perceptual",
                "phash_distance_threshold": 12,
            }
        )
        for index in indices:
            figures[index]["near_duplicate_cluster_id"] = cluster_id
    clusters.sort(key=lambda cluster: (-cluster["size"], cluster["cluster_id"]))
    figures.sort(key=lambda figure: figure["figure_id"])
    write_jsonl(interim_dir / "figures.jsonl", figures)
    write_json(interim_dir / "figure_duplicate_clusters.json", clusters)
    return figures, clusters


def process_corpus(
    inventory: list[dict[str, Any]],
    manifest: list[dict[str, Any]],
    *,
    interim_dir: Path,
    workers: int,
    refresh: bool,
) -> dict[str, Any]:
    source_by_id = {row["report_id"]: row for row in manifest}
    jobs = [
        {
            "report": report,
            "manifest": source_by_id[report["report_id"]],
            "interim_dir": interim_dir.as_posix(),
            "refresh": refresh,
        }
        for report in inventory
    ]
    results: list[dict[str, Any]] = []
    failures: list[dict[str, str]] = []
    with concurrent.futures.ProcessPoolExecutor(max_workers=max(1, workers)) as pool:
        futures = {pool.submit(process_one_document, job): job for job in jobs}
        for future in concurrent.futures.as_completed(futures):
            job = futures[future]
            try:
                result = future.result()
                results.append(result)
                status = result["status"]
            except Exception as exc:
                failures.append(
                    {
                        "report_id": job["report"]["report_id"],
                        "error": f"{type(exc).__name__}: {exc}",
                    }
                )
                status = "failed"
            completed = len(results) + len(failures)
            print(
                f"convert: {completed}/{len(jobs)} {status}: "
                f"{job['report']['report_id']}",
                file=sys.stderr,
            )
    figures, clusters = build_global_figure_index(interim_dir)
    result_by_id = {result["report_id"]: result for result in results}
    ordered_results = [
        result_by_id[report["report_id"]]
        for report in inventory
        if report["report_id"] in result_by_id
    ]
    write_jsonl(interim_dir / "conversion_manifest.jsonl", ordered_results)
    summary = {
        "updated_at": utc_now(),
        "processor_version": PROCESSOR_VERSION,
        "extraction_method": EXTRACTION_METHOD,
        "inventory_count": len(inventory),
        "processed_count": len(results),
        "failed_count": len(failures),
        "failures": failures,
        "page_count": sum(result["page_count"] for result in results),
        "table_count": sum(result["table_count"] for result in results),
        "figure_count": len(figures),
        "figure_near_duplicate_cluster_count": len(clusters),
        "needs_ocr_document_count": sum(
            bool(result["needs_ocr_pages"]) for result in results
        ),
        "needs_ocr_page_count": sum(
            len(result["needs_ocr_pages"]) for result in results
        ),
        "ocr_applied_document_count": sum(
            bool(result.get("ocr_applied_pages")) for result in results
        ),
        "ocr_applied_page_count": sum(
            len(result.get("ocr_applied_pages", [])) for result in results
        ),
        "status_counts": dict(Counter(result["status"] for result in results)),
        "duration_seconds_sum": round(
            sum(result["duration_seconds"] for result in results), 3
        ),
    }
    write_json(interim_dir / "conversion_summary.json", summary)
    return summary


def select_reports(
    inventory: list[dict[str, Any]], limit: int | None, ids: str | None
) -> list[dict[str, Any]]:
    if ids:
        selected_ids = {value.strip() for value in ids.split(",") if value.strip()}
        missing = selected_ids - {row["report_id"] for row in inventory}
        if missing:
            raise SystemExit(f"unknown report IDs: {sorted(missing)}")
        inventory = [row for row in inventory if row["report_id"] in selected_ids]
    if limit is not None:
        inventory = inventory[:limit]
    return inventory


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Convert IMF PDFs to interim Markdown")
    parser.add_argument(
        "command", choices=["benchmark", "convert", "all"], help="processing stage"
    )
    parser.add_argument("--raw-dir", type=Path, default=Path("data/raw"))
    parser.add_argument("--interim-dir", type=Path, default=Path("data/interim"))
    parser.add_argument("--workers", type=int, default=min(6, os.cpu_count() or 1))
    parser.add_argument("--sample-count", type=int, default=12)
    parser.add_argument("--limit", type=int)
    parser.add_argument("--ids", help="comma-separated report IDs")
    parser.add_argument("--refresh", action="store_true")
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    inventory = load_jsonl(args.raw_dir / "manifests" / "inventory.jsonl")
    manifest = load_jsonl(args.raw_dir / "manifests" / "download_manifest.jsonl")
    if not inventory or not manifest:
        raise SystemExit("raw inventory/download manifest is missing")
    inventory = select_reports(inventory, args.limit, args.ids)
    manifest_ids = {row["report_id"] for row in manifest}
    missing = {row["report_id"] for row in inventory} - manifest_ids
    if missing:
        raise SystemExit(f"download manifest missing report IDs: {sorted(missing)}")

    if args.command in {"benchmark", "all"}:
        run_benchmark(
            inventory,
            manifest,
            interim_dir=args.interim_dir,
            workers=args.workers,
            sample_count=min(args.sample_count, len(inventory)),
        )
    if args.command in {"convert", "all"}:
        summary = process_corpus(
            inventory,
            manifest,
            interim_dir=args.interim_dir,
            workers=args.workers,
            refresh=args.refresh,
        )
        if summary["failed_count"]:
            return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())