"""Educational, local-only WER example. No model, upload or external service."""
import re
import unicodedata

TABLE = str.maketrans("كي٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹", "کی01234567890123456789")

def normalize(text):
    text = unicodedata.normalize("NFC", text).translate(TABLE)
    return re.sub(r"\s+", " ", text).strip()

def distance(reference, hypothesis):
    a, b = reference.split(), hypothesis.split()
    if not a:
        raise ValueError("Reference must contain words")
    previous = list(range(len(b) + 1))
    for i, word_a in enumerate(a, 1):
        current = [i]
        for j, word_b in enumerate(b, 1):
            current.append(min(current[-1] + 1, previous[j] + 1,
                               previous[j - 1] + (word_a != word_b)))
        previous = current
    return previous[-1], len(a)

def wer(reference, hypothesis):
    errors, words = distance(reference, hypothesis)
    return errors / words

if __name__ == "__main__":
    reference = "من به بانک می روم"
    hypothesis = "من به بانك مي روم"
    assert wer(reference, hypothesis) == 0.4
    assert wer(normalize(reference), normalize(hypothesis)) == 0
    assert normalize("۱۲") != normalize("۱۳")
    print({"raw_wer": wer(reference, hypothesis),
           "normalized_wer": wer(normalize(reference), normalize(hypothesis)),
           "numeric_difference_preserved": True})
