htr-tiny / htr /inference /editor.py
spboucher04's picture
Release HTR-Tiny-0.3.0 (WP-AI-0002)
ff8d20f verified
Raw History Blame Contribute Delete
6.03 kB
"""Inference API for the non-generative HTR-Edit model: ``HTREditor.from_pretrained(dir).edit(text, metadata)``.
Pipeline: protect spans (citations, math, URLs β†’ placeholders, exactly as ``htr.inference.pipeline``) β†’ tokenise β†’
one encoder forward pass β†’ argmax KEEP/DELETE per source token and argmax phrase per insertion slot β†’ protected
tokens (placeholders, digit-bearing pieces) and their glue pieces forced to KEEP, insertions inside/next to them
blocked (``protection_plan``) β†’ realise edits β†’ decode β†’ restore placeholders β†’
preservation checks (``htr.evaluation.metrics.factual``) and warnings. Deterministic; no sampling, no decoding loop.
Sources longer than ``max_src`` tokens are edited on their first ``max_src`` tokens; the remainder is passed through
unchanged (warning added).
"""
from __future__ import annotations
import json
from pathlib import Path
import torch
from htr.evaluation.metrics import factual
from htr.inference.pipeline import NOTICE, ReconstructionResult
from htr.models.tagger import HTREditModel, load_edit_checkpoint
from htr.models.tokenizer import HTRTokenizer
from htr.parse.protect import protect, restore_placeholders
from htr.training.edits import PhraseVocab, apply_edits, protected_ids, protection_plan, space_ids
EDIT_NOTICE = NOTICE.replace("produced by HTR", "produced by HTR-Edit (non-generative editor)")
def _warnings(pres: dict, hyp: str, text: str) -> list[str]:
w = []
if pres["placeholders_exact"] < 1.0:
w.append("citations/equations/links not all preserved β€” verify protected spans")
if pres["number_recall"] < 1.0:
w.append(f"numbers from the input missing in the output (recall {pres['number_recall']:.2f})")
if pres["number_precision"] < 1.0:
w.append("output contains numbers absent from the input")
if abs(pres["negation_delta"]) >= 1:
w.append(f"negation count changed by {int(pres['negation_delta'])}")
if abs(pres["hedge_delta"]) >= 3:
w.append(f"hedging count changed by {int(pres['hedge_delta'])}")
lr = len(hyp.split()) / max(1, len(text.split()))
if lr < 0.6 or lr > 1.7:
w.append(f"length ratio {lr:.2f} outside the expected range")
return w
class HTREditor:
def __init__(self, model: HTREditModel, tok: HTRTokenizer, phrases: PhraseVocab, release_meta: dict | None = None, none_bias: float | None = None):
self.model = model.eval()
self.tok = tok
self.phrases = phrases
self.meta = release_meta or {}
self.none_bias = none_bias
self.device = next(model.parameters()).device
self.keep_ids = protected_ids(tok.sp)
self.spaced = space_ids(tok.sp)
if len(phrases) != model.cfg.n_phrases:
raise ValueError(f"phrase vocabulary ({len(phrases)}) does not match the model head ({model.cfg.n_phrases})")
@classmethod
def from_pretrained(cls, path: str | Path, device: str = "auto", none_bias: float | None = None) -> "HTREditor":
path = Path(path)
if device == "auto":
device = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
model = load_edit_checkpoint(path, device)
tok = HTRTokenizer(path / "tokenizer.model")
phrases = PhraseVocab.load(path / "phrases.json")
rm = json.loads((path / "release_meta.json").read_text()) if (path / "release_meta.json").exists() else {}
return cls(model, tok, phrases, rm, none_bias)
def edit(self, text: str, metadata: dict | None = None) -> ReconstructionResult:
return self.edit_many([text], [metadata or {}], batch_size=1)[0]
@torch.no_grad()
def edit_many(self, texts: list[str], metadatas: list[dict] | None = None, batch_size: int = 64) -> list[ReconstructionResult]:
metas = metadatas or [{} for _ in texts]
cfg = self.model.cfg
prepared = []
for i, (t, m) in enumerate(zip(texts, metas)):
prot = protect(t)
ids = self.tok.sp.encode(prot.text, out_type=int)
prepared.append((i, t, m or {}, prot, ids))
order = sorted(range(len(prepared)), key=lambda k: len(prepared[k][4]))
results: list[ReconstructionResult | None] = [None] * len(texts)
for b in range(0, len(order), batch_size):
chunk = [prepared[k] for k in order[b : b + batch_size]]
heads = [x[4][: cfg.max_src] for x in chunk]
L = max(len(h) for h in heads) + 2
inp = torch.tensor([[cfg.bos_id] + h + [cfg.eos_id] + [cfg.pad_id] * (L - len(h) - 2) for h in heads], device=self.device)
tags, ins = self.model.predict(inp, self.none_bias)
tags, ins = tags.cpu().tolist(), ins.cpu().tolist()
for (i, t, m, prot, ids), h, tg, it in zip(chunk, heads, tags, ins):
n = len(h)
keep, block = protection_plan(h, self.keep_ids, self.spaced)
if len(ids) > n:
block[n] = True # never insert at the truncation boundary
out_ids = apply_edits(h, tg[1 : n + 1], it[: n + 1], self.phrases, force_keep=keep, block_slot=block) + ids[n:]
hyp_prot = self.tok.sp.decode(out_ids)
hyp = restore_placeholders(hyp_prot, prot)
pres = factual(hyp_prot, prot.text)
warnings = _warnings(pres, hyp, t)
if len(ids) > n:
warnings.append(f"input longer than {cfg.max_src} tokens: the last {len(ids) - n} tokens were passed through unchanged")
n_del = sum(1 for k in range(n) if tg[k + 1] == 1 and not keep[k])
n_ins = sum(1 for k in range(n + 1) if it[k] != 0 and not block[k])
results[i] = ReconstructionResult(t, hyp, warnings, pres, {**m, "arch": "htr_edit", "edits": {"deleted_tokens": n_del, "insertions": n_ins, "source_tokens": len(ids)}}, self.meta.get("name", "htr-edit"), EDIT_NOTICE)
return results # type: ignore[return-value]