"""Deterministic word alignment. Text differences are not pronunciation diagnoses.""" import re import unicodedata MAX_WORDS = 500 def tokenize(text, language): """Ignore case/punctuation. Greek folds final sigma, preserving accents/diaeresis.""" if language not in {"en", "el"}: raise ValueError("Choose English or Greek.") text = unicodedata.normalize("NFC", text).replace("’", "'").replace("‘", "'") display = re.findall(r"[^\W_]+(?:'[^\W_]+)*", text, flags=re.UNICODE) # Casefold handles Greek σ/ς, but accents are deliberately not stripped. return [(word, unicodedata.normalize("NFC", word.casefold())) for word in display] def align(reference, transcript, language): """Use edit distance to identify possible replacements, omissions, and additions.""" expected = tokenize(reference, language) heard = tokenize(transcript, language) if not expected or not heard: raise ValueError("Enter some words before comparing the texts.") if max(len(expected), len(heard)) > MAX_WORDS: raise ValueError("Please use no more than 500 words.") n, m = len(expected), len(heard) costs = [[0] * (m + 1) for _ in range(n + 1)] for i in range(n + 1): costs[i][0] = i for j in range(m + 1): costs[0][j] = j for i in range(1, n + 1): for j in range(1, m + 1): costs[i][j] = min(costs[i-1][j-1] + (expected[i-1][1] != heard[j-1][1]), costs[i-1][j] + 1, costs[i][j-1] + 1) rows = [] i, j = n, m while i or j: if i and j and costs[i][j] == costs[i-1][j-1] + (expected[i-1][1] != heard[j-1][1]): kind = "match" if expected[i-1][1] == heard[j-1][1] else "changed" rows.append({"kind": kind, "expected": expected[i-1][0], "heard": heard[j-1][0], "reference_index": i-1, "transcript_index": j-1}) i, j = i-1, j-1 elif i and costs[i][j] == costs[i-1][j] + 1: rows.append({"kind": "skipped", "expected": expected[i-1][0], "heard": "", "reference_index": i-1, "transcript_index": None}) i -= 1 else: rows.append({"kind": "added", "expected": "", "heard": heard[j-1][0], "reference_index": None, "transcript_index": j-1}) j -= 1 rows.reverse() differences = [{**row, "id": str(index)} for index, row in enumerate(rows) if row["kind"] != "match"] counts = {kind: sum(row["kind"] == kind for row in differences) for kind in ("changed", "skipped", "added")} return { "language": language, "reference_words": n, "transcript_words": m, "differences": differences, "counts": counts, "word_difference_rate": round(costs[n][m] / n, 4), "notice": "These are possible text differences. Speech recognition can be wrong. Edit the transcript or dismiss a suggestion. This is not a pronunciation score.", "normalization": "Case and punctuation are ignored. Apostrophes are preserved." if language == "en" else "Case, punctuation, and final sigma variants are ignored. Accents and diaeresis are preserved; text differences do not establish pronunciation errors.", }