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.
- lectris/__init__.py +45 -0
- lectris/align.py +159 -0
- lectris/cli.py +290 -0
- lectris/confidence.py +154 -0
- lectris/decide.py +164 -0
- lectris/distance.py +231 -0
- lectris/edits.py +253 -0
- lectris/errors.py +9 -0
- lectris/eval/__init__.py +14 -0
- lectris/eval/calibrate.py +187 -0
- lectris/eval/experiment.py +448 -0
- lectris/eval/lines.py +47 -0
- lectris/eval/matching.py +71 -0
- lectris/eval/scoring.py +437 -0
- lectris/eval/stats.py +58 -0
- lectris/eval/truth.py +103 -0
- lectris/evidence.py +147 -0
- lectris/io/__init__.py +62 -0
- lectris/io/_common.py +153 -0
- lectris/io/_json.py +145 -0
- lectris/io/alto.py +274 -0
- lectris/io/detect.py +74 -0
- lectris/io/glypharis.py +165 -0
- lectris/io/hocr.py +332 -0
- lectris/io/jsonio.py +269 -0
- lectris/io/plain.py +49 -0
- lectris/io/tsv.py +177 -0
- lectris/layout/__init__.py +129 -0
- lectris/layout/columns.py +71 -0
- lectris/layout/geometry.py +224 -0
- lectris/layout/lines.py +133 -0
- lectris/layout/order.py +240 -0
- lectris/layout/paragraphs.py +194 -0
- lectris/lexicon.py +240 -0
- lectris/metrics.py +123 -0
- lectris/model.py +247 -0
- lectris/models/__init__.py +11 -0
- lectris/models/acceptance.py +174 -0
- lectris/models/channel.py +136 -0
- lectris/models/charlm.py +183 -0
- lectris/models/pack.py +244 -0
- lectris/models/risk.py +101 -0
- lectris/pipeline.py +423 -0
- lectris/profiles.py +117 -0
- lectris/propose.py +177 -0
- lectris/py.typed +0 -0
- lectris/quality.py +269 -0
- lectris/report.py +157 -0
- lectris/text/__init__.py +1 -0
- lectris/text/confusables.py +176 -0
- lectris/text/hyphenation.py +149 -0
- lectris/text/lexis.py +46 -0
- lectris/text/noise.py +62 -0
- lectris/text/numbers.py +77 -0
- lectris/text/punctuation.py +257 -0
- lectris/text/unicode.py +301 -0
- lectris/text/unwrap.py +108 -0
- lectris/text/whitespace.py +81 -0
- lectris-0.3.0.dist-info/METADATA +243 -0
- lectris-0.3.0.dist-info/RECORD +62 -0
- lectris-0.3.0.dist-info/WHEEL +4 -0
- lectris-0.3.0.dist-info/entry_points.txt +3 -0
lectris/decide.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""The decision layer: which candidate edits are accepted, and why (architecture §11).
|
|
2
|
+
|
|
3
|
+
``decide(text, candidates, policy)`` judges each candidate under a policy, resolves overlaps
|
|
4
|
+
between those that pass, and returns the revision of ``text`` that makes the accepted ones, with
|
|
5
|
+
a ``Decision`` for every candidate.
|
|
6
|
+
|
|
7
|
+
Policies:
|
|
8
|
+
|
|
9
|
+
- ``PARITY`` (``Parity()``): accepts exactly the candidates a LECTRIS v0.1 rule would have
|
|
10
|
+
applied, those whose feature ``v01`` is 1. It is the default, so output is v0.1's
|
|
11
|
+
(ADR-0006).
|
|
12
|
+
- ``Threshold(score, threshold)``: accepts the candidates whose ``score`` (a probability that the
|
|
13
|
+
edit is right) is at least ``threshold``. It promises nothing about harm; the risk-controlled
|
|
14
|
+
policy of Phase 7 chooses its threshold with a guarantee.
|
|
15
|
+
|
|
16
|
+
Overlaps. Candidates that pass may overlap (two readings of one token). The accepted set is the
|
|
17
|
+
one, among sets of candidates that do not overlap, that maximises the expected number of
|
|
18
|
+
characters changed rightly, the sum of ``probability * size`` (``size`` is the longer of
|
|
19
|
+
``before`` and ``after``, at least 1; under ``PARITY`` the probability is 1). It is found by
|
|
20
|
+
weighted interval scheduling. A tie leaves the text as it was. Two candidates overlap when their
|
|
21
|
+
spans share a character, when both insert at one place, or when one inserts inside the other's
|
|
22
|
+
span; an insertion at the edge of another candidate's span does not overlap it.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from bisect import bisect_right
|
|
26
|
+
from collections.abc import Callable, Iterable
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import Final, Protocol
|
|
29
|
+
|
|
30
|
+
from lectris.edits import Candidate, Decision, Revision, revise
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Policy(Protocol):
|
|
34
|
+
"""How candidates are judged: whether each one passes, its probability and the bar."""
|
|
35
|
+
|
|
36
|
+
def judge(self, candidate: Candidate) -> tuple[bool, float | None, float | None, str]:
|
|
37
|
+
"""``(passes, probability, threshold, reason)`` for ``candidate``."""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True, slots=True)
|
|
42
|
+
class Parity:
|
|
43
|
+
"""Accepts the candidates whose feature ``v01`` is 1: what LECTRIS v0.1 applied."""
|
|
44
|
+
|
|
45
|
+
def judge(self, candidate: Candidate) -> tuple[bool, float | None, float | None, str]:
|
|
46
|
+
if candidate.feature("v01") == 1.0:
|
|
47
|
+
return True, None, None, "the v0.1 rule applies it"
|
|
48
|
+
return False, None, None, "the v0.1 rule declines it"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
PARITY: Final = Parity()
|
|
52
|
+
"""The default policy: v0.1's behaviour."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True, slots=True)
|
|
56
|
+
class Guarantee:
|
|
57
|
+
"""What a risk-controlled policy promises, and for which engine.
|
|
58
|
+
|
|
59
|
+
With probability at least ``1 - delta`` over the calibration pages, the expected harm rate on
|
|
60
|
+
new pages like them, from ``engine``'s ``model``, is at most ``alpha`` (ADR-0002, ADR-0008).
|
|
61
|
+
``threshold`` is ``None`` when no threshold could be certified: then no guess is accepted.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
alpha: float
|
|
65
|
+
delta: float
|
|
66
|
+
threshold: float | None
|
|
67
|
+
engine: str
|
|
68
|
+
model: str
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True, slots=True)
|
|
72
|
+
class Threshold:
|
|
73
|
+
"""Accepts the candidates whose ``score`` is at least ``threshold``, both in ``[0, 1]``.
|
|
74
|
+
|
|
75
|
+
A risk-controlled threshold (``lectris.models.pack.ModelPack.policy``) carries its
|
|
76
|
+
``guarantee``.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
score: Callable[[Candidate], float]
|
|
80
|
+
threshold: float
|
|
81
|
+
guarantee: Guarantee | None = None
|
|
82
|
+
|
|
83
|
+
def __post_init__(self) -> None:
|
|
84
|
+
if not 0 <= self.threshold <= 1:
|
|
85
|
+
raise ValueError(f"a threshold is between 0 and 1, not {self.threshold!r}")
|
|
86
|
+
|
|
87
|
+
def judge(self, candidate: Candidate) -> tuple[bool, float | None, float | None, str]:
|
|
88
|
+
probability = self.score(candidate)
|
|
89
|
+
if not 0 <= probability <= 1:
|
|
90
|
+
raise ValueError(f"a score is a probability in [0, 1], not {probability!r}")
|
|
91
|
+
if probability >= self.threshold:
|
|
92
|
+
return True, probability, self.threshold, "its probability reaches the threshold"
|
|
93
|
+
return False, probability, self.threshold, "its probability is below the threshold"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def decide(text: str, candidates: Iterable[Candidate], policy: Policy = PARITY) -> Revision:
|
|
97
|
+
"""The revision of ``text`` that makes the candidates ``policy`` accepts (module docs).
|
|
98
|
+
|
|
99
|
+
Every candidate gets a ``Decision``, in the order of their spans. Raises ``ValueError`` if a
|
|
100
|
+
candidate's ``before`` is not what ``text`` holds at its span.
|
|
101
|
+
"""
|
|
102
|
+
ordered = sorted(candidates, key=_order)
|
|
103
|
+
judged: list[tuple[Candidate, bool, float | None, float | None, str]] = []
|
|
104
|
+
for candidate in ordered:
|
|
105
|
+
if text[candidate.start : candidate.end] != candidate.before:
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f"{candidate.rule} expected {candidate.before!r} at {candidate.start}, "
|
|
108
|
+
f"found {text[candidate.start : candidate.end]!r}"
|
|
109
|
+
)
|
|
110
|
+
judged.append((candidate, *policy.judge(candidate)))
|
|
111
|
+
passing = [(candidate, probability) for candidate, ok, probability, _, _ in judged if ok]
|
|
112
|
+
accepted = _best_set(passing)
|
|
113
|
+
decisions: list[Decision] = []
|
|
114
|
+
for candidate, ok, probability, threshold, reason in judged:
|
|
115
|
+
if ok and id(candidate) not in accepted:
|
|
116
|
+
decisions.append(
|
|
117
|
+
Decision(candidate, False, "it overlaps a better candidate", probability, threshold)
|
|
118
|
+
)
|
|
119
|
+
else:
|
|
120
|
+
decisions.append(Decision(candidate, ok, reason, probability, threshold))
|
|
121
|
+
edits = (decision.candidate.edit() for decision in decisions if decision.accepted)
|
|
122
|
+
revision = revise(text, edits)
|
|
123
|
+
return Revision(revision.text, revision.edits, tuple(decisions))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _order(candidate: Candidate) -> tuple[int, int, str, str]:
|
|
127
|
+
return candidate.start, candidate.end, candidate.rule, candidate.after
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _interval(candidate: Candidate) -> tuple[int, int]:
|
|
131
|
+
"""The candidate's place on a doubled scale, as a half-open interval: there, overlapping
|
|
132
|
+
(as the module documents it) is plain interval overlap."""
|
|
133
|
+
if candidate.start == candidate.end:
|
|
134
|
+
return 2 * candidate.start, 2 * candidate.start + 1
|
|
135
|
+
return 2 * candidate.start + 1, 2 * candidate.end
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _best_set(passing: list[tuple[Candidate, float | None]]) -> set[int]:
|
|
139
|
+
"""The ids of the non-overlapping candidates with the largest total ``probability * size``,
|
|
140
|
+
by weighted interval scheduling; a tie keeps the smaller set (the text as it was)."""
|
|
141
|
+
items = sorted(
|
|
142
|
+
((_interval(candidate), candidate, 1.0 if p is None else p) for candidate, p in passing),
|
|
143
|
+
key=lambda item: (item[0][1], item[0][0], _order(item[1])),
|
|
144
|
+
)
|
|
145
|
+
ends = [interval[1] for interval, _, _ in items]
|
|
146
|
+
best = [0.0] # best[k]: the best total of the first k items
|
|
147
|
+
take: list[bool] = []
|
|
148
|
+
previous: list[int] = []
|
|
149
|
+
for k, ((start, _), candidate, probability) in enumerate(items):
|
|
150
|
+
before = bisect_right(ends, start, 0, k) # items wholly before this one
|
|
151
|
+
weight = probability * max(len(candidate.before), len(candidate.after), 1)
|
|
152
|
+
with_it = weight + best[before]
|
|
153
|
+
take.append(with_it > best[k])
|
|
154
|
+
previous.append(before)
|
|
155
|
+
best.append(with_it if take[k] else best[k])
|
|
156
|
+
chosen: set[int] = set()
|
|
157
|
+
k = len(items)
|
|
158
|
+
while k > 0:
|
|
159
|
+
if take[k - 1]:
|
|
160
|
+
chosen.add(id(items[k - 1][1]))
|
|
161
|
+
k = previous[k - 1]
|
|
162
|
+
else:
|
|
163
|
+
k -= 1
|
|
164
|
+
return chosen
|
lectris/distance.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Edit distances between strings, including one weighted for the confusions OCR makes.
|
|
2
|
+
|
|
3
|
+
``levenshtein`` and ``damerau_levenshtein`` count edits of one character. ``ocr_distance`` also
|
|
4
|
+
lets a character or short sequence turn into another at a cost below 1 when the two look alike in
|
|
5
|
+
print (``rn`` and ``m``, ``0`` and ``O``), so ``"modern"`` is nearer to ``"rnodern"`` than to
|
|
6
|
+
``"modest"``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from collections.abc import Mapping, Sequence
|
|
11
|
+
from types import MappingProxyType
|
|
12
|
+
from typing import Final
|
|
13
|
+
|
|
14
|
+
_SIMILAR: Final = 0.25
|
|
15
|
+
_ALIKE: Final = 0.5
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _symmetric(pairs: Mapping[tuple[str, str], float]) -> Mapping[tuple[str, str], float]:
|
|
19
|
+
table: dict[tuple[str, str], float] = {}
|
|
20
|
+
for (first, second), cost in pairs.items():
|
|
21
|
+
table[first, second] = cost
|
|
22
|
+
table[second, first] = cost
|
|
23
|
+
return MappingProxyType(table)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
OCR_COSTS: Final[Mapping[tuple[str, str], float]] = _symmetric(
|
|
27
|
+
{
|
|
28
|
+
# Glyphs that many print fonts draw alike, or nearly so.
|
|
29
|
+
("0", "O"): _SIMILAR,
|
|
30
|
+
("1", "l"): _SIMILAR,
|
|
31
|
+
("1", "I"): _SIMILAR,
|
|
32
|
+
("l", "I"): _SIMILAR,
|
|
33
|
+
("rn", "m"): _SIMILAR,
|
|
34
|
+
("vv", "w"): _SIMILAR,
|
|
35
|
+
("VV", "W"): _SIMILAR,
|
|
36
|
+
# Glyphs that are alike but differ in size, a stroke, a serif or a gap.
|
|
37
|
+
("0", "o"): _ALIKE,
|
|
38
|
+
("5", "S"): _ALIKE,
|
|
39
|
+
("8", "B"): _ALIKE,
|
|
40
|
+
("2", "Z"): _ALIKE,
|
|
41
|
+
("6", "b"): _ALIKE,
|
|
42
|
+
("e", "c"): _ALIKE,
|
|
43
|
+
("u", "n"): _ALIKE,
|
|
44
|
+
("cl", "d"): _ALIKE,
|
|
45
|
+
("li", "h"): _ALIKE,
|
|
46
|
+
("|", "l"): _ALIKE,
|
|
47
|
+
("|", "I"): _ALIKE,
|
|
48
|
+
("|", "1"): _ALIKE,
|
|
49
|
+
}
|
|
50
|
+
)
|
|
51
|
+
"""The substitution costs ``ocr_distance`` uses by default: ``(seen, meant) -> cost``.
|
|
52
|
+
|
|
53
|
+
The table is symmetric: each pair is listed in both directions with the same cost. Pairs that
|
|
54
|
+
many fonts draw almost identically cost 0.25: ``0``/``O``, ``1``/``l``/``I``, ``rn``/``m`` and
|
|
55
|
+
``vv``/``w`` (``VV``/``W``). Pairs that are alike but differ in size, a stroke, a serif or a gap
|
|
56
|
+
cost 0.5: ``0``/``o``, ``5``/``S``, ``8``/``B``, ``2``/``Z``, ``6``/``b``, ``e``/``c``,
|
|
57
|
+
``u``/``n``, ``cl``/``d``, ``li``/``h``, and ``|`` with ``l``, ``I`` and ``1``. Any other
|
|
58
|
+
substitution costs 1.
|
|
59
|
+
|
|
60
|
+
The costs are heuristics chosen from glyph shapes, not measured from OCR output. Pass your own
|
|
61
|
+
table to ``ocr_distance`` when you have confusion counts for your engine and fonts.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def levenshtein(a: str, b: str) -> int:
|
|
66
|
+
"""The Levenshtein distance: the fewest insertions, deletions and substitutions of one
|
|
67
|
+
character that turn ``a`` into ``b``.
|
|
68
|
+
|
|
69
|
+
It is a metric. Time is ``O(len(a) * len(b))``.
|
|
70
|
+
|
|
71
|
+
>>> levenshtein("kitten", "sitting")
|
|
72
|
+
3
|
|
73
|
+
"""
|
|
74
|
+
if len(a) < len(b):
|
|
75
|
+
a, b = b, a
|
|
76
|
+
previous = list(range(len(b) + 1))
|
|
77
|
+
for i, char_a in enumerate(a, start=1):
|
|
78
|
+
current = [i]
|
|
79
|
+
for j, char_b in enumerate(b, start=1):
|
|
80
|
+
current.append(
|
|
81
|
+
min(
|
|
82
|
+
previous[j] + 1,
|
|
83
|
+
current[j - 1] + 1,
|
|
84
|
+
previous[j - 1] + (char_a != char_b),
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
previous = current
|
|
88
|
+
return previous[-1]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def damerau_levenshtein(a: str, b: str) -> int:
|
|
92
|
+
"""The optimal string alignment distance: Levenshtein's edits plus the transposition of two
|
|
93
|
+
adjacent characters, each costing 1.
|
|
94
|
+
|
|
95
|
+
This is the restricted Damerau-Levenshtein distance: no character is edited after it has
|
|
96
|
+
been transposed, so ``"ca"`` to ``"abc"`` costs 3 here (the unrestricted distance is 2), and
|
|
97
|
+
the triangle inequality does not always hold. Time is ``O(len(a) * len(b))``.
|
|
98
|
+
|
|
99
|
+
>>> damerau_levenshtein("form", "from")
|
|
100
|
+
1
|
|
101
|
+
"""
|
|
102
|
+
before: list[int] = []
|
|
103
|
+
previous = list(range(len(b) + 1))
|
|
104
|
+
for i in range(1, len(a) + 1):
|
|
105
|
+
current = [i]
|
|
106
|
+
for j in range(1, len(b) + 1):
|
|
107
|
+
distance = min(
|
|
108
|
+
previous[j] + 1,
|
|
109
|
+
current[j - 1] + 1,
|
|
110
|
+
previous[j - 1] + (a[i - 1] != b[j - 1]),
|
|
111
|
+
)
|
|
112
|
+
if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
|
|
113
|
+
distance = min(distance, before[j - 2] + 1)
|
|
114
|
+
current.append(distance)
|
|
115
|
+
before, previous = previous, current
|
|
116
|
+
return previous[-1]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# The weighted programme below is shared with lectris.lexicon, whose suggestions run it over many
|
|
120
|
+
# words with a common prefix. A table entry seen from the programme: the length of its span in
|
|
121
|
+
# the first string, its span in the second string, that span's length, and its cost.
|
|
122
|
+
type _Span = tuple[int, str, int, float]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class _CostIndex:
|
|
126
|
+
"""A substitution table arranged for the dynamic programme, indexed by its first strings."""
|
|
127
|
+
|
|
128
|
+
__slots__ = ("by_source", "longest_source", "longest_target", "target_prefixes")
|
|
129
|
+
|
|
130
|
+
def __init__(self, costs: Mapping[tuple[str, str], float]) -> None:
|
|
131
|
+
by_source: dict[str, list[tuple[str, float]]] = {}
|
|
132
|
+
for key, cost in costs.items():
|
|
133
|
+
source, target = key
|
|
134
|
+
if not source or not target or source == target:
|
|
135
|
+
raise ValueError(
|
|
136
|
+
f"a cost is for two different non-empty strings, not {source!r} and {target!r}"
|
|
137
|
+
)
|
|
138
|
+
if not (math.isfinite(cost) and cost >= 0):
|
|
139
|
+
raise ValueError(
|
|
140
|
+
f"a cost is a finite number of at least 0, not {cost!r} for {key!r}"
|
|
141
|
+
)
|
|
142
|
+
by_source.setdefault(source, []).append((target, float(cost)))
|
|
143
|
+
self.by_source = {source: tuple(found) for source, found in by_source.items()}
|
|
144
|
+
self.longest_source = max(map(len, by_source), default=0)
|
|
145
|
+
self.longest_target = max(
|
|
146
|
+
(len(target) for found in by_source.values() for target, _ in found), default=1
|
|
147
|
+
)
|
|
148
|
+
# The beginnings of second strings longer than one character: a row of the programme can
|
|
149
|
+
# be stepped over only by an entry whose second string starts with what that row ends in.
|
|
150
|
+
self.target_prefixes = frozenset(
|
|
151
|
+
target[:length]
|
|
152
|
+
for found in by_source.values()
|
|
153
|
+
for target, _ in found
|
|
154
|
+
for length in range(1, len(target))
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
def spans(self, a: str) -> list[tuple[_Span, ...]]:
|
|
158
|
+
"""For each position ``i`` in ``a`` (``0`` to ``len(a)``), the table entries whose first
|
|
159
|
+
string ends there."""
|
|
160
|
+
result: list[tuple[_Span, ...]] = [()]
|
|
161
|
+
for end in range(1, len(a) + 1):
|
|
162
|
+
found: list[_Span] = []
|
|
163
|
+
for length in range(1, min(self.longest_source, end) + 1):
|
|
164
|
+
for target, cost in self.by_source.get(a[end - length : end], ()):
|
|
165
|
+
found.append((length, target, len(target), cost))
|
|
166
|
+
result.append(tuple(found))
|
|
167
|
+
return result
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
_OCR_INDEX: Final = _CostIndex(OCR_COSTS)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _cost_index(costs: Mapping[tuple[str, str], float]) -> _CostIndex:
|
|
174
|
+
return _OCR_INDEX if costs is OCR_COSTS else _CostIndex(costs)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _first_row(a: str) -> list[float]:
|
|
178
|
+
return [float(i) for i in range(len(a) + 1)]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _next_row(
|
|
182
|
+
a: str, spans: Sequence[tuple[_Span, ...]], rows: Sequence[list[float]], b: str, j: int
|
|
183
|
+
) -> list[float]:
|
|
184
|
+
"""Row ``j`` of the weighted programme: the cost from each prefix of ``a`` to ``b[:j]``.
|
|
185
|
+
|
|
186
|
+
``rows[-1]`` is row ``j - 1``, ``rows[-2]`` row ``j - 2``, and so on: at least as many rows
|
|
187
|
+
as the table's longest second string, or all of them when ``j`` is smaller.
|
|
188
|
+
"""
|
|
189
|
+
previous = rows[-1]
|
|
190
|
+
char = b[j - 1]
|
|
191
|
+
row = [previous[0] + 1.0]
|
|
192
|
+
for i in range(1, len(a) + 1):
|
|
193
|
+
diagonal = previous[i - 1] if a[i - 1] == char else previous[i - 1] + 1.0
|
|
194
|
+
best = min(previous[i] + 1.0, row[i - 1] + 1.0, diagonal)
|
|
195
|
+
for length, target, target_length, weight in spans[i]:
|
|
196
|
+
if target_length <= j and b[j - target_length : j] == target:
|
|
197
|
+
best = min(best, rows[-target_length][i - length] + weight)
|
|
198
|
+
row.append(best)
|
|
199
|
+
return row
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def ocr_distance(a: str, b: str, *, costs: Mapping[tuple[str, str], float] = OCR_COSTS) -> float:
|
|
203
|
+
"""A weighted edit distance where the substitutions OCR makes cost less than 1.
|
|
204
|
+
|
|
205
|
+
Inserting, deleting or substituting one character costs 1, as in ``levenshtein``. In
|
|
206
|
+
addition, a span ``x`` of ``a`` may become a span ``y`` of ``b`` at ``costs[(x, y)]``; the
|
|
207
|
+
spans may be longer than one character (``("rn", "m")``). The result is the cheapest
|
|
208
|
+
combination, so it is never more than ``levenshtein(a, b)``, and it is symmetric when the
|
|
209
|
+
table is (``OCR_COSTS`` is). Each character takes part in at most one operation, so it is
|
|
210
|
+
not a metric: confusions that share a character do not chain, and ``"ru"`` is 0.5 from
|
|
211
|
+
``"rn"``, which is 0.25 from ``"m"``, but 2 from ``"m"``.
|
|
212
|
+
|
|
213
|
+
Time is ``O(len(a) * len(b) * k)``, where ``k`` is the number of table entries that can end
|
|
214
|
+
at one position of ``a`` (a handful for ``OCR_COSTS``).
|
|
215
|
+
|
|
216
|
+
Raises ``ValueError`` if a key of ``costs`` is not two different non-empty strings or a cost
|
|
217
|
+
is negative or not finite.
|
|
218
|
+
|
|
219
|
+
>>> ocr_distance("modern", "rnodern")
|
|
220
|
+
0.25
|
|
221
|
+
>>> levenshtein("modern", "rnodern")
|
|
222
|
+
2
|
|
223
|
+
"""
|
|
224
|
+
index = _cost_index(costs)
|
|
225
|
+
spans = index.spans(a)
|
|
226
|
+
rows = [_first_row(a)]
|
|
227
|
+
for j in range(1, len(b) + 1):
|
|
228
|
+
rows.append(_next_row(a, spans, rows, b, j))
|
|
229
|
+
if len(rows) > index.longest_target:
|
|
230
|
+
del rows[0]
|
|
231
|
+
return rows[-1][-1]
|
lectris/edits.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Edits: how every text rule records what it changed.
|
|
2
|
+
|
|
3
|
+
A rule returns a ``Revision``: its output text, and the edits that turn its input into that
|
|
4
|
+
output. ``start`` and ``end`` are offsets in the input; edits are sorted and do not overlap, and
|
|
5
|
+
``apply_edits(input, revision.edits) == revision.text`` always holds. ``OffsetMap`` maps a span
|
|
6
|
+
of a revision's output, or of the output of several revisions in turn, back to the input.
|
|
7
|
+
|
|
8
|
+
A proposer suggests ``Candidate`` edits instead; ``lectris.decide`` turns each into a
|
|
9
|
+
``Decision`` and the accepted ones into the revision's edits.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from bisect import bisect_right
|
|
14
|
+
from collections.abc import Callable, Iterable
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class Edit:
|
|
20
|
+
"""One change: ``input[start:end]`` (``before``) replaced by ``after``, by ``rule``."""
|
|
21
|
+
|
|
22
|
+
rule: str
|
|
23
|
+
start: int
|
|
24
|
+
end: int
|
|
25
|
+
before: str
|
|
26
|
+
after: str
|
|
27
|
+
|
|
28
|
+
def __post_init__(self) -> None:
|
|
29
|
+
if not 0 <= self.start <= self.end:
|
|
30
|
+
raise ValueError(f"an edit needs 0 <= start <= end, not {self.start}..{self.end}")
|
|
31
|
+
if len(self.before) != self.end - self.start:
|
|
32
|
+
raise ValueError(
|
|
33
|
+
f"'before' is {len(self.before)} characters, the span {self.end - self.start}"
|
|
34
|
+
)
|
|
35
|
+
if self.before == self.after:
|
|
36
|
+
raise ValueError(
|
|
37
|
+
f"an edit changes something; {self.rule} replaced {self.before!r} with itself"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True, slots=True)
|
|
42
|
+
class Candidate:
|
|
43
|
+
"""An edit a proposer suggests, with the evidence it found, before anything decides on it.
|
|
44
|
+
|
|
45
|
+
The span, ``before`` and ``after`` follow ``Edit``'s rules. ``features`` are named numbers
|
|
46
|
+
the decision layer reads, sorted by name, each name once (``feature`` reads one).
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
rule: str
|
|
50
|
+
start: int
|
|
51
|
+
end: int
|
|
52
|
+
before: str
|
|
53
|
+
after: str
|
|
54
|
+
features: tuple[tuple[str, float], ...] = ()
|
|
55
|
+
|
|
56
|
+
def __post_init__(self) -> None:
|
|
57
|
+
self.edit() # the same checks as an edit's
|
|
58
|
+
names = [name for name, _ in self.features]
|
|
59
|
+
if names != sorted(set(names)):
|
|
60
|
+
raise ValueError(f"a candidate's features are sorted by name, each once: {names}")
|
|
61
|
+
|
|
62
|
+
def edit(self) -> Edit:
|
|
63
|
+
"""The edit this candidate would make."""
|
|
64
|
+
return Edit(self.rule, self.start, self.end, self.before, self.after)
|
|
65
|
+
|
|
66
|
+
def feature(self, name: str, default: float = 0.0) -> float:
|
|
67
|
+
"""The value of the feature ``name``, or ``default`` if the candidate has none."""
|
|
68
|
+
for key, value in self.features:
|
|
69
|
+
if key == name:
|
|
70
|
+
return value
|
|
71
|
+
return default
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True)
|
|
75
|
+
class Decision:
|
|
76
|
+
"""What the decision layer made of a candidate: accepted or not, and why.
|
|
77
|
+
|
|
78
|
+
``probability`` is the candidate's chance of being right and ``threshold`` the bar it had to
|
|
79
|
+
reach, when the policy has them; ``reason`` says in words why it was accepted or declined.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
candidate: Candidate
|
|
83
|
+
accepted: bool
|
|
84
|
+
reason: str
|
|
85
|
+
probability: float | None = None
|
|
86
|
+
threshold: float | None = None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True, slots=True)
|
|
90
|
+
class Revision:
|
|
91
|
+
"""A rule's output: the new text, and the edits from the rule's input to it.
|
|
92
|
+
|
|
93
|
+
A proposer's revision also keeps its ``decisions``: one per candidate, accepted or declined.
|
|
94
|
+
Its accepted candidates are its edits.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
text: str
|
|
98
|
+
edits: tuple[Edit, ...] = ()
|
|
99
|
+
decisions: tuple[Decision, ...] = ()
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def changed(self) -> bool:
|
|
103
|
+
return bool(self.edits)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True, slots=True)
|
|
107
|
+
class _Stage:
|
|
108
|
+
"""One revision's edits, laid out for mapping its output offsets back to its input."""
|
|
109
|
+
|
|
110
|
+
out_starts: tuple[int, ...]
|
|
111
|
+
out_ends: tuple[int, ...]
|
|
112
|
+
in_starts: tuple[int, ...]
|
|
113
|
+
in_ends: tuple[int, ...]
|
|
114
|
+
shifts: tuple[int, ...] # shifts[k]: output length minus input length of the first k edits
|
|
115
|
+
|
|
116
|
+
@classmethod
|
|
117
|
+
def of(cls, edits: Iterable[Edit]) -> "_Stage":
|
|
118
|
+
ordered = sorted(edits, key=lambda edit: (edit.start, edit.end))
|
|
119
|
+
out_starts, out_ends, shifts = [], [], [0]
|
|
120
|
+
position = 0
|
|
121
|
+
for edit in ordered:
|
|
122
|
+
if edit.start < position:
|
|
123
|
+
raise ValueError(f"edits overlap or are out of order at offset {edit.start}")
|
|
124
|
+
position = edit.end
|
|
125
|
+
start = edit.start + shifts[-1]
|
|
126
|
+
out_starts.append(start)
|
|
127
|
+
out_ends.append(start + len(edit.after))
|
|
128
|
+
shifts.append(shifts[-1] + len(edit.after) - len(edit.before))
|
|
129
|
+
return cls(
|
|
130
|
+
tuple(out_starts),
|
|
131
|
+
tuple(out_ends),
|
|
132
|
+
tuple(edit.start for edit in ordered),
|
|
133
|
+
tuple(edit.end for edit in ordered),
|
|
134
|
+
tuple(shifts),
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def origin(self, offset: int) -> tuple[int, int]:
|
|
138
|
+
"""The input span the output character at ``offset`` came from (see ``OffsetMap``)."""
|
|
139
|
+
before = bisect_right(self.out_ends, offset) # edits wholly before the character
|
|
140
|
+
if before < len(self.out_starts) and self.out_starts[before] <= offset:
|
|
141
|
+
return self.in_starts[before], self.in_ends[before] # an edit wrote it
|
|
142
|
+
kept = offset - self.shifts[before]
|
|
143
|
+
return kept, kept + 1
|
|
144
|
+
|
|
145
|
+
def source(self, start: int, end: int) -> tuple[int, int]:
|
|
146
|
+
if start == end:
|
|
147
|
+
position = self.origin(start)[0]
|
|
148
|
+
return position, position
|
|
149
|
+
return self.origin(start)[0], self.origin(end - 1)[1]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@dataclass(frozen=True, slots=True)
|
|
153
|
+
class OffsetMap:
|
|
154
|
+
"""Where a span of a text came from, through one or more revisions.
|
|
155
|
+
|
|
156
|
+
``OffsetMap.from_edits(revision.edits)`` maps the revision's output back to its input, and
|
|
157
|
+
``first.then(second)`` maps the output of a later revision back to the input of the first,
|
|
158
|
+
across both. ``source(start, end)`` gives the smallest span of the input that the output span
|
|
159
|
+
came from:
|
|
160
|
+
|
|
161
|
+
- a character an edit left alone comes from its own place, so text no edit touched maps
|
|
162
|
+
exactly: ``output[start:end] == input[slice(*source(start, end))]`` for such a span;
|
|
163
|
+
- a character an edit wrote comes from the whole span the edit replaced, so a span that
|
|
164
|
+
reaches into an edit's text covers all of what the edit replaced (an insertion's characters
|
|
165
|
+
come from the empty span where it was inserted);
|
|
166
|
+
- an empty span (a position) maps to where the character at that position came from, and the
|
|
167
|
+
end of the output to the end of the input.
|
|
168
|
+
|
|
169
|
+
Offsets are not checked against the text's length: past the end, they map as if the text
|
|
170
|
+
went on unchanged.
|
|
171
|
+
|
|
172
|
+
>>> revision = substitute("1O5 apples", "O", "0", "confusables.in_numbers")
|
|
173
|
+
>>> offsets = OffsetMap.from_edits(revision.edits)
|
|
174
|
+
>>> offsets.source(4, 10), offsets.source(0, 3)
|
|
175
|
+
((4, 10), (0, 3))
|
|
176
|
+
"""
|
|
177
|
+
|
|
178
|
+
stages: tuple[_Stage, ...] = ()
|
|
179
|
+
|
|
180
|
+
@classmethod
|
|
181
|
+
def from_edits(cls, edits: Iterable[Edit]) -> "OffsetMap":
|
|
182
|
+
"""The map from a revision's output back to its input, given its edits.
|
|
183
|
+
|
|
184
|
+
The edits must not overlap (they may come in any order); ``ValueError`` otherwise.
|
|
185
|
+
"""
|
|
186
|
+
return cls((_Stage.of(edits),))
|
|
187
|
+
|
|
188
|
+
def then(self, later: "OffsetMap") -> "OffsetMap":
|
|
189
|
+
"""The map from ``later``'s output back to this map's input: ``later`` applies after."""
|
|
190
|
+
return OffsetMap(self.stages + later.stages)
|
|
191
|
+
|
|
192
|
+
def source(self, start: int, end: int | None = None) -> tuple[int, int]:
|
|
193
|
+
"""The input span the output span ``[start, end)`` came from; ``end`` defaults to
|
|
194
|
+
``start`` (a position). ``ValueError`` unless ``0 <= start <= end``."""
|
|
195
|
+
stop = start if end is None else end
|
|
196
|
+
if not 0 <= start <= stop:
|
|
197
|
+
raise ValueError(f"a span needs 0 <= start <= end, not {start}..{stop}")
|
|
198
|
+
for stage in reversed(self.stages):
|
|
199
|
+
start, stop = stage.source(start, stop)
|
|
200
|
+
return start, stop
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def unchanged(text: str) -> Revision:
|
|
204
|
+
"""The revision of a rule that changed nothing."""
|
|
205
|
+
return Revision(text)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def apply_edits(text: str, edits: Iterable[Edit]) -> str:
|
|
209
|
+
"""``text`` with the edits applied. They must be sorted, not overlap, and match ``text``."""
|
|
210
|
+
pieces: list[str] = []
|
|
211
|
+
position = 0
|
|
212
|
+
for edit in edits:
|
|
213
|
+
if edit.start < position:
|
|
214
|
+
raise ValueError(f"edits overlap or are out of order at offset {edit.start}")
|
|
215
|
+
if text[edit.start : edit.end] != edit.before:
|
|
216
|
+
raise ValueError(
|
|
217
|
+
f"{edit.rule} expected {edit.before!r} at {edit.start}, "
|
|
218
|
+
f"found {text[edit.start : edit.end]!r}"
|
|
219
|
+
)
|
|
220
|
+
pieces.append(text[position : edit.start])
|
|
221
|
+
pieces.append(edit.after)
|
|
222
|
+
position = edit.end
|
|
223
|
+
pieces.append(text[position:])
|
|
224
|
+
return "".join(pieces)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def revise(text: str, edits: Iterable[Edit]) -> Revision:
|
|
228
|
+
"""The revision that applies ``edits`` (in any order) to ``text``."""
|
|
229
|
+
ordered = tuple(sorted(edits, key=lambda edit: (edit.start, edit.end)))
|
|
230
|
+
return Revision(apply_edits(text, ordered), ordered)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def substitute(
|
|
234
|
+
text: str,
|
|
235
|
+
pattern: "re.Pattern[str] | str",
|
|
236
|
+
replace: "str | Callable[[re.Match[str]], str | None]",
|
|
237
|
+
rule: str,
|
|
238
|
+
) -> Revision:
|
|
239
|
+
"""Replace each match of ``pattern``, recording one edit per match that changes the text.
|
|
240
|
+
|
|
241
|
+
``replace`` is a string (expanded like ``re.sub``'s, so ``\\1`` works) or a function of the
|
|
242
|
+
match. A function returning ``None`` leaves that match as it was: the way to decline a match
|
|
243
|
+
the pattern found but the evidence does not support.
|
|
244
|
+
"""
|
|
245
|
+
compiled = re.compile(pattern) if isinstance(pattern, str) else pattern
|
|
246
|
+
edits: list[Edit] = []
|
|
247
|
+
for match in compiled.finditer(text):
|
|
248
|
+
after = match.expand(replace) if isinstance(replace, str) else replace(match)
|
|
249
|
+
before = match.group(0)
|
|
250
|
+
if after is None or after == before:
|
|
251
|
+
continue
|
|
252
|
+
edits.append(Edit(rule, match.start(), match.end(), before, after))
|
|
253
|
+
return revise(text, edits)
|
lectris/errors.py
ADDED
lectris/eval/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Evaluation: how much a correction helps and how much it harms (experiment protocol).
|
|
2
|
+
|
|
3
|
+
- ``truth``: a page's ground truth, as lines with their text and box.
|
|
4
|
+
- ``matching``: OCR lines matched one to one with ground-truth lines by box overlap, so that a
|
|
5
|
+
difference in reading order is not counted as recognition errors.
|
|
6
|
+
- ``scoring``: each block compared with the ground truth of its lines; character and word error
|
|
7
|
+
rates in the raw and the normalised tracks; every edit labelled a fix, a harm or neutral; the
|
|
8
|
+
harm rate of a page.
|
|
9
|
+
- ``stats``: the paired bootstrap over pages.
|
|
10
|
+
- ``experiment``: a registered experiment run from its configuration into a report.
|
|
11
|
+
|
|
12
|
+
It reads files and writes reports, so, like ``lectris.io`` and the CLI, it does I/O; its numbers
|
|
13
|
+
are deterministic for a seed.
|
|
14
|
+
"""
|