File size: 33,328 Bytes
cd6dbae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Compare a PDF with the Markdown that MarkItDown (or any converter) produced from it.

Finds what the Markdown lost or damaged and writes a work directory containing:

  report.json             machine-readable findings (one "item" per problem)
  validation_report.md    human-readable summary
  assets/*.png            crops of figures / tables / equations / glyph examples

Item types
  text             lines present in the PDF text layer but absent from the Markdown
  figure / graphic charts, diagrams, images (no text layer -> must be read visually)
  table            tables whose row/column structure was lost (draft GFM provided)
  equation         display equations that are missing or garbled
  glyph_corruption raw glyph codes such as "/C15" or "(cid:12)" left in the Markdown

Usage
  python analyze.py --pdf paper.pdf --md paper.md --out work/
  python analyze.py --pdf paper.pdf --md paper_appended.md --out work_verify/ --verify
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import os
import re
import sys
from collections import Counter, defaultdict

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import common as C  # noqa: E402

COVERED, PARTIAL = 0.85, 0.5  # coverage >= COVERED -> ok ; < PARTIAL -> missing

MATH_SIGNAL = re.compile(r"[=¼∑Σ∫√±≤≥≠≈∈∏ðÞ□]|/[Cg]\d{1,3}")
EQ_TAG = re.compile(r"(?:ð|\()\s*(\d{1,3})\s*(?:Þ|\))\s*$")
GLYPH_RX = re.compile(r"(?<![A-Za-z0-9])/[Cg]\d{1,3}|\(cid:\d+\)|[\ue000-\uf8ff\ufffd]")
GLYPH_HINTS = {  # heuristic only (TeX/Symbol fonts) -> always confirm on the crop
    "/C0": "−", "/C15": "•", "/C20": "≤", "/C21": "≥", "/C211": "©",
}
FIG_CAP = re.compile(r"^(Fig(?:ure)?\.?)\s*(\d+[A-Za-z]?)\s*[.:\u2013\u2014-]", re.I)
TAB_CAP = re.compile(r"^(Table)\s+([A-Za-z]?\d+[A-Za-z]?)\s*(?:[.:\u2013\u2014-]|$)", re.I)


# --------------------------------------------------------------------------- #
# geometry helpers
# --------------------------------------------------------------------------- #
def union(bs):
    return (min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs))


def center(b):
    return ((b[0] + b[2]) / 2, (b[1] + b[3]) / 2)


def inside(pt, b, pad=1.5):
    return b[0] - pad <= pt[0] <= b[2] + pad and b[1] - pad <= pt[1] <= b[3] + pad


def clip(b, w, h, pad=0):
    return (max(0, b[0] - pad), max(0, b[1] - pad), min(w, b[2] + pad), min(h, b[3] + pad))


def overlap_frac(a, b):
    x0, y0, x1, y1 = max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3])
    if x1 <= x0 or y1 <= y0:
        return 0.0
    return (x1 - x0) * (y1 - y0) / max(1e-6, (a[2] - a[0]) * (a[3] - a[1]))


# --------------------------------------------------------------------------- #
# cropping
# --------------------------------------------------------------------------- #
class Cropper:
    def __init__(self, pdf, assets_dir, dpi):
        self.pdf, self.dir, self.dpi = pdf, assets_dir, dpi
        os.makedirs(assets_dir, exist_ok=True)

    def crop(self, page_no, bbox, name, dpi=None):
        p = self.pdf.pages[page_no - 1]
        b = clip(bbox, float(p.width), float(p.height), 4)
        path = os.path.join(self.dir, name + ".png")
        try:
            p.crop(b).to_image(resolution=dpi or self.dpi).save(path)
            return os.path.relpath(path, os.path.dirname(self.dir))
        except Exception as e:  # pragma: no cover
            print(f"  ! crop failed for {name}: {e}", file=sys.stderr)
            return None

    def page(self, page_no, dpi=90):
        p = self.pdf.pages[page_no - 1]
        path = os.path.join(self.dir, f"page-{page_no:02d}.png")
        if not os.path.exists(path):
            p.to_image(resolution=dpi).save(path)
        return os.path.relpath(path, os.path.dirname(self.dir))


# --------------------------------------------------------------------------- #
# tables
# --------------------------------------------------------------------------- #
def rule_levels(page):
    """Horizontal rules grouped by y-level. Segmented rules (drawn cell by cell) are merged.

    Returns [(y, x0, x1, coverage)] sorted by y, coverage = fraction of [x0,x1] actually inked.
    """
    segs = []
    for o in list(page.rects) + list(page.lines):
        h = abs(o["bottom"] - o["top"])
        w = o["x1"] - o["x0"]
        if h <= 1.8 and w >= 12:
            segs.append(((o["top"] + o["bottom"]) / 2, o["x0"], o["x1"]))
    segs.sort()
    levels, cur = [], []
    for sgm in segs:
        if cur and abs(sgm[0] - cur[-1][0]) > 1.0:
            levels.append(cur); cur = []
        cur.append(sgm)
    if cur:
        levels.append(cur)
    out = []
    for lv in levels:
        xs = sorted((s_[1], s_[2]) for s_ in lv)
        merged = [list(xs[0])]
        for x0, x1 in xs[1:]:
            if x0 <= merged[-1][1] + 1.5:
                merged[-1][1] = max(merged[-1][1], x1)
            else:
                merged.append([x0, x1])
        # runs separated by > 8pt belong to different tables/columns
        groups = [[merged[0]]]
        for m in merged[1:]:
            (groups[-1].append(m) if m[0] - groups[-1][-1][1] <= 8 else groups.append([m]))
        y = sum(s_[0] for s_ in lv) / len(lv)
        for g in groups:
            x0, x1 = g[0][0], g[-1][1]
            inked = sum(m[1] - m[0] for m in g)
            out.append((y, x0, x1, inked / max(1e-6, x1 - x0)))
    return out


def find_captions(pdfpage: C.PdfPage):
    """Return [(kind,label,line,block_lines)] for real captions (short blocks starting 'Fig. N.'/'Table N')."""
    by_block = defaultdict(list)
    for l in pdfpage.lines:
        by_block[l.block].append(l)
    caps = []
    for l in pdfpage.lines:
        blk = by_block[l.block]
        if l is not blk[0] or len(blk) > 3:
            continue
        m = FIG_CAP.match(l.text)
        if m:
            caps.append(("figure", f"Fig. {m.group(2)}", l, blk))
            continue
        m = TAB_CAP.match(l.text)
        if m:
            caps.append(("table", f"Table {m.group(2)}", l, blk))
    return caps


def build_table(plpage, pdfpage: C.PdfPage, cap_lines, all_caps):
    """Locate a table below its caption using its horizontal rules and draft a GFM table."""
    cb = union([l.bbox for l in cap_lines])
    levels = rule_levels(plpage)
    # do not run into the next caption sitting below in the same column
    limit = float(plpage.height)
    for _, _, _, blk in all_caps:
        bb = union([x.bbox for x in blk])
        if bb[1] > cb[3] + 5 and min(bb[2], cb[2] + 250) - max(bb[0], cb[0]) > 0 and abs(bb[0] - cb[0]) < 60:
            limit = min(limit, bb[1])
    tops = [lv for lv in levels if 0 <= lv[0] - cb[3] <= 45 and abs(lv[1] - cb[0]) <= 25 and lv[3] >= 0.85]
    if not tops:
        return None
    top = min(tops, key=lambda lv: lv[0])
    chain = [top] + [lv for lv in levels if top[0] + 3 < lv[0] < limit and abs(lv[1] - top[1]) <= 8
                     and abs(lv[2] - top[2]) <= 8 and lv[3] >= 0.5]
    full = [lv for lv in chain if lv[3] >= 0.85]
    if len(full) < 2:
        return None
    bottom = full[-1][0]
    header_cut = full[-2][0] if len(full) >= 3 else None
    x0, x1 = top[1], top[2]
    bbox = (x0, cb[1], x1, bottom + 2)
    region = plpage.crop((x0 - 2, top[0] - 1, x1 + 2, bottom + 1))
    words = region.extract_words(x_tolerance=1.5, y_tolerance=2, keep_blank_chars=False)
    if not words:
        return None
    return {"bbox": bbox, "caption_bbox": cb, "draft": draft_gfm(words, header_cut), "n_words": len(words),
            "closed": True}


def _rows(words, tol=3.0):
    words = sorted(words, key=lambda w: (w["top"], w["x0"]))
    rows, cur, ref = [], [], None
    for w in words:
        if ref is None or abs(w["top"] - ref) <= tol:
            cur.append(w)
            ref = w["top"] if ref is None else ref
        else:
            rows.append(cur)
            cur, ref = [w], w["top"]
    if cur:
        rows.append(cur)
    return rows


def draft_gfm(words, header_cut):
    body_w = [w for w in words if header_cut is None or (w["top"] + w["bottom"]) / 2 > header_cut]
    head_w = [w for w in words if header_cut is not None and (w["top"] + w["bottom"]) / 2 <= header_cut]
    if header_cut is None:  # no header rule: first text row is the header
        rows0 = _rows(words)
        head_w, body_w = rows0[0], [w for r in rows0[1:] for w in r]
    if not body_w:
        return ""
    # column detection from body words (gap > 5pt starts a new column)
    ivs = sorted((w["x0"], w["x1"]) for w in body_w)
    cols = [list(ivs[0])]
    for a, b in ivs[1:]:
        if a - cols[-1][1] > 5:
            cols.append([a, b])
        else:
            cols[-1][1] = max(cols[-1][1], b)
    edges = [(cols[i][1] + cols[i + 1][0]) / 2 for i in range(len(cols) - 1)]

    def col_of(w):
        cx = (w["x0"] + w["x1"]) / 2
        for i, e in enumerate(edges):
            if cx < e:
                return i
        return len(cols) - 1

    def cells(row):
        cs = [""] * len(cols)
        for w in sorted(row, key=lambda w: w["x0"]):
            i = col_of(w)
            cs[i] = (cs[i] + " " + w["text"]).strip()
        return cs

    header = [""] * len(cols)
    for r in _rows(head_w):
        r = sorted(r, key=lambda w: w["x0"])
        hc = [[r[0]["x0"], r[0]["x1"], r[0]["text"]]]
        for w in r[1:]:
            if w["x0"] - hc[-1][1] <= 5:
                hc[-1][1] = w["x1"]; hc[-1][2] += " " + w["text"]
            else:
                hc.append([w["x0"], w["x1"], w["text"]])
        for x0_, x1_, txt in hc:
            ov = [i for i, (c0, c1) in enumerate(cols) if min(c1, x1_) - max(c0, x0_) > 0]
            if ov:
                i = ov[0]
            else:
                cx = (x0_ + x1_) / 2
                i = min(range(len(cols)), key=lambda k: abs((cols[k][0] + cols[k][1]) / 2 - cx))
            header[i] = (header[i] + " " + txt).strip()
    rows = [cells(r) for r in _rows(body_w)]
    # merge wrapped label cells
    merged: list[list[str]] = []
    i = 0
    while i < len(rows):
        r = rows[i]
        only0 = r[0] and not any(r[1:])
        if only0 and i + 1 < len(rows) and not rows[i + 1][0] and any(rows[i + 1][1:]):
            rows[i + 1][0] = r[0]
        elif only0 and merged and (r[0][:1].islower() or r[0][:1] in "()"):
            merged[-1][0] += " " + r[0]
        else:
            merged.append(r)
        i += 1
    esc = lambda s: s.replace("|", "\\|")
    out = ["| " + " | ".join(esc(h) for h in header) + " |", "|" + "|".join(["---"] * len(cols)) + "|"]
    out += ["| " + " | ".join(esc(c) for c in r) + " |" for r in merged]
    return "\n".join(out)


# --------------------------------------------------------------------------- #
# figures / graphics
# --------------------------------------------------------------------------- #
def graphic_clusters(plpage):
    objs = []
    for kind, lst in (("image", plpage.images), ("curve", plpage.curves), ("rect", plpage.rects), ("line", plpage.lines)):
        for o in lst:
            b = (o["x0"], o["top"], o["x1"], o["bottom"])
            w, h = b[2] - b[0], b[3] - b[1]
            if kind != "image" and ((w > 0.75 * plpage.width and h < 3) or (w < 0.8 and h < 0.8)):
                continue  # page-wide rules / dots
            objs.append((kind, b))
    n = len(objs)
    parent = list(range(n))

    def find(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    GAP = 7
    order = sorted(range(n), key=lambda i: objs[i][1][0])
    for ai, i in enumerate(order):
        bi = objs[i][1]
        for j in order[ai + 1:]:
            bj = objs[j][1]
            if bj[0] > bi[2] + GAP:
                break
            if bj[1] <= bi[3] + GAP and bj[3] >= bi[1] - GAP:
                parent[find(i)] = find(j)
    groups = defaultdict(list)
    for i in range(n):
        groups[find(i)].append(objs[i])
    res = []
    for g in groups.values():
        b = union([x[1] for x in g])
        k = Counter(x[0] for x in g)
        res.append({"bbox": b, "n_image": k["image"], "n_curve": k["curve"], "n_rect": k["rect"], "n_line": k["line"]})
    return res


def find_graphics(plpage, pdfpage: C.PdfPage, caps):
    fig_caps = [c for c in caps if c[0] == "figure"]
    clusters = []
    for g in graphic_clusters(plpage):
        b = g["bbox"]
        w, h = b[2] - b[0], b[3] - b[1]
        if w < 25 or h < 15:
            continue
        n_vec = g["n_curve"] + g["n_rect"] + g["n_line"]
        if not (g["n_image"] >= 1 or n_vec >= 12):
            continue
        words = sum(1 for l in pdfpage.lines if inside(center(l.bbox), b))
        cap, best = None, 1e9
        for kind, label, cl, blk in fig_caps:
            cbb = union([x.bbox for x in blk])
            d_below, d_above = cbb[1] - b[3], b[1] - cbb[3]
            xov = min(b[2], cbb[2]) - max(b[0], cbb[0]) > 0
            dist = d_below if -15 <= d_below <= 60 else d_above if -15 <= d_above <= 40 else None
            if dist is not None and xov and abs(dist) < best:
                cap, best = (label, blk, cbb), abs(dist)
        tableish = g["n_curve"] == 0 and g["n_image"] == 0 and words >= 10 and cap is None
        if tableish:
            continue
        g.update(words_inside=words, caption=cap)
        clusters.append(g)
    # merge sub-figures that share one caption
    merged, by_cap = [], defaultdict(list)
    for g in clusters:
        (by_cap[g["caption"][0]].append(g) if g["caption"] else merged.append(g))
    for label, gs in by_cap.items():
        b = union([x["bbox"] for x in gs])
        m = dict(gs[0])
        m["bbox"] = b
        for k in ("n_image", "n_curve", "n_rect", "n_line", "words_inside"):
            m[k] = sum(x[k] for x in gs)
        merged.append(m)
    return sorted(merged, key=lambda g: g["bbox"][1])


# --------------------------------------------------------------------------- #
# equations
# --------------------------------------------------------------------------- #
def mathlike(l: C.Line):
    t = l.text
    if MATH_SIGNAL.search(t):
        return True
    words = t.split()
    prose = len(words) >= 5 and sum(1 for w in words if len(re.sub(r"\W", "", w)) >= 3) >= 4
    return (not prose) and len(words) <= 5 and len(t) <= 32


def find_equations(pdfpage: C.PdfPage):
    cols = Counter()
    for l in pdfpage.lines:
        if len(l.text) >= 45:
            cols[(round(l.x0), round(l.x1))] += 1
    col_ranges = [k for k, v in cols.items() if v >= 3] or [(0, pdfpage.width)]
    eqs, used = [], set()
    for seed in pdfpage.lines:
        m = EQ_TAG.search(seed.text)
        if not m or id(seed) in used or len(seed.text) > 70:
            continue
        fits = [(a, b) for a, b in col_ranges if a - 6 <= seed.x1 <= b + 6 and seed.x0 >= a - 6]
        col = min(fits) if fits else (0, pdfpage.width)  # widest matching column
        cand = sorted((l for l in pdfpage.lines if l.x0 >= col[0] - 6 and l.x1 <= col[1] + 6
                       and seed.y0 - 70 <= l.y0 <= seed.y1 + 45), key=lambda l: (l.y0, l.x0))
        if seed not in cand:
            continue
        keep = {id(seed)}
        si = cand.index(seed)
        for rng in (range(si - 1, -1, -1), range(si + 1, len(cand))):
            prev = seed
            for i in rng:
                l = cand[i]
                if EQ_TAG.search(l.text) and len(l.text) <= 70:
                    break  # next equation starts here
                if not mathlike(l) or abs(l.y0 - prev.y0) > 26 and abs(l.y1 - prev.y1) > 26:
                    break
                keep.add(id(l))
                prev = l
        members = [l for l in cand if id(l) in keep]
        if not any(MATH_SIGNAL.search(l.text) for l in members):
            continue
        for l in members:
            used.add(id(l))
        eqs.append({"tag": m.group(1), "lines": members, "bbox": union([l.bbox for l in members])})
    return eqs


# --------------------------------------------------------------------------- #
# main analysis
# --------------------------------------------------------------------------- #
def locate_line(md_line: str, pdfpage: C.PdfPage):
    """Best-matching PDF line for an MD line (used to crop glyph-corruption examples)."""
    g = C.squash(GLYPH_RX.sub("", md_line))
    if len(g) < 6:
        return None
    grams = {g[i:i + 4] for i in range(len(g) - 3)}
    best, score = None, 0.0
    for l in pdfpage.lines:
        s = C.squash(l.text)
        lg = {s[i:i + 4] for i in range(max(0, len(s) - 3))}
        if not lg:
            continue
        sc = len(grams & lg) / max(1, len(grams | lg))
        if sc > score:
            best, score = l, sc
    return best if score >= 0.25 else None


def sev_text(n_chars):
    return "high" if n_chars >= 200 else "medium" if n_chars >= 60 else "low"


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--pdf", required=True)
    ap.add_argument("--md", required=True)
    ap.add_argument("--out", required=True, help="work directory (created)")
    ap.add_argument("--dpi", type=int, default=160, help="crop resolution (default 160)")
    ap.add_argument("--page-regex", help="regex (group 1 = page number) if the MD uses custom page markers")
    ap.add_argument("--tables", choices=["auto", "always", "never"], default="auto",
                    help="auto: draft a GFM table when the MD has no pipe table or the table text is damaged")
    ap.add_argument("--no-graphics", action="store_true")
    ap.add_argument("--verify", action="store_true",
                    help="MD already contains an appendix: report what is still unresolved")
    a = ap.parse_args()

    import pdfplumber

    raw = open(a.md, "rb").read().decode("utf-8", errors="replace")
    eol = "\r\n" if "\r\n" in raw else "\n"
    body, appendix = C.strip_appendix(raw)
    md_pages, mode = C.split_md_pages(body, a.page_regex)
    appx_idx = C.PageIndex(appendix) if appendix else None
    appended = set(re.findall(r"<!-- item:(\S+) -->", appendix)) if a.verify else set()
    skipped_log = dict(re.findall(r"^skipped:(\S+?): ?(.*)$", appendix, re.M)) if a.verify else {}

    pdfpages, engine = C.extract_pdf_lines(a.pdf)
    n_pdf = len(pdfpages)
    global_idx = C.PageIndex(body)

    os.makedirs(a.out, exist_ok=True)
    assets = os.path.join(a.out, "assets")
    if os.path.isdir(assets):  # stale crops from an earlier run would be confusing
        for f in os.listdir(assets):
            if f.endswith(".png"):
                os.remove(os.path.join(assets, f))
    items: list[dict] = []
    per_page = {}

    with pdfplumber.open(a.pdf) as pdf:
        crop = Cropper(pdf, assets, a.dpi)

        # ---------------- pass 1: text coverage --------------------------------
        for pg in pdfpages:
            idx = C.PageIndex(md_pages.get(pg.number, ""))
            for l in pg.lines:
                c = idx.coverage(l.text)
                if c is None:
                    continue
                l.cov = c
                if c >= COVERED:
                    continue
                l.status = "missing" if c < PARTIAL else "partial"
                long_line = len(C.squash(l.text)) >= 14 and len(C.tokens(l.text)) >= 3
                gidx_c = global_idx.coverage(l.text, consume=False) if (mode == "markers" and long_line) else 0
                if gidx_c is not None and gidx_c >= COVERED:
                    l.status = "misplaced"
                elif appx_idx is not None and (appx_idx.coverage(l.text, consume=False) or 0) >= COVERED:
                    l.status = "recovered"

        # ---------------- pass 2: structured regions ---------------------------
        regions: dict[int, list[dict]] = defaultdict(list)
        for pg in pdfpages:
            plpage = pdf.pages[pg.number - 1]
            caps = find_captions(pg)

            # tables
            tcount = 0
            if a.tables != "never":
                for kind, label, cl, blk in caps:
                    if kind != "table":
                        continue
                    t = build_table(plpage, pg, blk, caps)
                    if not t:
                        continue
                    tcount += 1
                    inside_lines = [l for l in pg.lines if inside(center(l.bbox), t["bbox"], 2)]
                    bad = [l for l in inside_lines if l.status in ("missing", "partial")]
                    md_text = md_pages.get(pg.number, "")
                    has_pipes = bool(re.search(r"^\s*\|.*\|\s*\n\s*\|[\s:\-|]+\|", md_text, re.M))
                    if a.tables == "auto" and has_pipes and not bad:
                        continue
                    cap_text = C.join_lines(blk)
                    it = {"id": f"TB-p{pg.number}-{tcount}", "type": "table", "page": pg.number,
                          "label": label, "bbox": [round(x, 1) for x in t["bbox"]],
                          "severity": "high" if bad else "medium",
                          "caption": cap_text,
                          "evidence": {"reason": ("table text is damaged in the MD (%d cells missing/scrambled)" % len(bad)) if bad
                                       else "table rows are flattened text; column structure is lost",
                                       "damaged_cells": [l.text for l in bad][:20]},
                          "draft_markdown": t["draft"],
                          "crop": crop.crop(pg.number, t["bbox"], f"table-{label.split()[-1]}-p{pg.number}")}
                    items.append(it)
                    regions[pg.number].append({"bbox": t["bbox"], "item": it})

            # equations
            for eq in find_equations(pg):
                garbled = any(re.search(r"[¼ðÞ□]|/[Cg]\d", l.text) for l in eq["lines"])
                bad = [l for l in eq["lines"] if l.status in ("missing", "partial")]
                if not garbled and not bad:
                    continue
                it = {"id": f"EQ-p{pg.number}-{eq['tag']}", "type": "equation", "page": pg.number,
                      "label": f"Equation ({eq['tag']})", "bbox": [round(x, 1) for x in eq["bbox"]],
                      "severity": "medium",
                      "evidence": {"reason": "equation text is garbled by font encoding" if garbled else "equation text missing from MD",
                                   "pdf_text_layer": " / ".join(l.text for l in eq["lines"])},
                      "crop": crop.crop(pg.number, eq["bbox"], f"eq-{eq['tag']}-p{pg.number}", dpi=max(a.dpi, 200))}
                items.append(it)
                regions[pg.number].append({"bbox": eq["bbox"], "item": it})

            # figures / images / charts
            if not a.no_graphics:
                for gi, g in enumerate(find_graphics(plpage, pg, caps), 1):
                    b = g["bbox"]
                    label, cap_txt, full = None, "", b
                    if g["caption"]:
                        label, blk, cbb = g["caption"]
                        cap_txt = C.join_lines(blk)
                        full = union([b, cbb])
                    small = (b[2] - b[0]) * (b[3] - b[1]) < 90 * 90
                    deco = (label is None) and (small or pg.number == 1)
                    kind = "figure" if label else "graphic"
                    it = {"id": f"{'FIG' if label else 'GFX'}-p{pg.number}-{gi}", "type": kind, "page": pg.number,
                          "label": label or "Unlabelled graphic", "bbox": [round(x, 1) for x in full],
                          "severity": "low" if deco else "high",
                          "caption": cap_txt,
                          "likely_decorative": bool(deco),
                          "evidence": {"reason": "visual content has no text-layer equivalent in the MD",
                                       "images": g["n_image"], "vector_shapes": g["n_curve"] + g["n_rect"] + g["n_line"],
                                       "text_lines_inside": g["words_inside"]},
                          "crop": crop.crop(pg.number, full, f"{'fig' if label else 'gfx'}-p{pg.number}-{gi}")}
                    items.append(it)
                    regions[pg.number].append({"bbox": full, "item": it})

        # ---------------- pass 3: leftover text items ---------------------------
        n_text = 0
        for pg in pdfpages:
            flagged = []
            for l in pg.lines:
                if l.status not in ("missing", "partial"):
                    continue
                owner = next((r for r in regions[pg.number] if inside(center(l.bbox), r["bbox"], 3)), None)
                if owner:
                    if owner["item"]["id"] in appended or owner["item"]["id"] in skipped_log:
                        l.status = "recovered"
                    owner["item"].setdefault("evidence", {}).setdefault("flagged_lines_inside", 0)
                    owner["item"]["evidence"]["flagged_lines_inside"] += 1
                    continue
                flagged.append(l)
            # group consecutive flagged lines (in reading order)
            order = {id(l): i for i, l in enumerate(pg.lines)}
            groups, cur = [], []
            for l in flagged:
                if cur and order[id(l)] != order[id(cur[-1])] + 1:
                    groups.append(cur); cur = []
                cur.append(l)
            if cur:
                groups.append(cur)
            for grp in groups:
                txt = C.join_lines(grp)
                if len(C.squash(txt)) < 3:
                    continue
                n_text += 1
                worst = min(l.cov for l in grp)
                whole_page = len(C.squash(md_pages.get(pg.number, ""))) < 20
                it = {"id": f"T-p{pg.number}-{n_text}", "type": "text", "page": pg.number,
                      "label": "Missing page" if whole_page else ("Missing text" if worst < PARTIAL else "Partially missing text"),
                      "bbox": [round(x, 1) for x in union([l.bbox for l in grp])],
                      "severity": sev_text(len(txt)),
                      "evidence": {"reason": "PDF text not found in the MD" if worst < PARTIAL else "PDF text only partly found in the MD (scrambled or truncated)",
                                   "min_coverage": round(worst, 2), "lines": len(grp)},
                      "pdf_text": txt}
                if len(txt) > 15:
                    it["crop"] = crop.crop(pg.number, union([l.bbox for l in grp]), f"text-p{pg.number}-{n_text}", dpi=110)
                items.append(it)

        for pg in pdfpages:
            per_page[pg.number] = {
                "lines": sum(1 for l in pg.lines if C.squash(l.text)),
                "missing": sum(1 for l in pg.lines if l.status == "missing"),
                "partial": sum(1 for l in pg.lines if l.status == "partial"),
                "misplaced": sum(1 for l in pg.lines if l.status == "misplaced"),
                "recovered": sum(1 for l in pg.lines if l.status == "recovered"),
                "md_chars": len(C.squash(md_pages.get(pg.number, "")))}

        # ---------------- pass 4: glyph corruption in the MD --------------------
        found: dict[str, dict] = {}
        for pno, txt in md_pages.items():
            for ln in txt.split("\n"):
                for m in GLYPH_RX.finditer(ln):
                    tok = m.group(0)
                    d = found.setdefault(tok, {"count": 0, "pages": set(), "examples": []})
                    d["count"] += 1
                    d["pages"].add(pno)
                    if len(d["examples"]) < 2:
                        d["examples"].append({"page": pno, "md_line": ln.strip()[:200]})
        if found:
            ex_out = {}
            for tok, d in sorted(found.items(), key=lambda kv: -kv[1]["count"]):
                exs = []
                for k_, ex in enumerate(d["examples"]):
                    pgobj = next((p for p in pdfpages if p.number == ex["page"]), None)
                    line = locate_line(ex["md_line"], pgobj) if pgobj else None
                    e = dict(ex)
                    if line:
                        e["pdf_line"] = line.text
                        e["crop"] = crop.crop(ex["page"], line.bbox, f"glyph-{re.sub(r'[^A-Za-z0-9]', '', tok)}-p{ex['page']}-{k_}", dpi=220)
                    exs.append(e)
                ex_out[tok] = {"count": d["count"], "pages": sorted(d["pages"]), "suggested": GLYPH_HINTS.get(tok, ""),
                               "examples": exs}
            items.append({"id": "GLYPH-1", "type": "glyph_corruption", "page": min(min(v["pages"]) for v in found.values()),
                          "label": "Raw glyph codes left in the MD", "severity": "medium",
                          "evidence": {"reason": "font glyph codes were not mapped to Unicode by the converter",
                                       "tokens": ex_out}})

        # ---------------- render context pages for review -----------------------
        for pno in sorted({i["page"] for i in items if i["type"] != "glyph_corruption"}):
            pass  # crops are enough; full pages are rendered on demand via render_page.py

    # ---------------- numbering / defaults ---------------------------------------
    items.sort(key=lambda i: (i["page"], (i.get("bbox") or [0, 0])[1]))
    for it in items:
        if it["type"] == "text":
            it["status"] = "done" if it["evidence"]["min_coverage"] >= 0 else "open"
            it["recovered_markdown"] = it["pdf_text"]
            it["auto"] = True
        else:
            it["status"] = "skipped" if it.get("likely_decorative") else "open"
            if it["status"] == "skipped":
                it["skip_reason"] = "auto: small/unlabelled graphic on the masthead or page furniture (confirm on crop)"
            it["recovered_markdown"] = ""

    if a.verify and appendix:
        for it in items:
            if it["id"] in appended:
                it["status"] = "resolved"
            elif it["id"] in skipped_log:
                it["status"], it["skip_reason"] = "skipped", skipped_log[it["id"]]

    tot = sum(v["lines"] for v in per_page.values())
    miss = sum(v["missing"] for v in per_page.values())
    part = sum(v["partial"] for v in per_page.values())
    rec = sum(v["recovered"] for v in per_page.values())
    summary = {
        "pdf_pages": n_pdf, "md_pages_detected": len(md_pages), "md_page_mode": mode,
        "text_lines": tot, "lines_missing": miss, "lines_partial": part, "lines_recovered_by_appendix": rec,
        "text_coverage_pct": round(100 * (tot - miss - part) / max(1, tot), 2),
        "items_by_type": dict(Counter(i["type"] for i in items)),
        "items_open": sum(1 for i in items if i["status"] == "open"),
    }
    report = {"meta": {"pdf": os.path.abspath(a.pdf), "md": os.path.abspath(a.md), "engine": engine, "eol": "crlf" if eol == "\r\n" else "lf",
                       "generated": dt.datetime.now().isoformat(timespec="seconds"), "verify_mode": a.verify},
              "summary": summary, "per_page": per_page, "items": items}
    json.dump(report, open(os.path.join(a.out, "report.json"), "w", encoding="utf8"), ensure_ascii=False, indent=2)
    write_human_report(report, os.path.join(a.out, "validation_report.md"))

    print(f"PDF pages: {n_pdf} | MD pages detected: {len(md_pages)} ({mode}) | engine: {engine}")
    if mode != "markers" and len(md_pages) != n_pdf:
        print("  ! MD has no per-page markers -> page-level attribution is approximate (use --page-regex if it has custom ones)")
    print(f"Text lines: {tot} | missing {miss} | partial {part} | text coverage {summary['text_coverage_pct']}%")
    print("Items:", summary["items_by_type"], "| open (need review):", summary["items_open"])
    if a.verify:
        res = sum(1 for i in items if i["status"] == "resolved")
        print(f"VERIFY: {res} items resolved via appendix, {summary['lines_recovered_by_appendix']} text lines recovered, "
              f"{summary['items_open']} still open, {miss + part} text lines still missing/partial")
    print("Report:", os.path.join(a.out, "report.json"))


def write_human_report(r, path):
    s = r["summary"]
    L = ["# MD ↔ PDF validation report", "",
         f"- PDF: `{os.path.basename(r['meta']['pdf'])}`  |  MD: `{os.path.basename(r['meta']['md'])}`",
         f"- Pages: PDF {s['pdf_pages']} / MD detected {s['md_pages_detected']} ({s['md_page_mode']})",
         f"- Text-line coverage: **{s['text_coverage_pct']}%** ({s['lines_missing']} missing, {s['lines_partial']} partial of {s['text_lines']})",
         f"- Findings: {s['items_by_type']}", "", "## Per-page text coverage", "",
         "| Page | PDF lines | Missing | Partial | Misplaced |", "|---|---|---|---|---|"]
    for p, v in r["per_page"].items():
        L.append(f"| {p} | {v['lines']} | {v['missing']} | {v['partial']} | {v['misplaced']} |")
    L += ["", "## Findings", "", "| ID | Page | Type | Severity | Status | Note |", "|---|---|---|---|---|---|"]
    for i in r["items"]:
        L.append(f"| {i['id']} | {i['page']} | {i['type']} | {i['severity']} | {i['status']} | {i.get('label','')} |")
    open(path, "w", encoding="utf8").write("\n".join(L) + "\n")


if __name__ == "__main__":
    main()