lectris 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. lectris/__init__.py +45 -0
  2. lectris/align.py +159 -0
  3. lectris/cli.py +290 -0
  4. lectris/confidence.py +154 -0
  5. lectris/decide.py +164 -0
  6. lectris/distance.py +231 -0
  7. lectris/edits.py +253 -0
  8. lectris/errors.py +9 -0
  9. lectris/eval/__init__.py +14 -0
  10. lectris/eval/calibrate.py +187 -0
  11. lectris/eval/experiment.py +448 -0
  12. lectris/eval/lines.py +47 -0
  13. lectris/eval/matching.py +71 -0
  14. lectris/eval/scoring.py +437 -0
  15. lectris/eval/stats.py +58 -0
  16. lectris/eval/truth.py +103 -0
  17. lectris/evidence.py +147 -0
  18. lectris/io/__init__.py +62 -0
  19. lectris/io/_common.py +153 -0
  20. lectris/io/_json.py +145 -0
  21. lectris/io/alto.py +274 -0
  22. lectris/io/detect.py +74 -0
  23. lectris/io/glypharis.py +165 -0
  24. lectris/io/hocr.py +332 -0
  25. lectris/io/jsonio.py +269 -0
  26. lectris/io/plain.py +49 -0
  27. lectris/io/tsv.py +177 -0
  28. lectris/layout/__init__.py +129 -0
  29. lectris/layout/columns.py +71 -0
  30. lectris/layout/geometry.py +224 -0
  31. lectris/layout/lines.py +133 -0
  32. lectris/layout/order.py +240 -0
  33. lectris/layout/paragraphs.py +194 -0
  34. lectris/lexicon.py +240 -0
  35. lectris/metrics.py +123 -0
  36. lectris/model.py +247 -0
  37. lectris/models/__init__.py +11 -0
  38. lectris/models/acceptance.py +174 -0
  39. lectris/models/channel.py +136 -0
  40. lectris/models/charlm.py +183 -0
  41. lectris/models/pack.py +244 -0
  42. lectris/models/risk.py +101 -0
  43. lectris/pipeline.py +423 -0
  44. lectris/profiles.py +117 -0
  45. lectris/propose.py +177 -0
  46. lectris/py.typed +0 -0
  47. lectris/quality.py +269 -0
  48. lectris/report.py +157 -0
  49. lectris/text/__init__.py +1 -0
  50. lectris/text/confusables.py +176 -0
  51. lectris/text/hyphenation.py +149 -0
  52. lectris/text/lexis.py +46 -0
  53. lectris/text/noise.py +62 -0
  54. lectris/text/numbers.py +77 -0
  55. lectris/text/punctuation.py +257 -0
  56. lectris/text/unicode.py +301 -0
  57. lectris/text/unwrap.py +108 -0
  58. lectris/text/whitespace.py +81 -0
  59. lectris-0.3.0.dist-info/METADATA +243 -0
  60. lectris-0.3.0.dist-info/RECORD +62 -0
  61. lectris-0.3.0.dist-info/WHEEL +4 -0
  62. lectris-0.3.0.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,187 @@
1
+ """Calibrating a model pack: its acceptance model and each profile's risk-controlled threshold.
2
+
3
+ ``calibrate(pack, fit, cal)`` (architecture §11; ADR-0002):
4
+
5
+ 1. **Training data.** Every page of the ``fit`` pairs is cleaned with the pack under ``PARITY``
6
+ with the ``standard`` profile, and every candidate (accepted or not, layout rules aside) is
7
+ labelled by its exact marginal effect (``scoring.label_candidates``): 1 if it brings its block
8
+ closer to the reference, else 0.
9
+ 2. **Acceptance.** A logistic regression on those examples (``models.acceptance``).
10
+ 3. **Risk.** For each profile, every page of the ``cal`` pairs is cleaned the same way with that
11
+ profile, and its candidates get their probabilities. A page's loss at a threshold is the
12
+ characters broken by the harmful candidates whose probability reaches it, over the page's
13
+ reference length (at most 1). Learn-then-Test (``models.risk``) certifies the thresholds whose
14
+ mean loss is below the profile's ``alpha`` with confidence ``1 - delta``, and the one used is
15
+ the certified threshold with the largest estimated CER reduction on the cal pages (the most
16
+ negative sum of the accepted candidates' effects; the strictest on a tie, ADR-0009).
17
+ 4. **Calibration.** The expected calibration error and the Brier score of the probabilities on
18
+ the ``cal`` candidates of the ``standard`` profile.
19
+
20
+ The loss at a threshold is estimated from each candidate's effect where ``PARITY`` proposed it:
21
+ a policy that accepts other candidates changes the text later stages see, and overlapping
22
+ candidates exclude each other. So the estimate is an approximation of the risk ``risk_policy``
23
+ runs at; the guarantee's validity is measured with full runs on held-out pages (protocol §5).
24
+ """
25
+
26
+ from collections.abc import Mapping, Sequence
27
+ from dataclasses import dataclass, replace
28
+ from typing import Final
29
+
30
+ from lectris import io
31
+ from lectris.decide import PARITY, Threshold
32
+ from lectris.eval import truth as truth_io
33
+ from lectris.eval.experiment import Pair
34
+ from lectris.eval.scoring import LabelledCandidate, drop_dont_care, label_candidates
35
+ from lectris.models.acceptance import Acceptance, calibration
36
+ from lectris.models.pack import Budget, ModelPack
37
+ from lectris.models.risk import certified, grid
38
+ from lectris.pipeline import clean
39
+
40
+ BUDGETS: Final = {"conservative": 0.01, "standard": 0.02, "aggressive": 0.05}
41
+ """Each profile's harm-rate budget ``alpha`` (ADR-0008: what 430 calibration pages can certify)."""
42
+
43
+ DELTA: Final = 0.1
44
+ """The confidence the budgets are held with is ``1 - DELTA``."""
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class PageCandidates:
49
+ """One page's labelled candidates, and its reference length."""
50
+
51
+ page: str
52
+ candidates: tuple[LabelledCandidate, ...]
53
+ reference_chars: int
54
+
55
+
56
+ def page_candidates(
57
+ pairs: Sequence[Pair], pack: ModelPack, profile: str, *, iou_threshold: float = 0.5
58
+ ) -> list[PageCandidates]:
59
+ """Each page cleaned with ``pack`` under ``PARITY``, with its labelled candidates."""
60
+ found = []
61
+ for pair in pairs:
62
+ truth = truth_io.read(pair.truth)
63
+ document = drop_dont_care(io.read(pair.engine), truth, iou_threshold=iou_threshold)
64
+ result = clean(document, profile=profile, policy=PARITY, pack=pack)
65
+ labelled = label_candidates(result, truth, iou_threshold=iou_threshold)
66
+ chars = sum(len(line.text) for line in truth.counted.lines)
67
+ found.append(PageCandidates(pair.page, tuple(labelled), chars))
68
+ return found
69
+
70
+
71
+ def page_losses(
72
+ pages: Sequence[PageCandidates], acceptance: Acceptance
73
+ ) -> list[list[tuple[float, int]]]:
74
+ """Each page's candidates as ``(probability, harm)``, ``harm`` the characters it breaks."""
75
+ return [
76
+ [(acceptance.probability(item.candidate), max(item.effect, 0)) for item in page.candidates]
77
+ for page in pages
78
+ ]
79
+
80
+
81
+ def most_useful(
82
+ thresholds: Sequence[float], pages: Sequence[PageCandidates], acceptance: Acceptance
83
+ ) -> float | None:
84
+ """Among ``thresholds``, the one with the most negative net effect; the highest on a tie."""
85
+ if not thresholds:
86
+ return None
87
+ effects: list[tuple[float, float]] = []
88
+ probability = {
89
+ id(item): acceptance.probability(item.candidate)
90
+ for page in pages
91
+ for item in page.candidates
92
+ }
93
+ for threshold in thresholds:
94
+ total = sum(
95
+ item.effect
96
+ for page in pages
97
+ for item in page.candidates
98
+ if probability[id(item)] >= threshold
99
+ )
100
+ effects.append((total, -threshold))
101
+ best = min(effects)
102
+ return -best[1]
103
+
104
+
105
+ def loss_at(
106
+ threshold: float, scored: Sequence[Sequence[tuple[float, int]]], pages: Sequence[PageCandidates]
107
+ ) -> list[float]:
108
+ """Each page's estimated loss at ``threshold`` (see the module's documentation)."""
109
+ return [
110
+ min(1.0, sum(harm for p, harm in items if p >= threshold) / max(1, page.reference_chars))
111
+ for items, page in zip(scored, pages, strict=True)
112
+ ]
113
+
114
+
115
+ def calibrate(
116
+ pack: ModelPack,
117
+ fit: Sequence[Pair],
118
+ cal: Sequence[Pair],
119
+ *,
120
+ budgets: Mapping[str, float] = BUDGETS,
121
+ delta: float = DELTA,
122
+ steps: int = 100,
123
+ l2: float = 1.0,
124
+ exclude: Sequence[str] = (),
125
+ ) -> ModelPack:
126
+ """``pack`` with its acceptance model, risk budgets and calibration (module documentation).
127
+
128
+ ``exclude`` names features the acceptance model is fitted without (an ablation: the model
129
+ then never sees them, whatever candidates carry)."""
130
+ training = page_candidates(fit, pack, "standard")
131
+ left_out = set(exclude)
132
+ examples = [
133
+ (
134
+ {k: v for k, v in item.candidate.features if k not in left_out},
135
+ 1 if item.fixes else 0,
136
+ )
137
+ for page in training
138
+ for item in page.candidates
139
+ ]
140
+ acceptance = Acceptance.fit(examples, l2=l2)
141
+ risk: dict[str, Budget] = {}
142
+ summary: dict[str, object] = {
143
+ "fit_pages": len(fit),
144
+ "fit_candidates": len(examples),
145
+ "fit_fixes": sum(label for _, label in examples),
146
+ "cal_pages": len(cal),
147
+ "l2": l2,
148
+ "grid_steps": steps,
149
+ "excluded_features": sorted(left_out),
150
+ }
151
+ for profile, alpha in sorted(budgets.items()):
152
+ pages = page_candidates(cal, pack, profile)
153
+ scored = page_losses(pages, acceptance)
154
+
155
+ def losses(
156
+ threshold: float,
157
+ scored: Sequence[Sequence[tuple[float, int]]] = scored,
158
+ pages: Sequence[PageCandidates] = pages,
159
+ ) -> list[float]:
160
+ return loss_at(threshold, scored, pages)
161
+
162
+ valid = certified(losses, grid(steps), alpha=alpha, delta=delta)
163
+ risk[profile] = Budget(
164
+ alpha,
165
+ delta,
166
+ most_useful(valid, pages, acceptance),
167
+ len(pages),
168
+ valid[-1] if valid else None,
169
+ )
170
+ if profile == "standard":
171
+ probabilities = [p for items in scored for p, _ in items]
172
+ labels = [1 if item.fixes else 0 for page in pages for item in page.candidates]
173
+ if probabilities:
174
+ measured = calibration(probabilities, labels)
175
+ summary |= {
176
+ "cal_candidates": len(probabilities),
177
+ "cal_fixes": sum(labels),
178
+ "ece": measured.ece,
179
+ "brier": measured.brier,
180
+ "reliability": [list(row) for row in measured.bins],
181
+ }
182
+ return replace(pack, acceptance=acceptance, risk=risk, calibration=summary)
183
+
184
+
185
+ def risk_policy(pack: ModelPack, profile: str) -> Threshold:
186
+ """The ``risk`` policy of ``profile`` (``ModelPack.policy``)."""
187
+ return pack.policy(profile)
@@ -0,0 +1,448 @@
1
+ """A registered experiment, run from its configuration into a report (experiment protocol §7).
2
+
3
+ A configuration is JSON:
4
+
5
+ .. code-block:: json
6
+
7
+ {"id": "LX-MAIN-001", "question": "Does the standard profile lower CER on dev?",
8
+ "pairs": "data/manifests/pairs/hiertext_val_dev.json",
9
+ "systems": [{"name": "B1", "profile": "standard", "policy": "parity"}],
10
+ "resamples": 1000, "seed": 1337, "iou": 0.5}
11
+
12
+ ``pairs`` names a manifest (relative to the configuration's folder), whose pages each give an
13
+ engine output file and a ground-truth file (``lectris.eval.truth``), relative to the manifest's
14
+ folder:
15
+
16
+ .. code-block:: json
17
+
18
+ {"pages": [{"page": "a1b2c3", "engine": "../../engine/a1b2c3.json",
19
+ "truth": "../../truth/a1b2c3.json"}]}
20
+
21
+ Each system is a profile and a policy: ``parity`` (LECTRIS v0.1's decisions), ``none`` (no
22
+ guess accepted: the transforms only, baseline B0), ``lexicon`` (baseline B2, a lexicon
23
+ corrector, ``LEXICON``) or ``risk`` (the pack's acceptance model and
24
+ the profile's risk-controlled threshold, ``lectris.eval.calibrate.risk_policy``). A system can
25
+ name a model ``pack`` (relative to the configuration's folder): it adds evidence and the lexicon
26
+ proposers, and ``risk`` needs one. Every page is read, its OCR lines on
27
+ don't-care ground truth are dropped (``scoring.drop_dont_care``), and it is cleaned by each
28
+ system and scored (``lectris.eval.scoring``). The report holds, for the uncorrected text and
29
+ for each system: CER (normalised and raw tracks), WER, the harm rate, edit counts by label, the
30
+ precision of edits and the share of pages made worse, with bootstrap intervals over pages; and
31
+ each system's paired CER difference from the uncorrected text. It holds aggregates only, never
32
+ text (ground rule 5).
33
+ """
34
+
35
+ import hashlib
36
+ import json
37
+ from collections.abc import Callable, Sequence
38
+ from dataclasses import dataclass
39
+ from pathlib import Path
40
+ from typing import Any, Final
41
+
42
+ from lectris import __version__, io
43
+ from lectris.decide import PARITY, Policy, Threshold
44
+ from lectris.errors import FormatError
45
+ from lectris.eval import truth as truth_io
46
+ from lectris.eval.scoring import PageScore, drop_dont_care, score_page
47
+ from lectris.eval.stats import Interval, bootstrap, ratio
48
+ from lectris.io._common import decode
49
+ from lectris.io._json import array, load, number, obj, required, string
50
+ from lectris.models import pack as pack_io
51
+ from lectris.pipeline import clean
52
+ from lectris.profiles import PROFILES
53
+
54
+ NONE: Final = Threshold(lambda _: 0.0, 1.0)
55
+ """A policy that accepts no guess: every candidate's probability is 0, below the bar of 1."""
56
+
57
+ LEXICON: Final = Threshold(
58
+ lambda c: 1.0 if c.rule == "lexical.word" and c.feature("lexical_rank", 9.0) == 0 else 0.0, 1.0
59
+ )
60
+ """Baseline B2, a lexicon corrector: every token not in the lexicon becomes the lexicon's most
61
+ frequent word one edit away (``lexical.word``'s first candidate); no other guess is accepted.
62
+ It needs a pack, for the word list."""
63
+
64
+ POLICIES: Final[dict[str, Policy]] = {"parity": PARITY, "none": NONE, "lexicon": LEXICON}
65
+ """The policies a configuration can name, besides ``risk`` (which needs a pack)."""
66
+
67
+ _POLICY_NAMES: Final = (*POLICIES, "risk")
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class System:
72
+ """One system an experiment runs: a name, a profile and a policy."""
73
+
74
+ name: str
75
+ profile: str
76
+ policy: str
77
+ pack: Path | None = None
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class Config:
82
+ """An experiment's configuration (see the module's documentation)."""
83
+
84
+ id: str
85
+ question: str
86
+ pairs: Path
87
+ systems: tuple[System, ...]
88
+ resamples: int = 1000
89
+ seed: int = 1337
90
+ iou: float = 0.5
91
+ compare: tuple[tuple[str, str], ...] = ()
92
+
93
+
94
+ @dataclass(frozen=True, slots=True)
95
+ class Pair:
96
+ """One page: its id, its engine output and its ground truth."""
97
+
98
+ page: str
99
+ engine: Path
100
+ truth: Path
101
+
102
+
103
+ def load_config(path: Path) -> Config:
104
+ """The configuration in the file at ``path``; ``FormatError`` names what is wrong."""
105
+ data = obj(load(decode(path.read_bytes())), "")
106
+ systems = tuple(
107
+ _system(item, f"systems[{index}]", path.parent)
108
+ for index, item in array(required(data, "systems", ""), "systems")
109
+ )
110
+ if not systems:
111
+ raise FormatError("systems: an experiment runs at least one system")
112
+ names = [system.name for system in systems]
113
+ if len(set(names)) != len(names):
114
+ raise FormatError(f"systems: each system's name is given once, not {names}")
115
+ return Config(
116
+ id=string(required(data, "id", ""), "id"),
117
+ question=string(data.get("question", ""), "question"),
118
+ pairs=(path.parent / string(required(data, "pairs", ""), "pairs")),
119
+ systems=systems,
120
+ resamples=_integer(data, "resamples", 1000),
121
+ seed=_integer(data, "seed", 1337),
122
+ iou=number(data.get("iou", 0.5), "iou"),
123
+ compare=_comparisons(data.get("compare", []), names),
124
+ )
125
+
126
+
127
+ def load_pairs(path: Path) -> tuple[Pair, ...]:
128
+ """The pages of the pairs manifest at ``path``."""
129
+ data = obj(load(decode(path.read_bytes())), "")
130
+ pairs = []
131
+ for index, item in array(required(data, "pages", ""), "pages"):
132
+ where = f"pages[{index}]"
133
+ page = obj(item, where)
134
+ pairs.append(
135
+ Pair(
136
+ string(required(page, "page", where), f"{where}.page"),
137
+ path.parent / string(required(page, "engine", where), f"{where}.engine"),
138
+ path.parent / string(required(page, "truth", where), f"{where}.truth"),
139
+ )
140
+ )
141
+ return tuple(pairs)
142
+
143
+
144
+ def run(config: Config) -> dict[str, Any]:
145
+ """Run ``config`` and return its report as a JSON-ready dictionary."""
146
+ pairs = load_pairs(config.pairs)
147
+ if not pairs:
148
+ raise FormatError(f"{config.pairs}: the manifest has no pages")
149
+ scores: dict[str, list[PageScore]] = {system.name: [] for system in config.systems}
150
+ from lectris.eval.calibrate import risk_policy # noqa: PLC0415 - calibrate imports this module
151
+
152
+ packs = {s.pack: pack_io.load(s.pack) for s in config.systems if s.pack is not None}
153
+ policies: dict[str, Policy] = {}
154
+ for system in config.systems:
155
+ if system.policy == "risk":
156
+ if system.pack is None:
157
+ raise FormatError(f"{system.name}: the risk policy needs a pack")
158
+ policies[system.name] = risk_policy(packs[system.pack], system.profile)
159
+ else:
160
+ policies[system.name] = POLICIES[system.policy]
161
+ for pair in pairs:
162
+ truth = truth_io.read(pair.truth)
163
+ document = drop_dont_care(io.read(pair.engine), truth, iou_threshold=config.iou)
164
+ for system in config.systems:
165
+ result = clean(
166
+ document,
167
+ profile=system.profile,
168
+ policy=policies[system.name],
169
+ pack=None if system.pack is None else packs[system.pack],
170
+ )
171
+ scores[system.name].append(score_page(result, truth, iou_threshold=config.iou))
172
+ first = scores[config.systems[0].name]
173
+ report: dict[str, Any] = {
174
+ "id": config.id,
175
+ "question": config.question,
176
+ "lectris_version": __version__,
177
+ "pages": len(pairs),
178
+ "manifest_sha256": hashlib.sha256(config.pairs.read_bytes()).hexdigest(),
179
+ "resamples": config.resamples,
180
+ "seed": config.seed,
181
+ "iou": config.iou,
182
+ "systems": [
183
+ {"name": s.name, "profile": s.profile, "policy": s.policy}
184
+ | ({} if s.pack is None else {"pack_sha256": _sha256(s.pack)})
185
+ for s in config.systems
186
+ ],
187
+ "lines": {
188
+ "ocr": sum(score.ocr_lines for score in first),
189
+ "truth": sum(score.truth_lines for score in first),
190
+ "matched": sum(score.matched_lines for score in first),
191
+ },
192
+ "uncorrected": _uncorrected(first, config),
193
+ "results": {name: _summary(pages, config) for name, pages in scores.items()},
194
+ "comparisons": {
195
+ f"{a} vs {b}": _comparison(scores[a], scores[b], config) for a, b in config.compare
196
+ },
197
+ }
198
+ return report
199
+
200
+
201
+ def write(report: dict[str, Any], folder: Path) -> tuple[Path, Path]:
202
+ """Write ``report`` as ``report.json`` and ``report.md`` in ``folder``; their paths."""
203
+ folder.mkdir(parents=True, exist_ok=True)
204
+ as_json = folder / "report.json"
205
+ as_markdown = folder / "report.md"
206
+ as_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8", newline="\n")
207
+ as_markdown.write_text(markdown(report), encoding="utf-8", newline="\n")
208
+ return as_json, as_markdown
209
+
210
+
211
+ def markdown(report: dict[str, Any]) -> str:
212
+ """The report as a Markdown page."""
213
+ lines = [
214
+ f"# {report['id']}",
215
+ "",
216
+ report["question"] or "(no question given)",
217
+ "",
218
+ f"- Pages: {report['pages']}; lines: {report['lines']['ocr']} OCR, "
219
+ f"{report['lines']['truth']} ground truth, {report['lines']['matched']} matched "
220
+ f"(IoU >= {report['iou']})",
221
+ f"- LECTRIS {report['lectris_version']}; manifest sha256 `{report['manifest_sha256']}`",
222
+ f"- Bootstrap: {report['resamples']} resamples over pages, seed {report['seed']}, 95%",
223
+ "",
224
+ "| System | CER (norm.) | CER (raw) | WER | ΔCER vs uncorrected | Harm rate | Fix / harm / "
225
+ "neutral / layout | Precision | Pages worse |",
226
+ "|---|---|---|---|---|---|---|---|---|",
227
+ ]
228
+ base = report["uncorrected"]
229
+ lines.append(
230
+ f"| uncorrected | {_pct(base['cer'])} | {_pct(base['cer_raw'])} | {_pct(base['wer'])} "
231
+ "| — | — | — | — | — |"
232
+ )
233
+ for name, result in report["results"].items():
234
+ lines.append(
235
+ f"| {name} | {_pct(result['cer'])} | {_pct(result['cer_raw'])} | "
236
+ f"{_pct(result['wer'])} | {_points(result['cer_change'])} | "
237
+ f"{_pct(result['harm_rate'], digits=3)} | "
238
+ f"{result['fixes']} / {result['harms']} / {result['neutral']} / "
239
+ f"{result['layout']} | "
240
+ f"{_pct(result['precision'])} | {_pct(result['pages_worse'])} |"
241
+ )
242
+ lines += [
243
+ "",
244
+ "Intervals are 95% paired-bootstrap percentile intervals over pages. ΔCER is the "
245
+ "system's normalised CER minus the uncorrected text's, in points. The harm rate is the "
246
+ "characters broken by harmful edits per reference character (ADR-0002). Layout edits "
247
+ "(de-hyphenation, unwrapping) are counted apart: the reference is laid out the same way "
248
+ "(lectris.eval.scoring, R-15).",
249
+ "",
250
+ ]
251
+ if report.get("comparisons"):
252
+ lines += [
253
+ "## Paired comparisons",
254
+ "",
255
+ "| A vs B | CER difference (points) | Repaired, per reference character | Broken |",
256
+ "|---|---|---|---|",
257
+ ]
258
+ lines.extend(
259
+ f"| {name} | {_points(c['cer'])} | {_points(c['fixed'])} | {_points(c['harmed'])} |"
260
+ for name, c in report["comparisons"].items()
261
+ )
262
+ lines += [
263
+ "",
264
+ "Each is A minus B, paired over pages, with its 95% bootstrap interval, in points of "
265
+ "the reference's characters.",
266
+ "",
267
+ ]
268
+ lines += [
269
+ "## Edits by rule",
270
+ "",
271
+ "| System | Rule | Fix | Harm | Neutral | Layout | Net effect (characters) |",
272
+ "|---|---|---|---|---|---|---|",
273
+ ]
274
+ for name, result in report["results"].items():
275
+ for rule, counts in result["by_rule"].items():
276
+ lines.append(
277
+ f"| {name} | `{rule}` | {counts['fix']} | {counts['harm']} | "
278
+ f"{counts['neutral']} | {counts['layout']} | {counts['effect']:+d} |"
279
+ )
280
+ lines += [
281
+ "",
282
+ "The net effect is the sum of the edits' effects on the distance to the reference: "
283
+ "below zero the rule repaired more than it broke. For a layout rule it is measured against "
284
+ "a reference laid out by the same rule, so it shows agreement, not accuracy.",
285
+ "",
286
+ ]
287
+ return "\n".join(lines)
288
+
289
+
290
+ def _comparisons(value: Any, names: Sequence[str]) -> tuple[tuple[str, str], ...]:
291
+ found = []
292
+ for index, item in array(value, "compare"):
293
+ pair = array(item, f"compare[{index}]")
294
+ if len(pair) != 2: # noqa: PLR2004 - a pair
295
+ raise FormatError(f"compare[{index}]: a comparison names two systems")
296
+ a, b = (string(name, f"compare[{index}][{i}]") for i, name in pair)
297
+ for name in (a, b):
298
+ if name not in names:
299
+ raise FormatError(f"compare[{index}]: no system called {name!r}")
300
+ found.append((a, b))
301
+ return tuple(found)
302
+
303
+
304
+ def _comparison(
305
+ first: Sequence[PageScore], second: Sequence[PageScore], config: Config
306
+ ) -> dict[str, Any]:
307
+ """Paired differences between two systems on the same pages: CER (normalised, points of
308
+ the reference), characters repaired and characters broken, per reference character."""
309
+ pairs = list(zip(first, second, strict=True))
310
+
311
+ def difference(key: Callable[[PageScore], int]) -> Callable[[Sequence[Any]], float]:
312
+ return lambda s: ratio([key(a) - key(b) for a, b in s], [a.chars.reference for a, _ in s])
313
+
314
+ def interval(statistic: Callable[[Sequence[Any]], float]) -> dict[str, float]:
315
+ found = bootstrap(pairs, statistic, resamples=config.resamples, seed=config.seed)
316
+ return {"estimate": found.estimate, "low": found.low, "high": found.high}
317
+
318
+ return {
319
+ "cer": interval(difference(lambda p: p.chars.after)),
320
+ "fixed": interval(difference(lambda p: p.fixed_chars)),
321
+ "harmed": interval(difference(lambda p: p.harm_chars)),
322
+ }
323
+
324
+
325
+ def _system(value: Any, path: str, folder: Path) -> System:
326
+ data = obj(value, path)
327
+ pack = data.get("pack")
328
+ system = System(
329
+ string(required(data, "name", path), f"{path}.name"),
330
+ string(data.get("profile", "standard"), f"{path}.profile"),
331
+ string(data.get("policy", "parity"), f"{path}.policy"),
332
+ None if pack is None else folder / string(pack, f"{path}.pack"),
333
+ )
334
+ if system.profile not in PROFILES:
335
+ raise FormatError(f"{path}.profile: no profile called {system.profile!r}")
336
+ if system.policy not in _POLICY_NAMES:
337
+ raise FormatError(
338
+ f"{path}.policy: one of {', '.join(_POLICY_NAMES)}, not {system.policy!r}"
339
+ )
340
+ if system.policy == "risk" and system.pack is None:
341
+ raise FormatError(f"{path}: the risk policy needs a pack")
342
+ return system
343
+
344
+
345
+ def _sha256(path: Path) -> str:
346
+ return hashlib.sha256(path.read_bytes()).hexdigest()
347
+
348
+
349
+ def _integer(data: dict[str, Any], key: str, default: int) -> int:
350
+ value = data.get(key, default)
351
+ if type(value) is not int or value < 0:
352
+ raise FormatError(f"{key}: a whole number, not {value!r}")
353
+ return value
354
+
355
+
356
+ def _interval(
357
+ pages: Sequence[PageScore], statistic: Callable[[Sequence[PageScore]], float], config: Config
358
+ ) -> dict[str, float]:
359
+ found: Interval = bootstrap(pages, statistic, resamples=config.resamples, seed=config.seed)
360
+ return {"estimate": found.estimate, "low": found.low, "high": found.high}
361
+
362
+
363
+ def _uncorrected(pages: Sequence[PageScore], config: Config) -> dict[str, Any]:
364
+ return {
365
+ "cer": _interval(
366
+ pages,
367
+ lambda s: ratio([p.chars.before for p in s], [p.chars.reference for p in s]),
368
+ config,
369
+ ),
370
+ "cer_raw": _interval(
371
+ pages,
372
+ lambda s: ratio([p.raw_chars.before for p in s], [p.raw_chars.reference for p in s]),
373
+ config,
374
+ ),
375
+ "wer": _interval(
376
+ pages,
377
+ lambda s: ratio([p.words.before for p in s], [p.words.reference for p in s]),
378
+ config,
379
+ ),
380
+ }
381
+
382
+
383
+ def _summary(pages: Sequence[PageScore], config: Config) -> dict[str, Any]:
384
+ fixes = sum(page.count("fix") for page in pages)
385
+ harms = sum(page.count("harm") for page in pages)
386
+ return {
387
+ "cer": _interval(
388
+ pages,
389
+ lambda s: ratio([p.chars.after for p in s], [p.chars.reference for p in s]),
390
+ config,
391
+ ),
392
+ "cer_raw": _interval(
393
+ pages,
394
+ lambda s: ratio([p.raw_chars.after for p in s], [p.raw_chars.reference for p in s]),
395
+ config,
396
+ ),
397
+ "wer": _interval(
398
+ pages,
399
+ lambda s: ratio([p.words.after for p in s], [p.words.reference for p in s]),
400
+ config,
401
+ ),
402
+ "cer_change": _interval(
403
+ pages,
404
+ lambda s: ratio(
405
+ [p.chars.after - p.chars.before for p in s], [p.chars.reference for p in s]
406
+ ),
407
+ config,
408
+ ),
409
+ "harm_rate": _interval(pages, lambda s: sum(p.harm_rate for p in s) / len(s), config),
410
+ "fixes": fixes,
411
+ "harms": harms,
412
+ "neutral": sum(page.count("neutral") for page in pages),
413
+ "layout": sum(page.count("layout") for page in pages),
414
+ "fixed_chars": sum(page.fixed_chars for page in pages),
415
+ "harm_chars": sum(page.harm_chars for page in pages),
416
+ "precision": fixes / (fixes + harms) if fixes + harms else None,
417
+ "pages_worse": sum(1 for page in pages if page.chars.after > page.chars.before)
418
+ / len(pages),
419
+ "by_rule": _by_rule(pages),
420
+ }
421
+
422
+
423
+ def _by_rule(pages: Sequence[PageScore]) -> dict[str, dict[str, int]]:
424
+ """Each rule's edits by label, and the sum of their effects, rules in name order."""
425
+ found: dict[str, dict[str, int]] = {}
426
+ for page in pages:
427
+ for item in page.labels:
428
+ counts = found.setdefault(
429
+ item.edit.rule, {"fix": 0, "harm": 0, "neutral": 0, "layout": 0, "effect": 0}
430
+ )
431
+ counts[item.label] += 1
432
+ counts["effect"] += item.effect
433
+ return dict(sorted(found.items()))
434
+
435
+
436
+ def _pct(value: Any, *, digits: int = 2) -> str:
437
+ if value is None:
438
+ return "—"
439
+ if isinstance(value, dict):
440
+ return (
441
+ f"{100 * value['estimate']:.{digits}f}% "
442
+ f"[{100 * value['low']:.{digits}f}, {100 * value['high']:.{digits}f}]"
443
+ )
444
+ return f"{100 * value:.{digits}f}%"
445
+
446
+
447
+ def _points(value: dict[str, float]) -> str:
448
+ return f"{100 * value['estimate']:+.2f} [{100 * value['low']:+.2f}, {100 * value['high']:+.2f}]"
lectris/eval/lines.py ADDED
@@ -0,0 +1,47 @@
1
+ """Matched lines of paired data: what the channel model and the language model are fitted on.
2
+
3
+ ``matched_lines(pairs)`` reads each page of a pairs manifest, drops the OCR lines on don't-care
4
+ ground truth, matches the OCR lines with the ground-truth lines that count, and returns, per page,
5
+ the matched pairs ``(intended, observed)`` and the text of every line that counts, both in the
6
+ normalised track (the form the proposers see once the transforms have run).
7
+ """
8
+
9
+ from collections.abc import Iterator, Sequence
10
+ from dataclasses import dataclass
11
+
12
+ from lectris import io
13
+ from lectris.eval import truth as truth_io
14
+ from lectris.eval.experiment import Pair
15
+ from lectris.eval.matching import match_lines
16
+ from lectris.eval.scoring import drop_dont_care, normalised
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class PageLines:
21
+ """One page's matched line pairs and its ground-truth lines that count."""
22
+
23
+ page: str
24
+ pairs: tuple[tuple[str, str], ...]
25
+ truth: tuple[str, ...]
26
+
27
+
28
+ def matched_lines(pairs: Sequence[Pair], *, iou_threshold: float = 0.5) -> Iterator[PageLines]:
29
+ """Each page's matched ``(intended, observed)`` lines and its ground-truth lines."""
30
+ for pair in pairs:
31
+ page = truth_io.read(pair.truth)
32
+ document = drop_dont_care(io.read(pair.engine), page, iou_threshold=iou_threshold)
33
+ counted = page.counted
34
+ lines = [line for p in document.pages for line in p.lines]
35
+ matching = match_lines(
36
+ [line.box for line in lines],
37
+ [line.box for line in counted.lines],
38
+ threshold=iou_threshold,
39
+ )
40
+ yield PageLines(
41
+ pair.page,
42
+ tuple(
43
+ (normalised(counted.lines[j].text), normalised(lines[i].text))
44
+ for i, j in matching.pairs
45
+ ),
46
+ tuple(normalised(line.text) for line in counted.lines),
47
+ )