"""Character error rate (CER) of OCR text. MIT license, Brasspage, Nov 2026.

Run: python cer.py truth/ ocr/          (the same file names in both folders)
     python cer.py truth.txt ocr.txt

CER = (swaps + deletes + inserts) / characters in the truth, summed over all files.
Both texts get NFKC and one space between words first, so line breaks and spaces at the ends do not count.
An empty truth file is skipped, and a missing OCR file counts as empty (every character lost).
pip install rapidfuzz makes it fast. Without it, plain Python gives the same numbers, slower.
"""

import sys
import unicodedata
from pathlib import Path

try:
    from rapidfuzz.distance.Levenshtein import distance
except ImportError:

    def distance(a, b):
        prev = list(range(len(b) + 1))
        for i, x in enumerate(a, 1):
            cur = [i]
            for j, y in enumerate(b, 1):
                cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y)))
            prev = cur
        return prev[-1]


def clean(text):
    return " ".join(unicodedata.normalize("NFKC", text).split())


def pairs(truth, ocr):
    if truth.is_file():
        return [(truth, ocr)]
    return [(t, ocr / t.name) for t in sorted(truth.glob("*.txt"))]


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit(__doc__)
    edits = chars = 0
    for truth, ocr in pairs(Path(sys.argv[1]), Path(sys.argv[2])):
        ref = clean(truth.read_text(encoding="utf-8"))
        hyp = clean(ocr.read_text(encoding="utf-8")) if ocr.exists() else ""
        if not ref:
            print(f"{truth.name}: skipped, the truth is empty")
            continue
        n = distance(ref, hyp)
        print(f"{truth.name}: {n / len(ref):.2%}")
        edits, chars = edits + n, chars + len(ref)
    if chars:
        print(f"CER {edits / chars:.2%} ({edits} edits, {chars} characters)")
