Pannuru commited on
Commit
cd6dbae
·
verified ·
1 Parent(s): 3137fce

Upload 6 files

Browse files
Files changed (6) hide show
  1. SKILL.md +77 -0
  2. analyze.py +716 -0
  3. apply_recovery.py +124 -0
  4. output .json +0 -0
  5. output.jsonl +0 -0
  6. resolve.py +84 -0
SKILL.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: md-pdf-validator
3
+ description: Compare a PDF with the Markdown file that Microsoft MarkItDown (or any PDF-to-Markdown converter) generated from it, find everything the Markdown lost or damaged, and append the missing content to the Markdown file. Use this skill whenever the user supplies a PDF together with its converted .md/.markdown file and asks to validate, verify, compare, audit, fix, complete, or "append the missing content" of the conversion, or says the conversion dropped figures, tables, equations, pages, or text, even if they do not name MarkItDown.
4
+ compatibility: Python 3 with pdfplumber (and Pillow/pypdfium2, which pdfplumber pulls in). pdftotext from poppler is used when present, with an automatic pdfplumber fallback.
5
+ ---
6
+
7
+ # MD ↔ PDF validator
8
+
9
+ PDF-to-Markdown converters silently lose or damage content. This skill compares the source PDF with the Markdown, reports what is wrong, and **appends** the missing content to the Markdown as a clearly delimited appendix. The original Markdown is never edited, so the user can always diff before and after.
10
+
11
+ ## What gets detected
12
+
13
+ | Item type | Meaning | Who fills it in |
14
+ |---|---|---|
15
+ | `text` | Lines in the PDF text layer that the MD lacks (deleted text, whole missing pages, scrambled numbers) | Automatic: verbatim PDF text is pre-filled |
16
+ | `figure` / `graphic` | Charts, diagrams, images with no text-layer equivalent | You, by looking at the crop image |
17
+ | `table` | Table whose rows/columns were flattened or whose cells are damaged | Draft GFM table is pre-filled; you verify it |
18
+ | `equation` | Numbered display equation that is garbled by font encoding or missing | You, by looking at the crop image (write LaTeX) |
19
+ | `glyph_corruption` | Raw glyph codes such as `/C15`, `(cid:12)` left in the MD text | You confirm the real characters on the crops |
20
+
21
+ ## Workflow
22
+
23
+ Scripts live in `scripts/` next to this file. Use the actual install path of the skill (for example `/mnt/skills/user/md-pdf-validator/scripts`). Work in a scratch directory such as `/home/claude/work`.
24
+
25
+ ### 1. Locate the inputs
26
+ Find the PDF and its MD in `/mnt/user-data/uploads/` (pair them by file stem). If several pairs exist, process each one separately. If a file is missing, say so and stop.
27
+
28
+ ### 2. Analyse
29
+ ```bash
30
+ python scripts/analyze.py --pdf /mnt/user-data/uploads/X.pdf --md /mnt/user-data/uploads/X.md --out /home/claude/work
31
+ ```
32
+ Read the printed summary and `work/validation_report.md`. Key options: `--page-regex` if the MD uses unusual page markers (group 1 = page number), `--tables never` to skip table drafting, `--no-graphics` to skip figure detection. If the MD has no page markers, page attribution is approximate; tell the user.
33
+
34
+ ### 3. Review every `open` item
35
+ Open the crop image of each item with the `view` tool (`work/assets/*.png`; paths are in `report.json`). Never write a transcription without looking at the crop: the text layer is exactly what was unreliable.
36
+
37
+ - **Figures with printed data labels**: transcribe as a Markdown table (label → value). Copy numbers exactly.
38
+ - **Charts without labels**: give a short description and approximate values, marked "(approx., read from chart)". Prefer exact values quoted in the paper's own text or tables if they exist.
39
+ - **Diagrams / flowcharts**: a Mermaid block (```mermaid) plus one or two sentences describing the flow.
40
+ - **Equations**: display LaTeX, e.g. `$$\chi^2 = \sum \frac{(O_i - E_i)^2}{E_i} \tag{1}$$`. Only transcribe the equation whose tag matches the item; the crop can include a neighbour.
41
+ - **Tables**: compare the draft with the crop. Fix header rows, merged/spanning headers, wrapped labels, and any damaged cells. Empty body = accept the draft as is.
42
+ - **Glyph codes**: give a two-column table `Code | Meaning` (see `evidence.tokens` in the report; `suggested` values are heuristics, confirm them on the example crops).
43
+ - **Decorative graphics** (logos, masthead art, "check for updates" badges): skip with a reason.
44
+ - **`text` items** are pre-filled and marked `done`; skim them and skip any that are page furniture.
45
+
46
+ ### 4. Record your decisions
47
+ Write `work/resolutions.md` (plain Markdown, no JSON escaping needed):
48
+ ```
49
+ ### @FIG-p8-1 done
50
+ | Method | Features reduced (%) |
51
+ |---|---|
52
+ | Info Gain | 29.82 |
53
+
54
+ ### @EQ-p5-1 done
55
+ $$\chi^2 = \sum \frac{(O_i - E_i)^2}{E_i} \tag{1}$$
56
+
57
+ ### @TB-p6-1 done
58
+
59
+ ### @GFX-p1-1 skip: publisher logo
60
+ ```
61
+ Then merge it: `python scripts/resolve.py --report work/report.json --resolutions work/resolutions.md`. It lists anything still open.
62
+
63
+ ### 5. Append and verify
64
+ ```bash
65
+ python scripts/apply_recovery.py --md /mnt/user-data/uploads/X.md --report work/report.json --out /mnt/user-data/outputs/X.md
66
+ python scripts/analyze.py --pdf /mnt/user-data/uploads/X.pdf --md /mnt/user-data/outputs/X.md --out /home/claude/work_verify --verify
67
+ ```
68
+ Verification should report 0 open items and 0 missing/partial lines. If not, fix the listed items and re-run step 4 to 5; re-running replaces the previous appendix. Use `--no-images` if the user only wants text, and `--strict` to fail while items are open.
69
+
70
+ ### 6. Deliver
71
+ Call `present_files` on the output `.md`, plus `work/validation_report.md`. Figure crops referenced by the appendix are copied to `X_assets/` next to the output MD; present those too when figures were appended. In the reply, summarise counts by type, list anything skipped or approximate, and state clearly what was NOT verified.
72
+
73
+ ## Rules that keep the result trustworthy
74
+ - Append only. Do not rewrite, reorder, or "clean up" the original MD, including line endings.
75
+ - Never invent content. If a figure value or symbol cannot be read from the crop, say so in the appendix rather than guessing.
76
+ - Report limits honestly: unnumbered inline math, scanned PDFs without a text layer (every line will show as missing; use the page renders and read visually), and tables without horizontal rules are not auto-detected.
77
+ - Details of the report format and detection heuristics are in `references/report_schema.md`; read it if you need to tune thresholds or debug a false positive/negative.
analyze.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compare a PDF with the Markdown that MarkItDown (or any converter) produced from it.
3
+
4
+ Finds what the Markdown lost or damaged and writes a work directory containing:
5
+
6
+ report.json machine-readable findings (one "item" per problem)
7
+ validation_report.md human-readable summary
8
+ assets/*.png crops of figures / tables / equations / glyph examples
9
+
10
+ Item types
11
+ text lines present in the PDF text layer but absent from the Markdown
12
+ figure / graphic charts, diagrams, images (no text layer -> must be read visually)
13
+ table tables whose row/column structure was lost (draft GFM provided)
14
+ equation display equations that are missing or garbled
15
+ glyph_corruption raw glyph codes such as "/C15" or "(cid:12)" left in the Markdown
16
+
17
+ Usage
18
+ python analyze.py --pdf paper.pdf --md paper.md --out work/
19
+ python analyze.py --pdf paper.pdf --md paper_appended.md --out work_verify/ --verify
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import datetime as dt
25
+ import json
26
+ import os
27
+ import re
28
+ import sys
29
+ from collections import Counter, defaultdict
30
+
31
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
32
+ import common as C # noqa: E402
33
+
34
+ COVERED, PARTIAL = 0.85, 0.5 # coverage >= COVERED -> ok ; < PARTIAL -> missing
35
+
36
+ MATH_SIGNAL = re.compile(r"[=¼∑Σ∫√±≤≥≠≈∈∏ðÞ□]|/[Cg]\d{1,3}")
37
+ EQ_TAG = re.compile(r"(?:ð|\()\s*(\d{1,3})\s*(?:Þ|\))\s*$")
38
+ GLYPH_RX = re.compile(r"(?<![A-Za-z0-9])/[Cg]\d{1,3}|\(cid:\d+\)|[\ue000-\uf8ff\ufffd]")
39
+ GLYPH_HINTS = { # heuristic only (TeX/Symbol fonts) -> always confirm on the crop
40
+ "/C0": "−", "/C15": "•", "/C20": "≤", "/C21": "≥", "/C211": "©",
41
+ }
42
+ FIG_CAP = re.compile(r"^(Fig(?:ure)?\.?)\s*(\d+[A-Za-z]?)\s*[.:\u2013\u2014-]", re.I)
43
+ TAB_CAP = re.compile(r"^(Table)\s+([A-Za-z]?\d+[A-Za-z]?)\s*(?:[.:\u2013\u2014-]|$)", re.I)
44
+
45
+
46
+ # --------------------------------------------------------------------------- #
47
+ # geometry helpers
48
+ # --------------------------------------------------------------------------- #
49
+ def union(bs):
50
+ 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))
51
+
52
+
53
+ def center(b):
54
+ return ((b[0] + b[2]) / 2, (b[1] + b[3]) / 2)
55
+
56
+
57
+ def inside(pt, b, pad=1.5):
58
+ return b[0] - pad <= pt[0] <= b[2] + pad and b[1] - pad <= pt[1] <= b[3] + pad
59
+
60
+
61
+ def clip(b, w, h, pad=0):
62
+ return (max(0, b[0] - pad), max(0, b[1] - pad), min(w, b[2] + pad), min(h, b[3] + pad))
63
+
64
+
65
+ def overlap_frac(a, b):
66
+ x0, y0, x1, y1 = max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3])
67
+ if x1 <= x0 or y1 <= y0:
68
+ return 0.0
69
+ return (x1 - x0) * (y1 - y0) / max(1e-6, (a[2] - a[0]) * (a[3] - a[1]))
70
+
71
+
72
+ # --------------------------------------------------------------------------- #
73
+ # cropping
74
+ # --------------------------------------------------------------------------- #
75
+ class Cropper:
76
+ def __init__(self, pdf, assets_dir, dpi):
77
+ self.pdf, self.dir, self.dpi = pdf, assets_dir, dpi
78
+ os.makedirs(assets_dir, exist_ok=True)
79
+
80
+ def crop(self, page_no, bbox, name, dpi=None):
81
+ p = self.pdf.pages[page_no - 1]
82
+ b = clip(bbox, float(p.width), float(p.height), 4)
83
+ path = os.path.join(self.dir, name + ".png")
84
+ try:
85
+ p.crop(b).to_image(resolution=dpi or self.dpi).save(path)
86
+ return os.path.relpath(path, os.path.dirname(self.dir))
87
+ except Exception as e: # pragma: no cover
88
+ print(f" ! crop failed for {name}: {e}", file=sys.stderr)
89
+ return None
90
+
91
+ def page(self, page_no, dpi=90):
92
+ p = self.pdf.pages[page_no - 1]
93
+ path = os.path.join(self.dir, f"page-{page_no:02d}.png")
94
+ if not os.path.exists(path):
95
+ p.to_image(resolution=dpi).save(path)
96
+ return os.path.relpath(path, os.path.dirname(self.dir))
97
+
98
+
99
+ # --------------------------------------------------------------------------- #
100
+ # tables
101
+ # --------------------------------------------------------------------------- #
102
+ def rule_levels(page):
103
+ """Horizontal rules grouped by y-level. Segmented rules (drawn cell by cell) are merged.
104
+
105
+ Returns [(y, x0, x1, coverage)] sorted by y, coverage = fraction of [x0,x1] actually inked.
106
+ """
107
+ segs = []
108
+ for o in list(page.rects) + list(page.lines):
109
+ h = abs(o["bottom"] - o["top"])
110
+ w = o["x1"] - o["x0"]
111
+ if h <= 1.8 and w >= 12:
112
+ segs.append(((o["top"] + o["bottom"]) / 2, o["x0"], o["x1"]))
113
+ segs.sort()
114
+ levels, cur = [], []
115
+ for sgm in segs:
116
+ if cur and abs(sgm[0] - cur[-1][0]) > 1.0:
117
+ levels.append(cur); cur = []
118
+ cur.append(sgm)
119
+ if cur:
120
+ levels.append(cur)
121
+ out = []
122
+ for lv in levels:
123
+ xs = sorted((s_[1], s_[2]) for s_ in lv)
124
+ merged = [list(xs[0])]
125
+ for x0, x1 in xs[1:]:
126
+ if x0 <= merged[-1][1] + 1.5:
127
+ merged[-1][1] = max(merged[-1][1], x1)
128
+ else:
129
+ merged.append([x0, x1])
130
+ # runs separated by > 8pt belong to different tables/columns
131
+ groups = [[merged[0]]]
132
+ for m in merged[1:]:
133
+ (groups[-1].append(m) if m[0] - groups[-1][-1][1] <= 8 else groups.append([m]))
134
+ y = sum(s_[0] for s_ in lv) / len(lv)
135
+ for g in groups:
136
+ x0, x1 = g[0][0], g[-1][1]
137
+ inked = sum(m[1] - m[0] for m in g)
138
+ out.append((y, x0, x1, inked / max(1e-6, x1 - x0)))
139
+ return out
140
+
141
+
142
+ def find_captions(pdfpage: C.PdfPage):
143
+ """Return [(kind,label,line,block_lines)] for real captions (short blocks starting 'Fig. N.'/'Table N')."""
144
+ by_block = defaultdict(list)
145
+ for l in pdfpage.lines:
146
+ by_block[l.block].append(l)
147
+ caps = []
148
+ for l in pdfpage.lines:
149
+ blk = by_block[l.block]
150
+ if l is not blk[0] or len(blk) > 3:
151
+ continue
152
+ m = FIG_CAP.match(l.text)
153
+ if m:
154
+ caps.append(("figure", f"Fig. {m.group(2)}", l, blk))
155
+ continue
156
+ m = TAB_CAP.match(l.text)
157
+ if m:
158
+ caps.append(("table", f"Table {m.group(2)}", l, blk))
159
+ return caps
160
+
161
+
162
+ def build_table(plpage, pdfpage: C.PdfPage, cap_lines, all_caps):
163
+ """Locate a table below its caption using its horizontal rules and draft a GFM table."""
164
+ cb = union([l.bbox for l in cap_lines])
165
+ levels = rule_levels(plpage)
166
+ # do not run into the next caption sitting below in the same column
167
+ limit = float(plpage.height)
168
+ for _, _, _, blk in all_caps:
169
+ bb = union([x.bbox for x in blk])
170
+ 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:
171
+ limit = min(limit, bb[1])
172
+ 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]
173
+ if not tops:
174
+ return None
175
+ top = min(tops, key=lambda lv: lv[0])
176
+ chain = [top] + [lv for lv in levels if top[0] + 3 < lv[0] < limit and abs(lv[1] - top[1]) <= 8
177
+ and abs(lv[2] - top[2]) <= 8 and lv[3] >= 0.5]
178
+ full = [lv for lv in chain if lv[3] >= 0.85]
179
+ if len(full) < 2:
180
+ return None
181
+ bottom = full[-1][0]
182
+ header_cut = full[-2][0] if len(full) >= 3 else None
183
+ x0, x1 = top[1], top[2]
184
+ bbox = (x0, cb[1], x1, bottom + 2)
185
+ region = plpage.crop((x0 - 2, top[0] - 1, x1 + 2, bottom + 1))
186
+ words = region.extract_words(x_tolerance=1.5, y_tolerance=2, keep_blank_chars=False)
187
+ if not words:
188
+ return None
189
+ return {"bbox": bbox, "caption_bbox": cb, "draft": draft_gfm(words, header_cut), "n_words": len(words),
190
+ "closed": True}
191
+
192
+
193
+ def _rows(words, tol=3.0):
194
+ words = sorted(words, key=lambda w: (w["top"], w["x0"]))
195
+ rows, cur, ref = [], [], None
196
+ for w in words:
197
+ if ref is None or abs(w["top"] - ref) <= tol:
198
+ cur.append(w)
199
+ ref = w["top"] if ref is None else ref
200
+ else:
201
+ rows.append(cur)
202
+ cur, ref = [w], w["top"]
203
+ if cur:
204
+ rows.append(cur)
205
+ return rows
206
+
207
+
208
+ def draft_gfm(words, header_cut):
209
+ body_w = [w for w in words if header_cut is None or (w["top"] + w["bottom"]) / 2 > header_cut]
210
+ head_w = [w for w in words if header_cut is not None and (w["top"] + w["bottom"]) / 2 <= header_cut]
211
+ if header_cut is None: # no header rule: first text row is the header
212
+ rows0 = _rows(words)
213
+ head_w, body_w = rows0[0], [w for r in rows0[1:] for w in r]
214
+ if not body_w:
215
+ return ""
216
+ # column detection from body words (gap > 5pt starts a new column)
217
+ ivs = sorted((w["x0"], w["x1"]) for w in body_w)
218
+ cols = [list(ivs[0])]
219
+ for a, b in ivs[1:]:
220
+ if a - cols[-1][1] > 5:
221
+ cols.append([a, b])
222
+ else:
223
+ cols[-1][1] = max(cols[-1][1], b)
224
+ edges = [(cols[i][1] + cols[i + 1][0]) / 2 for i in range(len(cols) - 1)]
225
+
226
+ def col_of(w):
227
+ cx = (w["x0"] + w["x1"]) / 2
228
+ for i, e in enumerate(edges):
229
+ if cx < e:
230
+ return i
231
+ return len(cols) - 1
232
+
233
+ def cells(row):
234
+ cs = [""] * len(cols)
235
+ for w in sorted(row, key=lambda w: w["x0"]):
236
+ i = col_of(w)
237
+ cs[i] = (cs[i] + " " + w["text"]).strip()
238
+ return cs
239
+
240
+ header = [""] * len(cols)
241
+ for r in _rows(head_w):
242
+ r = sorted(r, key=lambda w: w["x0"])
243
+ hc = [[r[0]["x0"], r[0]["x1"], r[0]["text"]]]
244
+ for w in r[1:]:
245
+ if w["x0"] - hc[-1][1] <= 5:
246
+ hc[-1][1] = w["x1"]; hc[-1][2] += " " + w["text"]
247
+ else:
248
+ hc.append([w["x0"], w["x1"], w["text"]])
249
+ for x0_, x1_, txt in hc:
250
+ ov = [i for i, (c0, c1) in enumerate(cols) if min(c1, x1_) - max(c0, x0_) > 0]
251
+ if ov:
252
+ i = ov[0]
253
+ else:
254
+ cx = (x0_ + x1_) / 2
255
+ i = min(range(len(cols)), key=lambda k: abs((cols[k][0] + cols[k][1]) / 2 - cx))
256
+ header[i] = (header[i] + " " + txt).strip()
257
+ rows = [cells(r) for r in _rows(body_w)]
258
+ # merge wrapped label cells
259
+ merged: list[list[str]] = []
260
+ i = 0
261
+ while i < len(rows):
262
+ r = rows[i]
263
+ only0 = r[0] and not any(r[1:])
264
+ if only0 and i + 1 < len(rows) and not rows[i + 1][0] and any(rows[i + 1][1:]):
265
+ rows[i + 1][0] = r[0]
266
+ elif only0 and merged and (r[0][:1].islower() or r[0][:1] in "()"):
267
+ merged[-1][0] += " " + r[0]
268
+ else:
269
+ merged.append(r)
270
+ i += 1
271
+ esc = lambda s: s.replace("|", "\\|")
272
+ out = ["| " + " | ".join(esc(h) for h in header) + " |", "|" + "|".join(["---"] * len(cols)) + "|"]
273
+ out += ["| " + " | ".join(esc(c) for c in r) + " |" for r in merged]
274
+ return "\n".join(out)
275
+
276
+
277
+ # --------------------------------------------------------------------------- #
278
+ # figures / graphics
279
+ # --------------------------------------------------------------------------- #
280
+ def graphic_clusters(plpage):
281
+ objs = []
282
+ for kind, lst in (("image", plpage.images), ("curve", plpage.curves), ("rect", plpage.rects), ("line", plpage.lines)):
283
+ for o in lst:
284
+ b = (o["x0"], o["top"], o["x1"], o["bottom"])
285
+ w, h = b[2] - b[0], b[3] - b[1]
286
+ if kind != "image" and ((w > 0.75 * plpage.width and h < 3) or (w < 0.8 and h < 0.8)):
287
+ continue # page-wide rules / dots
288
+ objs.append((kind, b))
289
+ n = len(objs)
290
+ parent = list(range(n))
291
+
292
+ def find(i):
293
+ while parent[i] != i:
294
+ parent[i] = parent[parent[i]]
295
+ i = parent[i]
296
+ return i
297
+
298
+ GAP = 7
299
+ order = sorted(range(n), key=lambda i: objs[i][1][0])
300
+ for ai, i in enumerate(order):
301
+ bi = objs[i][1]
302
+ for j in order[ai + 1:]:
303
+ bj = objs[j][1]
304
+ if bj[0] > bi[2] + GAP:
305
+ break
306
+ if bj[1] <= bi[3] + GAP and bj[3] >= bi[1] - GAP:
307
+ parent[find(i)] = find(j)
308
+ groups = defaultdict(list)
309
+ for i in range(n):
310
+ groups[find(i)].append(objs[i])
311
+ res = []
312
+ for g in groups.values():
313
+ b = union([x[1] for x in g])
314
+ k = Counter(x[0] for x in g)
315
+ res.append({"bbox": b, "n_image": k["image"], "n_curve": k["curve"], "n_rect": k["rect"], "n_line": k["line"]})
316
+ return res
317
+
318
+
319
+ def find_graphics(plpage, pdfpage: C.PdfPage, caps):
320
+ fig_caps = [c for c in caps if c[0] == "figure"]
321
+ clusters = []
322
+ for g in graphic_clusters(plpage):
323
+ b = g["bbox"]
324
+ w, h = b[2] - b[0], b[3] - b[1]
325
+ if w < 25 or h < 15:
326
+ continue
327
+ n_vec = g["n_curve"] + g["n_rect"] + g["n_line"]
328
+ if not (g["n_image"] >= 1 or n_vec >= 12):
329
+ continue
330
+ words = sum(1 for l in pdfpage.lines if inside(center(l.bbox), b))
331
+ cap, best = None, 1e9
332
+ for kind, label, cl, blk in fig_caps:
333
+ cbb = union([x.bbox for x in blk])
334
+ d_below, d_above = cbb[1] - b[3], b[1] - cbb[3]
335
+ xov = min(b[2], cbb[2]) - max(b[0], cbb[0]) > 0
336
+ dist = d_below if -15 <= d_below <= 60 else d_above if -15 <= d_above <= 40 else None
337
+ if dist is not None and xov and abs(dist) < best:
338
+ cap, best = (label, blk, cbb), abs(dist)
339
+ tableish = g["n_curve"] == 0 and g["n_image"] == 0 and words >= 10 and cap is None
340
+ if tableish:
341
+ continue
342
+ g.update(words_inside=words, caption=cap)
343
+ clusters.append(g)
344
+ # merge sub-figures that share one caption
345
+ merged, by_cap = [], defaultdict(list)
346
+ for g in clusters:
347
+ (by_cap[g["caption"][0]].append(g) if g["caption"] else merged.append(g))
348
+ for label, gs in by_cap.items():
349
+ b = union([x["bbox"] for x in gs])
350
+ m = dict(gs[0])
351
+ m["bbox"] = b
352
+ for k in ("n_image", "n_curve", "n_rect", "n_line", "words_inside"):
353
+ m[k] = sum(x[k] for x in gs)
354
+ merged.append(m)
355
+ return sorted(merged, key=lambda g: g["bbox"][1])
356
+
357
+
358
+ # --------------------------------------------------------------------------- #
359
+ # equations
360
+ # --------------------------------------------------------------------------- #
361
+ def mathlike(l: C.Line):
362
+ t = l.text
363
+ if MATH_SIGNAL.search(t):
364
+ return True
365
+ words = t.split()
366
+ prose = len(words) >= 5 and sum(1 for w in words if len(re.sub(r"\W", "", w)) >= 3) >= 4
367
+ return (not prose) and len(words) <= 5 and len(t) <= 32
368
+
369
+
370
+ def find_equations(pdfpage: C.PdfPage):
371
+ cols = Counter()
372
+ for l in pdfpage.lines:
373
+ if len(l.text) >= 45:
374
+ cols[(round(l.x0), round(l.x1))] += 1
375
+ col_ranges = [k for k, v in cols.items() if v >= 3] or [(0, pdfpage.width)]
376
+ eqs, used = [], set()
377
+ for seed in pdfpage.lines:
378
+ m = EQ_TAG.search(seed.text)
379
+ if not m or id(seed) in used or len(seed.text) > 70:
380
+ continue
381
+ fits = [(a, b) for a, b in col_ranges if a - 6 <= seed.x1 <= b + 6 and seed.x0 >= a - 6]
382
+ col = min(fits) if fits else (0, pdfpage.width) # widest matching column
383
+ cand = sorted((l for l in pdfpage.lines if l.x0 >= col[0] - 6 and l.x1 <= col[1] + 6
384
+ and seed.y0 - 70 <= l.y0 <= seed.y1 + 45), key=lambda l: (l.y0, l.x0))
385
+ if seed not in cand:
386
+ continue
387
+ keep = {id(seed)}
388
+ si = cand.index(seed)
389
+ for rng in (range(si - 1, -1, -1), range(si + 1, len(cand))):
390
+ prev = seed
391
+ for i in rng:
392
+ l = cand[i]
393
+ if EQ_TAG.search(l.text) and len(l.text) <= 70:
394
+ break # next equation starts here
395
+ if not mathlike(l) or abs(l.y0 - prev.y0) > 26 and abs(l.y1 - prev.y1) > 26:
396
+ break
397
+ keep.add(id(l))
398
+ prev = l
399
+ members = [l for l in cand if id(l) in keep]
400
+ if not any(MATH_SIGNAL.search(l.text) for l in members):
401
+ continue
402
+ for l in members:
403
+ used.add(id(l))
404
+ eqs.append({"tag": m.group(1), "lines": members, "bbox": union([l.bbox for l in members])})
405
+ return eqs
406
+
407
+
408
+ # --------------------------------------------------------------------------- #
409
+ # main analysis
410
+ # --------------------------------------------------------------------------- #
411
+ def locate_line(md_line: str, pdfpage: C.PdfPage):
412
+ """Best-matching PDF line for an MD line (used to crop glyph-corruption examples)."""
413
+ g = C.squash(GLYPH_RX.sub("", md_line))
414
+ if len(g) < 6:
415
+ return None
416
+ grams = {g[i:i + 4] for i in range(len(g) - 3)}
417
+ best, score = None, 0.0
418
+ for l in pdfpage.lines:
419
+ s = C.squash(l.text)
420
+ lg = {s[i:i + 4] for i in range(max(0, len(s) - 3))}
421
+ if not lg:
422
+ continue
423
+ sc = len(grams & lg) / max(1, len(grams | lg))
424
+ if sc > score:
425
+ best, score = l, sc
426
+ return best if score >= 0.25 else None
427
+
428
+
429
+ def sev_text(n_chars):
430
+ return "high" if n_chars >= 200 else "medium" if n_chars >= 60 else "low"
431
+
432
+
433
+ def main():
434
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
435
+ ap.add_argument("--pdf", required=True)
436
+ ap.add_argument("--md", required=True)
437
+ ap.add_argument("--out", required=True, help="work directory (created)")
438
+ ap.add_argument("--dpi", type=int, default=160, help="crop resolution (default 160)")
439
+ ap.add_argument("--page-regex", help="regex (group 1 = page number) if the MD uses custom page markers")
440
+ ap.add_argument("--tables", choices=["auto", "always", "never"], default="auto",
441
+ help="auto: draft a GFM table when the MD has no pipe table or the table text is damaged")
442
+ ap.add_argument("--no-graphics", action="store_true")
443
+ ap.add_argument("--verify", action="store_true",
444
+ help="MD already contains an appendix: report what is still unresolved")
445
+ a = ap.parse_args()
446
+
447
+ import pdfplumber
448
+
449
+ raw = open(a.md, "rb").read().decode("utf-8", errors="replace")
450
+ eol = "\r\n" if "\r\n" in raw else "\n"
451
+ body, appendix = C.strip_appendix(raw)
452
+ md_pages, mode = C.split_md_pages(body, a.page_regex)
453
+ appx_idx = C.PageIndex(appendix) if appendix else None
454
+ appended = set(re.findall(r"<!-- item:(\S+) -->", appendix)) if a.verify else set()
455
+ skipped_log = dict(re.findall(r"^skipped:(\S+?): ?(.*)$", appendix, re.M)) if a.verify else {}
456
+
457
+ pdfpages, engine = C.extract_pdf_lines(a.pdf)
458
+ n_pdf = len(pdfpages)
459
+ global_idx = C.PageIndex(body)
460
+
461
+ os.makedirs(a.out, exist_ok=True)
462
+ assets = os.path.join(a.out, "assets")
463
+ if os.path.isdir(assets): # stale crops from an earlier run would be confusing
464
+ for f in os.listdir(assets):
465
+ if f.endswith(".png"):
466
+ os.remove(os.path.join(assets, f))
467
+ items: list[dict] = []
468
+ per_page = {}
469
+
470
+ with pdfplumber.open(a.pdf) as pdf:
471
+ crop = Cropper(pdf, assets, a.dpi)
472
+
473
+ # ---------------- pass 1: text coverage --------------------------------
474
+ for pg in pdfpages:
475
+ idx = C.PageIndex(md_pages.get(pg.number, ""))
476
+ for l in pg.lines:
477
+ c = idx.coverage(l.text)
478
+ if c is None:
479
+ continue
480
+ l.cov = c
481
+ if c >= COVERED:
482
+ continue
483
+ l.status = "missing" if c < PARTIAL else "partial"
484
+ long_line = len(C.squash(l.text)) >= 14 and len(C.tokens(l.text)) >= 3
485
+ gidx_c = global_idx.coverage(l.text, consume=False) if (mode == "markers" and long_line) else 0
486
+ if gidx_c is not None and gidx_c >= COVERED:
487
+ l.status = "misplaced"
488
+ elif appx_idx is not None and (appx_idx.coverage(l.text, consume=False) or 0) >= COVERED:
489
+ l.status = "recovered"
490
+
491
+ # ---------------- pass 2: structured regions ---------------------------
492
+ regions: dict[int, list[dict]] = defaultdict(list)
493
+ for pg in pdfpages:
494
+ plpage = pdf.pages[pg.number - 1]
495
+ caps = find_captions(pg)
496
+
497
+ # tables
498
+ tcount = 0
499
+ if a.tables != "never":
500
+ for kind, label, cl, blk in caps:
501
+ if kind != "table":
502
+ continue
503
+ t = build_table(plpage, pg, blk, caps)
504
+ if not t:
505
+ continue
506
+ tcount += 1
507
+ inside_lines = [l for l in pg.lines if inside(center(l.bbox), t["bbox"], 2)]
508
+ bad = [l for l in inside_lines if l.status in ("missing", "partial")]
509
+ md_text = md_pages.get(pg.number, "")
510
+ has_pipes = bool(re.search(r"^\s*\|.*\|\s*\n\s*\|[\s:\-|]+\|", md_text, re.M))
511
+ if a.tables == "auto" and has_pipes and not bad:
512
+ continue
513
+ cap_text = C.join_lines(blk)
514
+ it = {"id": f"TB-p{pg.number}-{tcount}", "type": "table", "page": pg.number,
515
+ "label": label, "bbox": [round(x, 1) for x in t["bbox"]],
516
+ "severity": "high" if bad else "medium",
517
+ "caption": cap_text,
518
+ "evidence": {"reason": ("table text is damaged in the MD (%d cells missing/scrambled)" % len(bad)) if bad
519
+ else "table rows are flattened text; column structure is lost",
520
+ "damaged_cells": [l.text for l in bad][:20]},
521
+ "draft_markdown": t["draft"],
522
+ "crop": crop.crop(pg.number, t["bbox"], f"table-{label.split()[-1]}-p{pg.number}")}
523
+ items.append(it)
524
+ regions[pg.number].append({"bbox": t["bbox"], "item": it})
525
+
526
+ # equations
527
+ for eq in find_equations(pg):
528
+ garbled = any(re.search(r"[¼ðÞ□]|/[Cg]\d", l.text) for l in eq["lines"])
529
+ bad = [l for l in eq["lines"] if l.status in ("missing", "partial")]
530
+ if not garbled and not bad:
531
+ continue
532
+ it = {"id": f"EQ-p{pg.number}-{eq['tag']}", "type": "equation", "page": pg.number,
533
+ "label": f"Equation ({eq['tag']})", "bbox": [round(x, 1) for x in eq["bbox"]],
534
+ "severity": "medium",
535
+ "evidence": {"reason": "equation text is garbled by font encoding" if garbled else "equation text missing from MD",
536
+ "pdf_text_layer": " / ".join(l.text for l in eq["lines"])},
537
+ "crop": crop.crop(pg.number, eq["bbox"], f"eq-{eq['tag']}-p{pg.number}", dpi=max(a.dpi, 200))}
538
+ items.append(it)
539
+ regions[pg.number].append({"bbox": eq["bbox"], "item": it})
540
+
541
+ # figures / images / charts
542
+ if not a.no_graphics:
543
+ for gi, g in enumerate(find_graphics(plpage, pg, caps), 1):
544
+ b = g["bbox"]
545
+ label, cap_txt, full = None, "", b
546
+ if g["caption"]:
547
+ label, blk, cbb = g["caption"]
548
+ cap_txt = C.join_lines(blk)
549
+ full = union([b, cbb])
550
+ small = (b[2] - b[0]) * (b[3] - b[1]) < 90 * 90
551
+ deco = (label is None) and (small or pg.number == 1)
552
+ kind = "figure" if label else "graphic"
553
+ it = {"id": f"{'FIG' if label else 'GFX'}-p{pg.number}-{gi}", "type": kind, "page": pg.number,
554
+ "label": label or "Unlabelled graphic", "bbox": [round(x, 1) for x in full],
555
+ "severity": "low" if deco else "high",
556
+ "caption": cap_txt,
557
+ "likely_decorative": bool(deco),
558
+ "evidence": {"reason": "visual content has no text-layer equivalent in the MD",
559
+ "images": g["n_image"], "vector_shapes": g["n_curve"] + g["n_rect"] + g["n_line"],
560
+ "text_lines_inside": g["words_inside"]},
561
+ "crop": crop.crop(pg.number, full, f"{'fig' if label else 'gfx'}-p{pg.number}-{gi}")}
562
+ items.append(it)
563
+ regions[pg.number].append({"bbox": full, "item": it})
564
+
565
+ # ---------------- pass 3: leftover text items ---------------------------
566
+ n_text = 0
567
+ for pg in pdfpages:
568
+ flagged = []
569
+ for l in pg.lines:
570
+ if l.status not in ("missing", "partial"):
571
+ continue
572
+ owner = next((r for r in regions[pg.number] if inside(center(l.bbox), r["bbox"], 3)), None)
573
+ if owner:
574
+ if owner["item"]["id"] in appended or owner["item"]["id"] in skipped_log:
575
+ l.status = "recovered"
576
+ owner["item"].setdefault("evidence", {}).setdefault("flagged_lines_inside", 0)
577
+ owner["item"]["evidence"]["flagged_lines_inside"] += 1
578
+ continue
579
+ flagged.append(l)
580
+ # group consecutive flagged lines (in reading order)
581
+ order = {id(l): i for i, l in enumerate(pg.lines)}
582
+ groups, cur = [], []
583
+ for l in flagged:
584
+ if cur and order[id(l)] != order[id(cur[-1])] + 1:
585
+ groups.append(cur); cur = []
586
+ cur.append(l)
587
+ if cur:
588
+ groups.append(cur)
589
+ for grp in groups:
590
+ txt = C.join_lines(grp)
591
+ if len(C.squash(txt)) < 3:
592
+ continue
593
+ n_text += 1
594
+ worst = min(l.cov for l in grp)
595
+ whole_page = len(C.squash(md_pages.get(pg.number, ""))) < 20
596
+ it = {"id": f"T-p{pg.number}-{n_text}", "type": "text", "page": pg.number,
597
+ "label": "Missing page" if whole_page else ("Missing text" if worst < PARTIAL else "Partially missing text"),
598
+ "bbox": [round(x, 1) for x in union([l.bbox for l in grp])],
599
+ "severity": sev_text(len(txt)),
600
+ "evidence": {"reason": "PDF text not found in the MD" if worst < PARTIAL else "PDF text only partly found in the MD (scrambled or truncated)",
601
+ "min_coverage": round(worst, 2), "lines": len(grp)},
602
+ "pdf_text": txt}
603
+ if len(txt) > 15:
604
+ it["crop"] = crop.crop(pg.number, union([l.bbox for l in grp]), f"text-p{pg.number}-{n_text}", dpi=110)
605
+ items.append(it)
606
+
607
+ for pg in pdfpages:
608
+ per_page[pg.number] = {
609
+ "lines": sum(1 for l in pg.lines if C.squash(l.text)),
610
+ "missing": sum(1 for l in pg.lines if l.status == "missing"),
611
+ "partial": sum(1 for l in pg.lines if l.status == "partial"),
612
+ "misplaced": sum(1 for l in pg.lines if l.status == "misplaced"),
613
+ "recovered": sum(1 for l in pg.lines if l.status == "recovered"),
614
+ "md_chars": len(C.squash(md_pages.get(pg.number, "")))}
615
+
616
+ # ---------------- pass 4: glyph corruption in the MD --------------------
617
+ found: dict[str, dict] = {}
618
+ for pno, txt in md_pages.items():
619
+ for ln in txt.split("\n"):
620
+ for m in GLYPH_RX.finditer(ln):
621
+ tok = m.group(0)
622
+ d = found.setdefault(tok, {"count": 0, "pages": set(), "examples": []})
623
+ d["count"] += 1
624
+ d["pages"].add(pno)
625
+ if len(d["examples"]) < 2:
626
+ d["examples"].append({"page": pno, "md_line": ln.strip()[:200]})
627
+ if found:
628
+ ex_out = {}
629
+ for tok, d in sorted(found.items(), key=lambda kv: -kv[1]["count"]):
630
+ exs = []
631
+ for k_, ex in enumerate(d["examples"]):
632
+ pgobj = next((p for p in pdfpages if p.number == ex["page"]), None)
633
+ line = locate_line(ex["md_line"], pgobj) if pgobj else None
634
+ e = dict(ex)
635
+ if line:
636
+ e["pdf_line"] = line.text
637
+ e["crop"] = crop.crop(ex["page"], line.bbox, f"glyph-{re.sub(r'[^A-Za-z0-9]', '', tok)}-p{ex['page']}-{k_}", dpi=220)
638
+ exs.append(e)
639
+ ex_out[tok] = {"count": d["count"], "pages": sorted(d["pages"]), "suggested": GLYPH_HINTS.get(tok, ""),
640
+ "examples": exs}
641
+ items.append({"id": "GLYPH-1", "type": "glyph_corruption", "page": min(min(v["pages"]) for v in found.values()),
642
+ "label": "Raw glyph codes left in the MD", "severity": "medium",
643
+ "evidence": {"reason": "font glyph codes were not mapped to Unicode by the converter",
644
+ "tokens": ex_out}})
645
+
646
+ # ---------------- render context pages for review -----------------------
647
+ for pno in sorted({i["page"] for i in items if i["type"] != "glyph_corruption"}):
648
+ pass # crops are enough; full pages are rendered on demand via render_page.py
649
+
650
+ # ---------------- numbering / defaults ---------------------------------------
651
+ items.sort(key=lambda i: (i["page"], (i.get("bbox") or [0, 0])[1]))
652
+ for it in items:
653
+ if it["type"] == "text":
654
+ it["status"] = "done" if it["evidence"]["min_coverage"] >= 0 else "open"
655
+ it["recovered_markdown"] = it["pdf_text"]
656
+ it["auto"] = True
657
+ else:
658
+ it["status"] = "skipped" if it.get("likely_decorative") else "open"
659
+ if it["status"] == "skipped":
660
+ it["skip_reason"] = "auto: small/unlabelled graphic on the masthead or page furniture (confirm on crop)"
661
+ it["recovered_markdown"] = ""
662
+
663
+ if a.verify and appendix:
664
+ for it in items:
665
+ if it["id"] in appended:
666
+ it["status"] = "resolved"
667
+ elif it["id"] in skipped_log:
668
+ it["status"], it["skip_reason"] = "skipped", skipped_log[it["id"]]
669
+
670
+ tot = sum(v["lines"] for v in per_page.values())
671
+ miss = sum(v["missing"] for v in per_page.values())
672
+ part = sum(v["partial"] for v in per_page.values())
673
+ rec = sum(v["recovered"] for v in per_page.values())
674
+ summary = {
675
+ "pdf_pages": n_pdf, "md_pages_detected": len(md_pages), "md_page_mode": mode,
676
+ "text_lines": tot, "lines_missing": miss, "lines_partial": part, "lines_recovered_by_appendix": rec,
677
+ "text_coverage_pct": round(100 * (tot - miss - part) / max(1, tot), 2),
678
+ "items_by_type": dict(Counter(i["type"] for i in items)),
679
+ "items_open": sum(1 for i in items if i["status"] == "open"),
680
+ }
681
+ report = {"meta": {"pdf": os.path.abspath(a.pdf), "md": os.path.abspath(a.md), "engine": engine, "eol": "crlf" if eol == "\r\n" else "lf",
682
+ "generated": dt.datetime.now().isoformat(timespec="seconds"), "verify_mode": a.verify},
683
+ "summary": summary, "per_page": per_page, "items": items}
684
+ json.dump(report, open(os.path.join(a.out, "report.json"), "w", encoding="utf8"), ensure_ascii=False, indent=2)
685
+ write_human_report(report, os.path.join(a.out, "validation_report.md"))
686
+
687
+ print(f"PDF pages: {n_pdf} | MD pages detected: {len(md_pages)} ({mode}) | engine: {engine}")
688
+ if mode != "markers" and len(md_pages) != n_pdf:
689
+ print(" ! MD has no per-page markers -> page-level attribution is approximate (use --page-regex if it has custom ones)")
690
+ print(f"Text lines: {tot} | missing {miss} | partial {part} | text coverage {summary['text_coverage_pct']}%")
691
+ print("Items:", summary["items_by_type"], "| open (need review):", summary["items_open"])
692
+ if a.verify:
693
+ res = sum(1 for i in items if i["status"] == "resolved")
694
+ print(f"VERIFY: {res} items resolved via appendix, {summary['lines_recovered_by_appendix']} text lines recovered, "
695
+ f"{summary['items_open']} still open, {miss + part} text lines still missing/partial")
696
+ print("Report:", os.path.join(a.out, "report.json"))
697
+
698
+
699
+ def write_human_report(r, path):
700
+ s = r["summary"]
701
+ L = ["# MD ↔ PDF validation report", "",
702
+ f"- PDF: `{os.path.basename(r['meta']['pdf'])}` | MD: `{os.path.basename(r['meta']['md'])}`",
703
+ f"- Pages: PDF {s['pdf_pages']} / MD detected {s['md_pages_detected']} ({s['md_page_mode']})",
704
+ f"- Text-line coverage: **{s['text_coverage_pct']}%** ({s['lines_missing']} missing, {s['lines_partial']} partial of {s['text_lines']})",
705
+ f"- Findings: {s['items_by_type']}", "", "## Per-page text coverage", "",
706
+ "| Page | PDF lines | Missing | Partial | Misplaced |", "|---|---|---|---|---|"]
707
+ for p, v in r["per_page"].items():
708
+ L.append(f"| {p} | {v['lines']} | {v['missing']} | {v['partial']} | {v['misplaced']} |")
709
+ L += ["", "## Findings", "", "| ID | Page | Type | Severity | Status | Note |", "|---|---|---|---|---|---|"]
710
+ for i in r["items"]:
711
+ L.append(f"| {i['id']} | {i['page']} | {i['type']} | {i['severity']} | {i['status']} | {i.get('label','')} |")
712
+ open(path, "w", encoding="utf8").write("\n".join(L) + "\n")
713
+
714
+
715
+ if __name__ == "__main__":
716
+ main()
apply_recovery.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Append recovered content to the Markdown file.
3
+
4
+ The original Markdown is never edited: everything found missing, garbled or structurally
5
+ lost is added as a clearly delimited appendix at the end of the file. Re-running replaces
6
+ the previous appendix (idempotent), so the tool can be used iteratively.
7
+
8
+ Usage
9
+ python apply_recovery.py --md paper.md --report work/report.json --out out/paper.md
10
+ Options
11
+ --no-images do not copy figure crops / add image links
12
+ --strict exit with code 2 if any item is still "open"
13
+ """
14
+ import argparse
15
+ import datetime as dt
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import sys
21
+
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+ import common as C # noqa: E402
24
+
25
+
26
+ def item_heading(it):
27
+ t, lab = it["type"], it.get("label", "")
28
+ cap = (it.get("caption") or "").strip()
29
+ if t in ("figure", "graphic", "table"):
30
+ cap = re.sub(rf"^{re.escape(lab)}\s*[.:\u2013\u2014-]?\s*", "", cap) if lab else cap
31
+ return f"**{lab}" + (f" — {cap}" if cap else "") + f"** *({t}, PDF p. {it['page']})*"
32
+ if t == "equation":
33
+ return f"**{lab}** *(PDF p. {it['page']})*"
34
+ if t == "text":
35
+ return f"**{lab}** *(PDF p. {it['page']})*"
36
+ return f"**{lab}**"
37
+
38
+
39
+ def build(items, md_name, pdf_name, assets_rel, eol_images):
40
+ today = dt.date.today().isoformat()
41
+ L = [C.APPX_BEGIN, "", "---", "", "## Appendix — Content recovered from the source PDF", "",
42
+ f"> Added by md-pdf-validator on {today} by comparing `{md_name}` with `{pdf_name}`. "
43
+ "Everything above this appendix is the original converter output and is unchanged. "
44
+ "The items below were missing, garbled, or had lost their structure in that output; "
45
+ "each is tagged with its PDF page.", ""]
46
+ glyph = [i for i in items if i["type"] == "glyph_corruption"]
47
+ rest = [i for i in items if i["type"] != "glyph_corruption"]
48
+ cur = None
49
+ for it in sorted(rest, key=lambda i: (i["page"], (i.get("bbox") or [0, 0])[1])):
50
+ if it["page"] != cur:
51
+ cur = it["page"]
52
+ L += [f"### PDF page {cur}", ""]
53
+ L += [f"<!-- item:{it['id']} -->", item_heading(it), ""]
54
+ if it["type"] in ("figure", "graphic") and eol_images and it.get("crop"):
55
+ fn = os.path.basename(it["crop"])
56
+ alt = (it.get("label") or "figure").replace("]", "")
57
+ L += [f"![{alt}]({assets_rel}/{fn})", ""]
58
+ L += [it["recovered_markdown"].strip(), ""]
59
+ for it in glyph:
60
+ L += ["### Corrections — raw glyph codes in the converted text", "", f"<!-- item:{it['id']} -->",
61
+ it["recovered_markdown"].strip(), ""]
62
+ return L
63
+
64
+
65
+ def main():
66
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
67
+ ap.add_argument("--md", required=True)
68
+ ap.add_argument("--report", required=True)
69
+ ap.add_argument("--out", required=True, help="output .md path (its folder receives <name>_assets/)")
70
+ ap.add_argument("--no-images", action="store_true")
71
+ ap.add_argument("--strict", action="store_true")
72
+ a = ap.parse_args()
73
+
74
+ rep = json.load(open(a.report, encoding="utf8"))
75
+ work = os.path.dirname(os.path.abspath(a.report))
76
+ raw = open(a.md, "rb").read()
77
+ bom = raw.startswith(b"\xef\xbb\xbf")
78
+ text = raw.decode("utf-8-sig", errors="replace")
79
+ eol = "\r\n" if "\r\n" in text else "\n"
80
+ body, _old = C.strip_appendix(text)
81
+ body = body.rstrip("\r\n")
82
+
83
+ items = rep["items"]
84
+ open_items = [i for i in items if i["status"] == "open"]
85
+ use = [i for i in items if i["status"] == "done" and (i.get("recovered_markdown") or "").strip()]
86
+ skipped = [i for i in items if i["status"] == "skipped"]
87
+
88
+ out_dir = os.path.dirname(os.path.abspath(a.out))
89
+ os.makedirs(out_dir, exist_ok=True)
90
+ stem = os.path.splitext(os.path.basename(a.out))[0]
91
+ assets_rel = f"{stem}_assets"
92
+ want_images = not a.no_images
93
+ if want_images:
94
+ for it in use:
95
+ if it["type"] in ("figure", "graphic") and it.get("crop"):
96
+ src = os.path.join(work, it["crop"])
97
+ if os.path.exists(src):
98
+ os.makedirs(os.path.join(out_dir, assets_rel), exist_ok=True)
99
+ shutil.copy2(src, os.path.join(out_dir, assets_rel, os.path.basename(src)))
100
+
101
+ lines = build(use, os.path.basename(a.md), os.path.basename(rep["meta"]["pdf"]), assets_rel, want_images)
102
+ if skipped:
103
+ lines += ["<!-- resolution log"] + [f"skipped:{i['id']}: {i.get('skip_reason','')}".replace("--", "-") for i in skipped] + ["-->", ""]
104
+ lines.append(C.APPX_END)
105
+ appendix = "\n".join(lines)
106
+ result = body + "\n\n" + appendix + "\n"
107
+ if eol == "\r\n":
108
+ result = result.replace("\r\n", "\n").replace("\n", "\r\n")
109
+ with open(a.out, "wb") as f:
110
+ f.write((b"\xef\xbb\xbf" if bom else b"") + result.encode("utf-8"))
111
+
112
+ kinds = {}
113
+ for i in use:
114
+ kinds[i["type"]] = kinds.get(i["type"], 0) + 1
115
+ print(f"Wrote {a.out}")
116
+ print(f" appended: {len(use)} items {kinds} | skipped: {len(skipped)} | still open: {len(open_items)}")
117
+ for i in open_items:
118
+ print(f" ! open, NOT appended: {i['id']} ({i['type']}, p.{i['page']})")
119
+ if a.strict and open_items:
120
+ sys.exit(2)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
output .json ADDED
The diff for this file is too large to render. See raw diff
 
output.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
resolve.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Merge reviewed content into report.json.
3
+
4
+ Writing recovered Markdown (LaTeX, tables, diagrams) inside JSON means escaping every
5
+ backslash and quote, which is error-prone. Instead, write a plain Markdown "resolutions"
6
+ file and let this script merge it:
7
+
8
+ ### @FIG-p4-1 done
9
+ **Figure 1 - Proposed Spam Detection Model.** ...transcription / Mermaid / description...
10
+
11
+ ### @EQ-p5-1 done
12
+ $$\\chi^2 = \\sum \\frac{(O_i - E_i)^2}{E_i} \\tag{1}$$
13
+
14
+ ### @TB-p6-1 done
15
+ (empty body = accept the auto-drafted table exactly as generated)
16
+
17
+ ### @GFX-p1-1 skip: publisher logo, decorative
18
+ ### @T-p3-2 skip: page furniture, not content
19
+
20
+ Rules
21
+ * `done` + body -> body becomes the recovered Markdown for that item
22
+ * `done` + no body -> keep what is already in the item (auto draft / auto text)
23
+ * `skip: reason` -> item is not appended (reason is logged in the appendix)
24
+ * Unknown ids are reported and ignored.
25
+
26
+ Usage: python resolve.py --report work/report.json --resolutions work/resolutions.md
27
+ """
28
+ import argparse
29
+ import json
30
+ import re
31
+ import sys
32
+
33
+ HDR = re.compile(r"^###\s+@(\S+)\s+(done|skip)\b\s*:?\s*(.*)$", re.I)
34
+
35
+
36
+ def parse(text):
37
+ out, cur = {}, None
38
+ for line in text.replace("\r\n", "\n").split("\n"):
39
+ m = HDR.match(line)
40
+ if m:
41
+ cur = m.group(1)
42
+ out[cur] = {"verb": m.group(2).lower(), "reason": m.group(3).strip(), "body": []}
43
+ elif cur:
44
+ out[cur]["body"].append(line)
45
+ for v in out.values():
46
+ v["body"] = "\n".join(v["body"]).strip("\n").strip()
47
+ return out
48
+
49
+
50
+ def main():
51
+ ap = argparse.ArgumentParser()
52
+ ap.add_argument("--report", required=True)
53
+ ap.add_argument("--resolutions", required=True)
54
+ a = ap.parse_args()
55
+ rep = json.load(open(a.report, encoding="utf8"))
56
+ res = parse(open(a.resolutions, encoding="utf8").read())
57
+ by_id = {i["id"]: i for i in rep["items"]}
58
+ done = skipped = 0
59
+ for rid, r in res.items():
60
+ it = by_id.get(rid)
61
+ if not it:
62
+ print(f" ! unknown id {rid} (ignored)")
63
+ continue
64
+ if r["verb"] == "skip":
65
+ it["status"], it["skip_reason"] = "skipped", r["reason"] or "skipped by reviewer"
66
+ skipped += 1
67
+ continue
68
+ body = r["body"] or it.get("recovered_markdown") or it.get("draft_markdown") or ""
69
+ if not body.strip():
70
+ print(f" ! {rid}: marked done but there is no content (add a body) -> left open")
71
+ continue
72
+ it["recovered_markdown"], it["status"] = body, "done"
73
+ it.pop("skip_reason", None)
74
+ done += 1
75
+ rep["summary"]["items_open"] = sum(1 for i in rep["items"] if i["status"] == "open")
76
+ json.dump(rep, open(a.report, "w", encoding="utf8"), ensure_ascii=False, indent=2)
77
+ print(f"resolved: {done} done, {skipped} skipped | still open: {rep['summary']['items_open']}")
78
+ for i in rep["items"]:
79
+ if i["status"] == "open":
80
+ print(f" open: {i['id']} ({i['type']}, p.{i['page']}, {i.get('label','')})")
81
+
82
+
83
+ if __name__ == "__main__":
84
+ sys.exit(main())