"""Score OCR text against a truth file: true words found, and extra words. MIT license, Brasspage, Nov 2026.

Run: python3 score.py <truth.txt> <ocr.txt>
     python3 score.py <truth.txt> <searchable.pdf>   (pip install pypdfium2, or pdftotext from poppler)

A word counts when the OCR text has it anywhere, as often as the truth has it (word order is not scored).
Case, quote style and punctuation at the ends of a word are ignored. A word split by a hyphen at a line end
counts as missed. Extra words are OCR words that are not in the truth: noise, pen marks read as letters, or
misread words.
"""

import subprocess
import sys
import unicodedata
from collections import Counter

FIX = {"‘": "'", "’": "'", "“": '"', "”": '"', "—": "-", "–": "-", "­": ""}
ENDS = ".,;:!?\"'()[]{}*_-"


def tokens(text):
    text = unicodedata.normalize("NFKC", text)
    for a, b in FIX.items():
        text = text.replace(a, b)
    return [w for w in (x.strip(ENDS).lower() for x in text.split()) if any(c.isalnum() for c in w)]


def score(truth, got):
    """(true words found, true words, extra words)"""
    a, b = Counter(tokens(truth)), Counter(tokens(got))
    return sum((a & b).values()), sum(a.values()), sum((b - a).values())


def read(path):
    if not path.lower().endswith(".pdf"):
        with open(path, encoding="utf-8") as f:
            return f.read()
    try:  # pdfium is the PDF engine of Chrome, and it reads the slanted text layer of a tilted page right
        import pypdfium2 as pdfium
    except ImportError:
        print("pypdfium2 is not installed, so pdftotext reads the PDF. It can garble a tilted page.", file=sys.stderr)
        return subprocess.run(["pdftotext", path, "-"], capture_output=True, text=True, check=True).stdout
    return "\f".join(page.get_textpage().get_text_range() for page in pdfium.PdfDocument(path))


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit(__doc__)
    found, of, extra = score(read(sys.argv[1]), read(sys.argv[2]))
    print(f"{found} of {of} true words ({100 * found / of:.1f}%), {extra} extra words")
