"""``htr`` command-line interface (versioned): reconstruct text, batch files, inspect a release.""" from __future__ import annotations import argparse import json import sys from pathlib import Path from htr import __version__ def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="htr", description="Human Text Reconstruction Transformer (research tool; outputs are synthetic reconstructions)") ap.add_argument("--version", action="version", version=f"htr {__version__}") sub = ap.add_subparsers(dest="cmd", required=True) r = sub.add_parser("reconstruct", help="reconstruct one passage") r.add_argument("--model", required=True) r.add_argument("--text", default=None) r.add_argument("--file", default=None) r.add_argument("--discipline", default=None) r.add_argument("--year", type=int, default=None) r.add_argument("--role", default=None) r.add_argument("--beam", type=int, default=1) r.add_argument("--device", default="auto") r.add_argument("--json", action="store_true") b = sub.add_parser("batch", help="reconstruct a JSONL file with fields text[, discipline, pub_year, section_role]") b.add_argument("--model", required=True) b.add_argument("--input", required=True) b.add_argument("--output", required=True) b.add_argument("--beam", type=int, default=1) b.add_argument("--device", default="auto") i = sub.add_parser("info", help="show release metadata") i.add_argument("--model", required=True) a = ap.parse_args(argv) if a.cmd == "info": p = Path(a.model) for f in ("release_meta.json", "config.json", "MANIFEST.json"): if (p / f).exists(): print(f"== {f}") print((p / f).read_text()[:2000]) return 0 from htr.inference.pipeline import HTRReconstructor rec = HTRReconstructor.from_pretrained(a.model, device=a.device) if a.cmd == "reconstruct": text = a.text or (Path(a.file).read_text() if a.file else sys.stdin.read()) res = rec.reconstruct(text.strip(), {"discipline": a.discipline, "pub_year": a.year, "section_role": a.role}, beam=a.beam) if a.json: print(json.dumps(res.to_dict(), ensure_ascii=False, indent=2)) else: print(res.reconstruction) for w in res.warnings: print(f"! {w}", file=sys.stderr) print(f"[{res.notice}]", file=sys.stderr) return 0 if a.cmd == "batch": n = 0 with open(a.input, encoding="utf-8") as fin, open(a.output, "w", encoding="utf-8") as fout: for line in fin: if not line.strip(): continue row = json.loads(line) res = rec.reconstruct(row["text"], {k: row.get(k) for k in ("discipline", "pub_year", "section_role", "era")}, beam=a.beam) fout.write(json.dumps({**row, "reconstruction": res.reconstruction, "warnings": res.warnings, "preservation": res.preservation}, ensure_ascii=False) + "\n") n += 1 print(f"wrote {n} reconstructions to {a.output}", file=sys.stderr) return 0 return 1 if __name__ == "__main__": raise SystemExit(main())