"""Transcript cleaning (training labels keep case + punctuation) and normalized WER (for filtering and eval).""" import re import unicodedata _MAP = str.maketrans({"‘": "'", "’": "'", "`": "'", "“": "", "”": "", '"': "", "–": "-", "—": "-", "…": "..."}) _OK = re.compile(r"[A-Za-z0-9 .,?!'\-:;%$&]+") def clean_text(s): """Label form: NFKC, unified quotes/dashes, single spaces. None if anything outside the output alphabet remains (dropping the clip beats silently corrupting its label).""" s = " ".join(unicodedata.normalize("NFKC", s or "").translate(_MAP).split()) return s if s and _OK.fullmatch(s) else None def norm_words(s): return re.sub(r"[^a-z0-9' ]", " ", s.lower()).split() def edits(a, b): d = list(range(len(b) + 1)) for i, x in enumerate(a, 1): prev, d[0] = d[0], i for j, y in enumerate(b, 1): prev, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, prev + (x != y)) return d[-1] def wer(ref, hyp): r = norm_words(ref) return edits(r, norm_words(hyp)) / max(1, len(r)) def ops(a, b): """(insertions, deletions, substitutions) turning reference words a into hypothesis words b (one min-cost alignment).""" n, m = len(a), len(b) d = [[0] * (m + 1) for _ in range(n + 1)] for i in range(n + 1): d[i][0] = i for j in range(m + 1): d[0][j] = j for i in range(1, n + 1): for j in range(1, m + 1): d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] != b[j - 1])) ins = dele = sub = 0 i, j = n, m while i or j: if i and j and d[i][j] == d[i - 1][j - 1] + (a[i - 1] != b[j - 1]): sub += a[i - 1] != b[j - 1] i, j = i - 1, j - 1 elif i and d[i][j] == d[i - 1][j] + 1: dele += 1 i -= 1 else: ins += 1 j -= 1 return ins, dele, sub def repeats(w, n=3): """Words wasted on stutter loops: a word run of length >= n counts (run - 1); a repeated bigram (x y x y) counts 2.""" c, i = 0, 0 while i < len(w): j = i while j + 1 < len(w) and w[j + 1] == w[i]: j += 1 if j - i + 1 >= n: c += j - i i = j + 1 c += sum(2 for i in range(len(w) - 3) if w[i] != w[i + 1] and w[i:i + 2] == w[i + 2:i + 4]) return c GHOST = {"thank you", "you", "thanks for watching", "bye", "thank you very much", "thank you so much"} # Whisper's silence outputs def cap_sentences(rows, cap=4, seed=0): """Keep at most `cap` clips per normalized transcript (1 for the ghost phrases), chosen at random: a few sentences repeated thousands of times would be memorized instead of learned.""" import random from collections import Counter rows = list(rows) random.Random(seed).shuffle(rows) seen, out = Counter(), [] for r in rows: k = " ".join(norm_words(r["text"])) if seen[k] < (1 if k in GHOST else cap): seen[k] += 1 out.append(r) return out