Skip to main content

LECTRIS

OCR output, read back into clean, ordered text: every change it makes is recorded and explained.

CI Python 3.12+ License: Apache-2.0 Checked by Repro

OCR engines return words, lines and boxes, and the text they recover still needs work: columns read in the wrong order, words split across lines, fi ligatures, O read for 0, spaces in the middle of numbers, specks read as lines of punctuation. LECTRIS reads the engine's output (hOCR, ALTO, Tesseract TSV, JSON or plain text), puts the lines in reading order, groups them into paragraphs, and repairs the text with small, conservative rules. Each rule records each edit it makes, so you can audit a result, count what changed, or switch a rule off.

It does not run OCR, process images or use language models, and it has no dependencies outside the standard library.

Status: v0.1 released; v2 in planning. v2 turns the rules into proposers whose candidates are scored from evidence (including the OCR engine's own uncertainty) and accepted under a threshold that bounds the harm done to correct text. It is designed alongside the GLYPHARIS OCR engine. See Research.

Example

from lectris import clean

ocr = (
    "The first survey of the river  recorded 1O5 species , most of them\n"
    "in the upper reaches. Later surveys con-\n"
    "firmed the count.\n"
    "~~~ ,,, ' ' |||\n"
    "Water quality fell by 3 .5 percent in ten years."
)
result = clean(ocr)
print(result.text)
The first survey of the river recorded 105 species, most of them in the upper reaches. Later surveys confirmed the count. Water quality fell by 3.5 percent in ten years.

Every change is in the result: ten edits here, each with its rule, its place and what it replaced.

for change in result.changes():
    print(change.edit.rule, repr(change.edit.before), "->", repr(change.edit.after))
unicode.ligatures 'fi' -> 'fi'
whitespace.collapse '  ' -> ' '
noise.drop_lines "~~~ ,,, ' ' |||\n" -> ''
hyphenation.join '-\nfirmed ' -> 'firmed\n'
unwrap.join_lines '\n' -> ' '
unwrap.join_lines '\n' -> ' '
unwrap.join_lines '\n' -> ' '
confusables.in_numbers '1O5' -> '105'
numbers.separators ' .' -> '.'
punctuation.spacing ' ' -> ''

Install

pip install git+https://github.com/DuhItzAniket/Lectris

LECTRIS needs Python 3.12 or newer.

The command line

lectris clean page.hocr                     # the cleaned text, on standard output
lectris clean page.xml -o page.txt -r report.json --summary
lectris clean scan.tsv --profile conservative
lectris clean results/page.json             # what glypharis-ocr wrote
lectris eval reference.txt page.txt         # character and word error rates
lectris rules                               # every profile and its rules
lectris experiment run configs/LX-MAIN-001.json  # a registered experiment's report
lectris fit --pairs fit.json --engine glypharis --model glypharis_v1 --text books/ -o pack.lectris.json.gz
lectris calibrate --pack pack.lectris.json.gz --fit fit.json --cal cal.json -o calibrated.lectris.json.gz

The input's format is detected from its content; --format names it. --lexicon words.txt (one word per line, an optional count after it) makes de-hyphenation and the confusion rules more precise. No dictionary is bundled.

With a model pack: risk-controlled corrections

A model pack holds what LECTRIS learns about one OCR engine: what it confuses, a character language model, word counts, and an acceptance model calibrated so that each profile keeps the harm it does to correct text within a budget, with a stated confidence.

lectris fit --pairs fit.json --engine glypharis --model glypharis_v1 --text books/ -o pack.lectris.json.gz
lectris calibrate --pack pack.lectris.json.gz --fit fit.json --cal cal.json -o calibrated.lectris.json.gz
lectris clean page.json --pack calibrated.lectris.json.gz -r report.md --report-format markdown

With a calibrated pack, every guess (the v0.1 rules' and those of two more proposers: words one edit from a lexicon word, missing and spurious spaces) is accepted only if its probability of being right reaches the profile's threshold. The report states the guarantee, for instance harm rate at most 0.02 with confidence 0.9, and whether it applies: it holds only for input from the engine and model the pack was calibrated for, and the command warns when it does not. It also lists, for review, the corrections it declined that were still likely.

from lectris import clean, io
from lectris.models import pack

model = pack.load("calibrated.lectris.json.gz")
result = clean(io.read("page.json"), pack=model, policy=model.policy("standard"))
result.guarantee, result.guarantee_applies  # the promise, and whether it holds here
result.flags()  # declined but likely corrections

Without a pack, LECTRIS behaves exactly as v0.1. The pairs come from running the engine on pages with ground truth; scripts/build_hiertext_pairs.py builds them for HierText.

Profiles

Profile What it changes
conservative The safest repairs: line breaks, invisible characters, compatibility forms, ligatures, Unicode composition, extra spaces, and words hyphenated across lines. Line breaks are kept.
standard (default) The conservative rules, plus noise lines dropped, paragraphs unwrapped onto one line, letters read inside numbers, spaces inside numbers and before punctuation, and dash variants.
aggressive The standard rules, plus digits read inside words, straight quotes and three-dot ellipses. Recall over precision: read its report before trusting it.

Every profile is idempotent: cleaning its own output changes nothing. The rules, their evidence and what each one deliberately leaves alone are listed in docs/rules.md.

Reading OCR output

from pathlib import Path

from lectris import clean, io, report

document = io.read("page.hocr")  # or .xml (ALTO), .tsv, .json (incl. GLYPHARIS), .txt
result = clean(document, profile="standard")
print(report.summary(result))  # edits per rule
Path("report.json").write_text(report.to_json(result), encoding="utf-8")
Format What is read
hOCR pages, areas and paragraphs, lines, words, with bbox and x_wconf
ALTO XML 2–4 text blocks, lines and strings with their positions, WC confidences and HYP hyphens
Tesseract TSV pages, paragraphs, lines and words with boxes and confidences
JSON LECTRIS's own form, or a flat list of lines with text, bbox and confidence
GLYPHARIS JSON the engine and model versions, the page size, and each line's text, box, polygon, calibrated confidence and detection score
Plain text pages separated by form feeds, paragraphs by blank lines

When the lines have boxes, the layout steps put them in reading order (columns read whole, a title before the columns under it) and group them into paragraphs from their spacing, indents and sentence ends. Every threshold is relative to the size of the text, so a scan at any resolution gives the same result.

Measuring OCR

from lectris import metrics

metrics.cer("kitten sat", "sitting sat")  # 0.3: 3 errors in 10 characters
metrics.word_errors("kitten sat", "sitting sat")  # substitutions, deletions, insertions
metrics.confusions(reference, ocr_text)  # which characters the engine mixes up

Design

  • No silent edits. A rule returns its new text and the edits that produced it; the pipeline keeps them all.
  • Precision before recall. A rule changes text only where local evidence is strong, and each rule's tests list the correct text it must leave alone.
  • Pure and deterministic. The same input always gives the same output.

The architecture is in docs/ARCHITECTURE.md.

Scope: Latin-script text, horizontal lines (scans skewed by a few degrees are corrected), left-to-right reading order. Tables, and tables of contents whose page numbers stand far to the right, are read column by column.

Research

LECTRIS v2 is also a research project: auditable, risk-controlled post-OCR correction with engine uncertainty. Every experiment is registered before it runs, and every reported number traces back to a generated report.

Document What's in it
Architecture v0.1 as built and the v2 target: propose, evidence, decide
Implementation plan research questions, phases, tasks and exit criteria
Roadmap milestones, dependencies, where LECTRIS meets GLYPHARIS
Phase status what is done, with the numbers behind it
Experiment protocol splits, metrics (harm included), statistics, risk-control validity
Decisions architecture decision records
Risk register known risks and mitigations
Datasets provenance, licences and roles
Research log hypotheses, experiment registry, related work, paper outline

Development

uv sync
uv run pytest
uv run ruff check && uv run mypy

Every pull request is checked by Repro, which runs the tests on both sides of the change, compares what the changed functions actually return, and posts a Reproduction Card on the pull request. See CONTRIBUTING.md.

License

Apache License 2.0.

Metadata

Release files for lectris 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lectris 0.3.0
File Size Uploaded Provenance Actions
lectris-0.3.0.tar.gz 126.4 kB With provenance Details for lectris-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lectris 0.3.0
File Interpreter ABI Platform Actions
lectris-0.3.0-py3-none-any.whl Python 3 none any Details for lectris-0.3.0-py3-none-any.whl

Total release size: 279.2 kB

Release files / lectris-0.3.0.tar.gz

Download URL lectris-0.3.0.tar.gz
Size 126.4 kB
Tags Source
SHA-256 checksum
How to use checksums
4dea1cf984ec3dfc81a737724f62236b9ef4dfbe6d480d661085ca996b90db9c
BLAKE2b-256 checksum
How to use checksums
41f0b5f2db3282dec888f0faa8594baa31b04a25b4f285975435eaf3f5f7e32f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Release files / lectris-0.3.0-py3-none-any.whl

Download URL lectris-0.3.0-py3-none-any.whl
Size 152.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eb3a7f02faca549ec84d5e19aae788036091f94b9f7021e801e9856f19ead6ef
BLAKE2b-256 checksum
How to use checksums
9f8d1df315245339a1816e8fb8ba3bcf8d4d94911369ccb64bff0839afc7adf5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Security for lectris 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for lectris-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page