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
lectris/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """LECTRIS: OCR output, read back into clean, ordered text.
2
+
3
+ ``clean()`` runs a profile's layout and text rules and returns the text with every edit it
4
+ made; ``lectris.io`` reads OCR formats; ``lectris.report`` renders what changed;
5
+ ``lectris.metrics`` measures OCR against a reference.
6
+ """
7
+
8
+ from importlib.metadata import PackageNotFoundError, version
9
+
10
+ from lectris import io, metrics, report
11
+ from lectris.edits import Edit, Revision
12
+ from lectris.errors import FormatError, LectrisError
13
+ from lectris.lexicon import Lexicon
14
+ from lectris.model import Block, Box, Document, Line, Page, Word
15
+ from lectris.pipeline import CleanBlock, Profile, Result, Step, clean
16
+ from lectris.profiles import PROFILES
17
+
18
+ try:
19
+ __version__ = version("lectris")
20
+ except PackageNotFoundError: # running from a source tree that is not installed
21
+ __version__ = "0.0.0"
22
+
23
+ __all__ = [
24
+ "PROFILES",
25
+ "Block",
26
+ "Box",
27
+ "CleanBlock",
28
+ "Document",
29
+ "Edit",
30
+ "FormatError",
31
+ "LectrisError",
32
+ "Lexicon",
33
+ "Line",
34
+ "Page",
35
+ "Profile",
36
+ "Result",
37
+ "Revision",
38
+ "Step",
39
+ "Word",
40
+ "__version__",
41
+ "clean",
42
+ "io",
43
+ "metrics",
44
+ "report",
45
+ ]
lectris/align.py ADDED
@@ -0,0 +1,159 @@
1
+ """Alignment: a minimum-edit (Levenshtein) alignment of two sequences, of characters or words.
2
+
3
+ ``align`` pairs a reference with a hypothesis (usually a transcription with OCR output) as a
4
+ list of operations, one per element: ``equal``, ``substitute``, ``insert`` (an element only the
5
+ hypothesis has) or ``delete`` (an element only the reference has). The number of operations that
6
+ are not ``equal`` is the Levenshtein distance; every operation costs 1.
7
+
8
+ Several alignments are often equally short; ``align`` picks one deterministically:
9
+
10
+ 1. Elements the two sequences share at the start and at the end are aligned as ``equal``.
11
+ 2. Between them, the alignment is traced back from the end, and at each step the first of these
12
+ that still leads to a minimum-cost alignment is taken: pair the two current elements
13
+ (``equal`` or ``substitute``), then ``delete`` the reference element, then ``insert`` the
14
+ hypothesis element.
15
+
16
+ So ``"ab"`` against ``"ba"`` is two substitutions, not a deletion and an insertion. The work is
17
+ proportional to the length times the distance (a band around the diagonal, widened until it
18
+ holds the distance), so long texts with few errors align quickly.
19
+ """
20
+
21
+ from collections.abc import Sequence
22
+ from dataclasses import dataclass
23
+ from typing import Final, Literal
24
+
25
+ type OpKind = Literal["equal", "substitute", "insert", "delete"]
26
+
27
+ KINDS: Final[tuple[OpKind, ...]] = ("equal", "substitute", "insert", "delete")
28
+
29
+ _PAIR: Final = 1
30
+ _DELETE: Final = 2
31
+ _INSERT: Final = 3
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class Op:
36
+ """One step of an alignment: a reference element, a hypothesis element, or both.
37
+
38
+ ``equal`` and ``substitute`` hold one element of each (the same, and different);
39
+ ``insert`` has ``reference == ""`` and ``delete`` has ``hypothesis == ""``.
40
+ """
41
+
42
+ kind: OpKind
43
+ reference: str
44
+ hypothesis: str
45
+
46
+ def __post_init__(self) -> None:
47
+ if self.kind not in KINDS:
48
+ raise ValueError(f"an op's kind is one of {', '.join(KINDS)}, not {self.kind!r}")
49
+ valid = {
50
+ "equal": self.reference == self.hypothesis,
51
+ "substitute": self.reference != self.hypothesis,
52
+ "insert": self.reference == "",
53
+ "delete": self.hypothesis == "",
54
+ }[self.kind]
55
+ if not valid:
56
+ raise ValueError(
57
+ f"{self.reference!r} and {self.hypothesis!r} cannot make a {self.kind!r} op"
58
+ )
59
+
60
+
61
+ def align(reference: Sequence[str], hypothesis: Sequence[str]) -> tuple[Op, ...]:
62
+ """A minimum-edit alignment of two sequences of strings, one ``Op`` per element.
63
+
64
+ Pass two ``str`` to align characters, or two lists of words to align words. Elements are
65
+ compared with ``==``. The module describes which alignment is chosen when several are
66
+ equally short.
67
+ """
68
+ n, m = len(reference), len(hypothesis)
69
+ prefix = 0
70
+ while prefix < min(n, m) and reference[prefix] == hypothesis[prefix]:
71
+ prefix += 1
72
+ suffix = 0
73
+ while suffix < min(n, m) - prefix and reference[n - 1 - suffix] == hypothesis[m - 1 - suffix]:
74
+ suffix += 1
75
+ middle = _align_middle(reference[prefix : n - suffix], hypothesis[prefix : m - suffix])
76
+ return (
77
+ *(Op("equal", element, element) for element in reference[:prefix]),
78
+ *middle,
79
+ *(Op("equal", element, element) for element in reference[n - suffix :]),
80
+ )
81
+
82
+
83
+ def align_chars(reference: str, hypothesis: str) -> tuple[Op, ...]:
84
+ """The character alignment of two texts: one ``Op`` per character."""
85
+ return align(reference, hypothesis)
86
+
87
+
88
+ def align_words(reference: str, hypothesis: str) -> tuple[Op, ...]:
89
+ """The word alignment of two texts, whose words are their whitespace-separated pieces."""
90
+ return align(reference.split(), hypothesis.split())
91
+
92
+
93
+ def _align_middle(reference: Sequence[str], hypothesis: Sequence[str]) -> list[Op]:
94
+ if not reference:
95
+ return [Op("insert", "", element) for element in hypothesis]
96
+ if not hypothesis:
97
+ return [Op("delete", element, "") for element in reference]
98
+ bound = max(abs(len(hypothesis) - len(reference)), 1)
99
+ while (ops := _align_banded(reference, hypothesis, bound)) is None:
100
+ bound *= 2
101
+ return ops
102
+
103
+
104
+ def _align_banded(
105
+ reference: Sequence[str], hypothesis: Sequence[str], bound: int
106
+ ) -> list[Op] | None:
107
+ """The alignment if the distance is at most ``bound``, else ``None``.
108
+
109
+ Only cells ``(i, j)`` with ``|j - i| + |delta - (j - i)| <= bound`` are computed, where
110
+ ``delta = len(hypothesis) - len(reference)``: an alignment through any other cell costs more
111
+ than ``bound``. When the distance is at most ``bound``, every minimum-cost alignment lies in
112
+ the band, so the costs on them and the steps chosen are those of the full table.
113
+ """
114
+ n, m = len(reference), len(hypothesis)
115
+ delta = m - n
116
+ slack = (bound - abs(delta)) // 2
117
+ low, high = min(0, delta) - slack, max(0, delta) + slack
118
+ starts = [0]
119
+ steps = [bytearray([0, *([_INSERT] * min(m, high))])]
120
+ previous = list(range(min(m, high) + 1))
121
+ previous_start = 0
122
+ for i in range(1, n + 1):
123
+ element = reference[i - 1]
124
+ start, stop = max(0, i + low), min(m, i + high)
125
+ costs = [0] * (stop - start + 1)
126
+ row = bytearray(stop - start + 1)
127
+ width = len(previous)
128
+ for j in range(start, stop + 1):
129
+ best, step = n + m + 1, 0
130
+ above = j - previous_start
131
+ if 0 < above <= width:
132
+ best, step = previous[above - 1] + (element != hypothesis[j - 1]), _PAIR
133
+ if 0 <= above < width and previous[above] + 1 < best:
134
+ best, step = previous[above] + 1, _DELETE
135
+ if j > start and costs[j - 1 - start] + 1 < best:
136
+ best, step = costs[j - 1 - start] + 1, _INSERT
137
+ costs[j - start] = best
138
+ row[j - start] = step
139
+ starts.append(start)
140
+ steps.append(row)
141
+ previous, previous_start = costs, start
142
+ if previous[m - previous_start] > bound:
143
+ return None
144
+ ops: list[Op] = []
145
+ i, j = n, m
146
+ while i or j:
147
+ step = steps[i][j - starts[i]]
148
+ if step == _PAIR:
149
+ before, after = reference[i - 1], hypothesis[j - 1]
150
+ ops.append(Op("equal" if before == after else "substitute", before, after))
151
+ i, j = i - 1, j - 1
152
+ elif step == _DELETE:
153
+ ops.append(Op("delete", reference[i - 1], ""))
154
+ i -= 1
155
+ else:
156
+ ops.append(Op("insert", "", hypothesis[j - 1]))
157
+ j -= 1
158
+ ops.reverse()
159
+ return ops
lectris/cli.py ADDED
@@ -0,0 +1,290 @@
1
+ """The ``lectris`` command: clean OCR output, evaluate it against a reference, list the rules,
2
+ run a registered experiment."""
3
+
4
+ import argparse
5
+ import sys
6
+ from collections.abc import Callable, Sequence
7
+ from importlib.metadata import version
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ from lectris import io, metrics, report
12
+ from lectris.errors import LectrisError
13
+ from lectris.io._common import decode
14
+ from lectris.io.detect import detect
15
+ from lectris.lexicon import Lexicon
16
+ from lectris.model import Document
17
+
18
+ if TYPE_CHECKING:
19
+ from lectris.decide import Policy
20
+ from lectris.models.pack import ModelPack
21
+ from lectris.pipeline import clean
22
+ from lectris.profiles import PROFILES
23
+
24
+ _REPORT_FORMATS = ("json", "markdown")
25
+
26
+
27
+ def _parser() -> argparse.ArgumentParser:
28
+ parser = argparse.ArgumentParser(
29
+ prog="lectris",
30
+ description="OCR output, read back into clean, ordered text, with every change recorded.",
31
+ )
32
+ parser.add_argument("--version", action="version", version=f"lectris {version('lectris')}")
33
+ commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
34
+
35
+ run = commands.add_parser("clean", help="clean an OCR file and write its text")
36
+ run.add_argument("input", help="hOCR, ALTO, TSV, JSON or text; - reads standard input")
37
+ run.add_argument("-f", "--format", choices=io.FORMATS, help="the input's format (detected)")
38
+ run.add_argument("-p", "--profile", choices=tuple(PROFILES), default="standard")
39
+ run.add_argument("-o", "--output", type=Path, help="write the text here (standard output)")
40
+ run.add_argument("-l", "--lexicon", type=Path, help="a word list: one word per line")
41
+ run.add_argument(
42
+ "--pack", type=Path, help="a model pack: evidence, the lexicon proposers, the risk policy"
43
+ )
44
+ run.add_argument(
45
+ "--policy",
46
+ choices=("parity", "risk", "none"),
47
+ help="how guesses are decided (risk with a calibrated pack, else parity)",
48
+ )
49
+ run.add_argument("-r", "--report", type=Path, help="write the report of every edit here")
50
+ run.add_argument(
51
+ "--report-format", choices=_REPORT_FORMATS, default="json", help="the report's format"
52
+ )
53
+ run.add_argument(
54
+ "-s", "--summary", action="store_true", help="print each rule's edit count to stderr"
55
+ )
56
+
57
+ score = commands.add_parser("eval", help="character and word error rates against a reference")
58
+ score.add_argument("reference", type=Path, help="the correct text")
59
+ score.add_argument("hypothesis", type=Path, help="the text to score")
60
+ score.add_argument(
61
+ "--normalize", action="store_true", help="NFC and collapsed whitespace on both sides"
62
+ )
63
+ score.add_argument("--ignore-case", action="store_true", help="compare case-insensitively")
64
+
65
+ commands.add_parser("rules", help="list the profiles and the rules each one runs")
66
+
67
+ fitting = commands.add_parser("fit", help="fit a model pack on paired data")
68
+ fitting.add_argument("--pairs", type=Path, required=True, help="a pairs manifest (fit split)")
69
+ fitting.add_argument("--engine", required=True, help="the engine's name, as documents name it")
70
+ fitting.add_argument("--model", required=True, help="the engine's model version")
71
+ fitting.add_argument(
72
+ "--text", type=Path, action="append", default=[], help="a folder of .txt files (repeatable)"
73
+ )
74
+ fitting.add_argument("--max-chars", type=int, default=3_000_000, help="text read at most")
75
+ fitting.add_argument("--order", type=int, default=5, help="the language model's order")
76
+ fitting.add_argument("-o", "--output", type=Path, required=True, help="the pack to write")
77
+
78
+ calibrating = commands.add_parser(
79
+ "calibrate", help="fit a pack's acceptance model and choose each profile's threshold"
80
+ )
81
+ calibrating.add_argument("--pack", type=Path, required=True, help="the pack lectris fit wrote")
82
+ calibrating.add_argument("--fit", type=Path, required=True, help="pairs to fit acceptance on")
83
+ calibrating.add_argument(
84
+ "--cal", type=Path, required=True, help="pairs to choose thresholds on"
85
+ )
86
+ calibrating.add_argument(
87
+ "--exclude", action="append", default=[], help="a feature to fit without (repeatable)"
88
+ )
89
+ calibrating.add_argument("-o", "--output", type=Path, required=True, help="the pack to write")
90
+
91
+ experiment = commands.add_parser("experiment", help="run a registered experiment")
92
+ actions = experiment.add_subparsers(dest="action", required=True, metavar="ACTION")
93
+ start = actions.add_parser("run", help="run an experiment's configuration into its report")
94
+ start.add_argument("config", type=Path, help="the experiment's configuration (JSON)")
95
+ start.add_argument(
96
+ "-o", "--output", type=Path, default=Path("reports"), help="reports go in OUTPUT/<id>/"
97
+ )
98
+ return parser
99
+
100
+
101
+ def _write(text: str) -> None:
102
+ """Write ``text`` to standard output as UTF-8, whatever the console's or the system's code
103
+ page (Windows writes a pipe or a file in its ANSI code page by default)."""
104
+ buffer = getattr(sys.stdout, "buffer", None)
105
+ if buffer is None:
106
+ sys.stdout.write(text)
107
+ return
108
+ sys.stdout.flush()
109
+ buffer.write(text.encode("utf-8"))
110
+ buffer.flush()
111
+
112
+
113
+ def _read_input(argument: str, format_name: str | None) -> Document | str:
114
+ """The input as a document, or as text when it is plain text.
115
+
116
+ Plain text goes to ``clean()`` as a string, so the rules see its spacing and line breaks as
117
+ they are written and record what they change (a document keeps only its words).
118
+ """
119
+ data = sys.stdin.buffer.read() if argument == "-" else Path(argument).read_bytes()
120
+ chosen = format_name or detect(data)
121
+ if chosen == "text":
122
+ return decode(data)
123
+ if argument == "-":
124
+ return io.parse(data, format=chosen)
125
+ return io.read(argument, format=chosen)
126
+
127
+
128
+ def _clean(arguments: argparse.Namespace) -> int:
129
+ document = _read_input(arguments.input, arguments.format)
130
+ lexicon = None if arguments.lexicon is None else Lexicon.from_file(arguments.lexicon)
131
+ model, policy = _pack_and_policy(arguments, document)
132
+ result = clean(document, profile=arguments.profile, lexicon=lexicon, policy=policy, pack=model)
133
+ text = result.text + "\n" if result.text else ""
134
+ if arguments.output is None:
135
+ _write(text)
136
+ else:
137
+ arguments.output.write_text(text, encoding="utf-8", newline="\n")
138
+ if arguments.report is not None:
139
+ rendered = (
140
+ report.to_json(result)
141
+ if arguments.report_format == "json"
142
+ else report.to_markdown(result)
143
+ )
144
+ arguments.report.write_text(rendered, encoding="utf-8", newline="\n")
145
+ if arguments.summary:
146
+ sys.stderr.write(report.summary(result))
147
+ return 0
148
+
149
+
150
+ def _pack_and_policy(
151
+ arguments: argparse.Namespace, document: Document | str
152
+ ) -> tuple["ModelPack | None", "Policy"]:
153
+ """The pack and the policy ``clean`` asked for, with a warning when a risk guarantee
154
+ cannot apply to the input."""
155
+ from lectris.decide import PARITY # noqa: PLC0415 - only packs need these
156
+ from lectris.eval.experiment import NONE # noqa: PLC0415
157
+
158
+ if arguments.pack is None:
159
+ if arguments.policy == "risk":
160
+ raise LectrisError("--policy risk needs --pack")
161
+ return None, NONE if arguments.policy == "none" else PARITY
162
+ from lectris.models import pack # noqa: PLC0415
163
+
164
+ model = pack.load(arguments.pack)
165
+ name = arguments.policy or ("risk" if model.acceptance is not None else "parity")
166
+ if name == "risk":
167
+ engine = document.engine if isinstance(document, Document) else None
168
+ if engine is None or (engine.name, engine.model) != (model.engine, model.model):
169
+ seen = "plain text" if engine is None else f"{engine.name} {engine.model}"
170
+ sys.stderr.write(
171
+ f"lectris: the pack was calibrated for {model.engine} {model.model}, the input "
172
+ f"is from {seen}: its harm guarantee does not apply to this input\n"
173
+ )
174
+ return model, model.policy(arguments.profile)
175
+ return model, NONE if name == "none" else PARITY
176
+
177
+
178
+ def _eval(arguments: argparse.Namespace) -> int:
179
+ # The same decoding as the readers: UTF-8, a byte order mark (UTF-8, 16 or 32) dropped.
180
+ reference = decode(arguments.reference.read_bytes())
181
+ hypothesis = decode(arguments.hypothesis.read_bytes())
182
+ options = {"normalize": arguments.normalize, "ignore_case": arguments.ignore_case}
183
+ for name, counts in (
184
+ ("CER", metrics.char_errors(reference, hypothesis, **options)),
185
+ ("WER", metrics.word_errors(reference, hypothesis, **options)),
186
+ ):
187
+ sys.stdout.write(
188
+ f"{name} {counts.rate:.4f} ({counts.errors} errors in {counts.reference_length}: "
189
+ f"{counts.substitutions} substituted, {counts.deletions} deleted, "
190
+ f"{counts.insertions} inserted)\n"
191
+ )
192
+ return 0
193
+
194
+
195
+ def _experiment(arguments: argparse.Namespace) -> int:
196
+ from lectris.eval import experiment # noqa: PLC0415 - only this command needs it
197
+
198
+ config = experiment.load_config(arguments.config)
199
+ as_json, as_markdown = experiment.write(experiment.run(config), arguments.output / config.id)
200
+ sys.stdout.write(f"{as_json}\n{as_markdown}\n")
201
+ return 0
202
+
203
+
204
+ def _fit(arguments: argparse.Namespace) -> int:
205
+ import hashlib # noqa: PLC0415 - only this command needs these
206
+
207
+ from lectris.eval.experiment import load_pairs # noqa: PLC0415
208
+ from lectris.eval.lines import matched_lines # noqa: PLC0415
209
+ from lectris.models import pack # noqa: PLC0415
210
+
211
+ pairs: list[tuple[str, str]] = []
212
+ truth: list[str] = []
213
+ for page in matched_lines(load_pairs(arguments.pairs)):
214
+ pairs.extend(page.pairs)
215
+ truth.extend(page.truth)
216
+ texts = [path for folder in arguments.text for path in sorted(folder.glob("*.txt"))]
217
+ manifest = arguments.pairs.read_bytes()
218
+ fitted = pack.fit(
219
+ pairs,
220
+ truth,
221
+ engine=arguments.engine,
222
+ model=arguments.model,
223
+ texts=texts,
224
+ max_chars=arguments.max_chars,
225
+ order=arguments.order,
226
+ sources=(
227
+ pack.Source(
228
+ arguments.pairs.name,
229
+ hashlib.sha256(manifest).hexdigest(),
230
+ "channel, language, lexicon",
231
+ ),
232
+ ),
233
+ )
234
+ pack.save(fitted, arguments.output)
235
+ sys.stdout.write(
236
+ f"{arguments.output}: {len(pairs)} line pairs, {len(fitted.lexicon)} words, "
237
+ f"{fitted.language.size} n-grams\n"
238
+ )
239
+ return 0
240
+
241
+
242
+ def _calibrate(arguments: argparse.Namespace) -> int:
243
+ from lectris.eval.calibrate import calibrate # noqa: PLC0415 - only this command needs it
244
+ from lectris.eval.experiment import load_pairs # noqa: PLC0415
245
+ from lectris.models import pack # noqa: PLC0415
246
+
247
+ calibrated = calibrate(
248
+ pack.load(arguments.pack),
249
+ load_pairs(arguments.fit),
250
+ load_pairs(arguments.cal),
251
+ exclude=arguments.exclude,
252
+ )
253
+ pack.save(calibrated, arguments.output)
254
+ budgets = calibrated.risk or {}
255
+ lines = [
256
+ f"{name}: alpha {b.alpha}, threshold {b.threshold}" for name, b in sorted(budgets.items())
257
+ ]
258
+ sys.stdout.write(f"{arguments.output}\n" + "\n".join(lines) + "\n")
259
+ return 0
260
+
261
+
262
+ def _rules() -> int:
263
+ for profile in PROFILES.values():
264
+ sys.stdout.write(f"{profile.name}: {profile.description}\n")
265
+ for step in profile.steps:
266
+ sys.stdout.write(f" {step.id}\n")
267
+ sys.stdout.write("\n")
268
+ return 0
269
+
270
+
271
+ def main(argv: Sequence[str] | None = None) -> int:
272
+ """Run the command; returns the exit status (0 done, 1 an input it cannot read, 2 usage)."""
273
+ arguments = _parser().parse_args(argv)
274
+ commands: dict[str, Callable[[argparse.Namespace], int]] = {
275
+ "clean": _clean,
276
+ "eval": _eval,
277
+ "experiment": _experiment,
278
+ "fit": _fit,
279
+ "calibrate": _calibrate,
280
+ "rules": lambda _: _rules(),
281
+ }
282
+ try:
283
+ return commands[arguments.command](arguments)
284
+ except (LectrisError, OSError, ValueError) as error:
285
+ sys.stderr.write(f"lectris: {error}\n")
286
+ return 1
287
+
288
+
289
+ if __name__ == "__main__":
290
+ raise SystemExit(main())
lectris/confidence.py ADDED
@@ -0,0 +1,154 @@
1
+ """Confidence: word confidences aggregated to lines, blocks and pages, and low-confidence spans.
2
+
3
+ A confidence is a float in ``[0, 1]``, or ``None`` when the OCR engine gave none. Unknown
4
+ confidences are skipped, never counted as zero, and a value aggregated from no known confidence
5
+ is ``None``.
6
+ """
7
+
8
+ import math
9
+ from collections.abc import Iterable
10
+ from dataclasses import dataclass
11
+ from typing import Final, Literal
12
+
13
+ from lectris.model import Block, Line, Page
14
+
15
+ type Method = Literal["weighted", "mean", "min", "geometric"]
16
+
17
+ METHODS: Final[tuple[Method, ...]] = ("weighted", "mean", "min", "geometric")
18
+
19
+
20
+ def aggregate(
21
+ values: Iterable[tuple[float | None, int]], *, method: Method = "weighted"
22
+ ) -> float | None:
23
+ """One confidence from ``(confidence, weight)`` pairs; the weight is usually a length.
24
+
25
+ Pairs whose confidence is ``None`` are skipped; with no known confidence the result is
26
+ ``None``. The methods:
27
+
28
+ - ``"weighted"``: the weighted mean.
29
+ - ``"mean"``: the plain mean; weights are ignored.
30
+ - ``"min"``: the lowest confidence; weights are ignored.
31
+ - ``"geometric"``: the weighted geometric mean, ``exp(sum(w * ln c) / sum(w))``. It is 0 if
32
+ a confidence with a positive weight is 0, and it is pulled down by a low value more than
33
+ the weighted mean is.
34
+
35
+ For ``"weighted"`` and ``"geometric"``, pairs with weight 0 do not count, unless every known
36
+ confidence has weight 0: then each counts once. The result always lies between the lowest
37
+ and the highest known confidence.
38
+
39
+ Raises ``ValueError`` for an unknown method, a negative weight, or a confidence outside
40
+ ``[0, 1]``.
41
+ """
42
+ if method not in METHODS:
43
+ raise ValueError(f"method is one of {', '.join(METHODS)}, not {method!r}")
44
+ known: list[tuple[float, int]] = []
45
+ for confidence, weight in values:
46
+ if weight < 0:
47
+ raise ValueError(f"a weight is 0 or more, not {weight!r}")
48
+ if confidence is None:
49
+ continue
50
+ if not 0.0 <= confidence <= 1.0:
51
+ raise ValueError(f"a confidence is between 0 and 1, not {confidence!r}")
52
+ known.append((confidence, weight))
53
+ if not known:
54
+ return None
55
+ if method == "min":
56
+ return min(confidence for confidence, _ in known)
57
+ if method == "mean":
58
+ return _bounded(math.fsum(c for c, _ in known) / len(known), [c for c, _ in known])
59
+ weighted = [(c, w) for c, w in known if w > 0] or [(c, 1) for c, _ in known]
60
+ total = sum(w for _, w in weighted)
61
+ confidences = [c for c, _ in weighted]
62
+ if method == "weighted":
63
+ return _bounded(math.fsum(c * w for c, w in weighted) / total, confidences)
64
+ if min(confidences) == 0.0:
65
+ return 0.0
66
+ mean = math.exp(math.fsum(w * math.log(c) for c, w in weighted) / total)
67
+ return _bounded(mean, confidences)
68
+
69
+
70
+ def _bounded(mean: float, confidences: list[float]) -> float:
71
+ # A mean lies between the extremes; this only removes floating-point rounding.
72
+ return min(max(mean, min(confidences)), max(confidences))
73
+
74
+
75
+ def line_confidence(line: Line, *, method: Method = "weighted") -> float | None:
76
+ """The line's own confidence if it has one, else its words' aggregated by ``method``.
77
+
78
+ Each word is weighted by its length in characters.
79
+ """
80
+ if line.confidence is not None:
81
+ return line.confidence
82
+ return aggregate(((word.confidence, len(word.text)) for word in line.words), method=method)
83
+
84
+
85
+ def block_confidence(block: Block, *, method: Method = "weighted") -> float | None:
86
+ """The block's lines' confidences (``line_confidence``) aggregated by ``method``.
87
+
88
+ Each line is weighted by the length of its text, so its spaces count with its letters.
89
+ """
90
+ return _lines_confidence(block.lines, method)
91
+
92
+
93
+ def page_confidence(page: Page, *, method: Method = "weighted") -> float | None:
94
+ """Every line's confidence (``line_confidence``) on the page, aggregated by ``method``.
95
+
96
+ Lines are weighted by the length of their text, as in ``block_confidence``; blocks are not
97
+ weighted separately.
98
+ """
99
+ return _lines_confidence(page.lines, method)
100
+
101
+
102
+ def _lines_confidence(lines: Iterable[Line], method: Method) -> float | None:
103
+ return aggregate(
104
+ ((line_confidence(line, method=method), len(line.text)) for line in lines), method=method
105
+ )
106
+
107
+
108
+ @dataclass(frozen=True, slots=True)
109
+ class Span:
110
+ """A stretch of a block's text whose words the OCR engine was unsure of.
111
+
112
+ ``text == block.text[start:end]``; ``confidence`` is the lowest of its words'.
113
+ """
114
+
115
+ start: int
116
+ end: int
117
+ text: str
118
+ confidence: float
119
+
120
+
121
+ def low_confidence_spans(block: Block, *, threshold: float = 0.6) -> tuple[Span, ...]:
122
+ """The spans of ``block.text`` whose words have a confidence below ``threshold``.
123
+
124
+ Offsets are in ``block.text``: lines joined by ``"\\n"``, words by one space. A word without
125
+ a confidence takes its line's; when neither has one, the word is never low. Low words next
126
+ to each other on a line make one span, which covers the spaces between them; a span never
127
+ crosses a line break. Words with empty text are skipped: they neither start nor end a span.
128
+
129
+ Raises ``ValueError`` if ``threshold`` is not in ``[0, 1]``.
130
+ """
131
+ if not 0.0 <= threshold <= 1.0:
132
+ raise ValueError(f"a threshold is between 0 and 1, not {threshold!r}")
133
+ text = block.text
134
+ spans: list[Span] = []
135
+ line_start = 0
136
+ for line in block.lines:
137
+ run: tuple[int, int, float] | None = None
138
+ position = line_start
139
+ for word in line.words:
140
+ end = position + len(word.text)
141
+ confidence = line.confidence if word.confidence is None else word.confidence
142
+ if word.text and confidence is not None and confidence < threshold:
143
+ if run is None:
144
+ run = (position, end, confidence)
145
+ else:
146
+ run = (run[0], end, min(run[2], confidence))
147
+ elif word.text and run is not None:
148
+ spans.append(Span(run[0], run[1], text[run[0] : run[1]], run[2]))
149
+ run = None
150
+ position = end + 1
151
+ if run is not None:
152
+ spans.append(Span(run[0], run[1], text[run[0] : run[1]], run[2]))
153
+ line_start += len(line.text) + 1
154
+ return tuple(spans)