md-validator / apply_recovery.py
Pannuru's picture
Upload 6 files
cd6dbae verified
Raw History Blame Contribute Delete
5.35 kB
#!/usr/bin/env python3
"""Append recovered content to the Markdown file.
The original Markdown is never edited: everything found missing, garbled or structurally
lost is added as a clearly delimited appendix at the end of the file. Re-running replaces
the previous appendix (idempotent), so the tool can be used iteratively.
Usage
python apply_recovery.py --md paper.md --report work/report.json --out out/paper.md
Options
--no-images do not copy figure crops / add image links
--strict exit with code 2 if any item is still "open"
"""
import argparse
import datetime as dt
import json
import os
import re
import shutil
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import common as C # noqa: E402
def item_heading(it):
t, lab = it["type"], it.get("label", "")
cap = (it.get("caption") or "").strip()
if t in ("figure", "graphic", "table"):
cap = re.sub(rf"^{re.escape(lab)}\s*[.:\u2013\u2014-]?\s*", "", cap) if lab else cap
return f"**{lab}" + (f" — {cap}" if cap else "") + f"** *({t}, PDF p. {it['page']})*"
if t == "equation":
return f"**{lab}** *(PDF p. {it['page']})*"
if t == "text":
return f"**{lab}** *(PDF p. {it['page']})*"
return f"**{lab}**"
def build(items, md_name, pdf_name, assets_rel, eol_images):
today = dt.date.today().isoformat()
L = [C.APPX_BEGIN, "", "---", "", "## Appendix — Content recovered from the source PDF", "",
f"> Added by md-pdf-validator on {today} by comparing `{md_name}` with `{pdf_name}`. "
"Everything above this appendix is the original converter output and is unchanged. "
"The items below were missing, garbled, or had lost their structure in that output; "
"each is tagged with its PDF page.", ""]
glyph = [i for i in items if i["type"] == "glyph_corruption"]
rest = [i for i in items if i["type"] != "glyph_corruption"]
cur = None
for it in sorted(rest, key=lambda i: (i["page"], (i.get("bbox") or [0, 0])[1])):
if it["page"] != cur:
cur = it["page"]
L += [f"### PDF page {cur}", ""]
L += [f"<!-- item:{it['id']} -->", item_heading(it), ""]
if it["type"] in ("figure", "graphic") and eol_images and it.get("crop"):
fn = os.path.basename(it["crop"])
alt = (it.get("label") or "figure").replace("]", "")
L += [f"![{alt}]({assets_rel}/{fn})", ""]
L += [it["recovered_markdown"].strip(), ""]
for it in glyph:
L += ["### Corrections — raw glyph codes in the converted text", "", f"<!-- item:{it['id']} -->",
it["recovered_markdown"].strip(), ""]
return L
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--md", required=True)
ap.add_argument("--report", required=True)
ap.add_argument("--out", required=True, help="output .md path (its folder receives <name>_assets/)")
ap.add_argument("--no-images", action="store_true")
ap.add_argument("--strict", action="store_true")
a = ap.parse_args()
rep = json.load(open(a.report, encoding="utf8"))
work = os.path.dirname(os.path.abspath(a.report))
raw = open(a.md, "rb").read()
bom = raw.startswith(b"\xef\xbb\xbf")
text = raw.decode("utf-8-sig", errors="replace")
eol = "\r\n" if "\r\n" in text else "\n"
body, _old = C.strip_appendix(text)
body = body.rstrip("\r\n")
items = rep["items"]
open_items = [i for i in items if i["status"] == "open"]
use = [i for i in items if i["status"] == "done" and (i.get("recovered_markdown") or "").strip()]
skipped = [i for i in items if i["status"] == "skipped"]
out_dir = os.path.dirname(os.path.abspath(a.out))
os.makedirs(out_dir, exist_ok=True)
stem = os.path.splitext(os.path.basename(a.out))[0]
assets_rel = f"{stem}_assets"
want_images = not a.no_images
if want_images:
for it in use:
if it["type"] in ("figure", "graphic") and it.get("crop"):
src = os.path.join(work, it["crop"])
if os.path.exists(src):
os.makedirs(os.path.join(out_dir, assets_rel), exist_ok=True)
shutil.copy2(src, os.path.join(out_dir, assets_rel, os.path.basename(src)))
lines = build(use, os.path.basename(a.md), os.path.basename(rep["meta"]["pdf"]), assets_rel, want_images)
if skipped:
lines += ["<!-- resolution log"] + [f"skipped:{i['id']}: {i.get('skip_reason','')}".replace("--", "-") for i in skipped] + ["-->", ""]
lines.append(C.APPX_END)
appendix = "\n".join(lines)
result = body + "\n\n" + appendix + "\n"
if eol == "\r\n":
result = result.replace("\r\n", "\n").replace("\n", "\r\n")
with open(a.out, "wb") as f:
f.write((b"\xef\xbb\xbf" if bom else b"") + result.encode("utf-8"))
kinds = {}
for i in use:
kinds[i["type"]] = kinds.get(i["type"], 0) + 1
print(f"Wrote {a.out}")
print(f" appended: {len(use)} items {kinds} | skipped: {len(skipped)} | still open: {len(open_items)}")
for i in open_items:
print(f" ! open, NOT appended: {i['id']} ({i['type']}, p.{i['page']})")
if a.strict and open_items:
sys.exit(2)
if __name__ == "__main__":
main()