"""Deletion-only cleanup targets built from Phonon's own words. DisfluencySpeech gives, per clip, the verbatim text (transcript_a) and the same text with fillers, discourse markers, edit terms and restarts removed (transcript_c). Phonon's output (hyp) differs from both where it misheard. Training on transcript_c directly would teach the cleanup model to write words it never saw (Phonon heard "peppers", the target says "papyrus"). So the target is hyp with only the disfluent words removed: 1. a -> c: c is (almost) a subsequence of a; an LCS alignment marks every word of a as kept or removed. 2. hyp -> a: a Levenshtein alignment maps each hyp word to the a word it stands for (match or substitution). 3. A hyp word is dropped when its a word was removed, or when it is an unaligned filler (uh, um, ...). 4. The kept words are re-joined with Phonon's own punctuation, a sentence end on a dropped word moves to the previous kept word, and sentence starts are capitalised. """ from __future__ import annotations import re PROTECT = {"actually", "anyway", "anyways", "now", "however", "basically", "honestly"} FILLERS = {"uh", "um", "er", "erm", "ah", "eh", "hmm", "mm", "uhm", "huh", "mhm", "uh-huh", "hm"} _SENT_END = re.compile(r"[.?!]+$") _EDGE = re.compile(r"^[^\w']+|[^\w']+$") def norm_word(w: str) -> str: return _EDGE.sub("", w.lower()).replace("’", "'") def words(text: str) -> list[str]: """Whitespace tokens that contain at least one letter/digit (bare '-' or '--' tokens are dropped).""" return [w for w in (text or "").split() if norm_word(w)] def lcs_keep(a: list[str], c: list[str]) -> list[bool]: """keep[i] is True when a[i] is part of a longest common subsequence with c (normalised words).""" na, nc = [norm_word(w) for w in a], [norm_word(w) for w in c] n, m = len(na), len(nc) dp = [[0] * (m + 1) for _ in range(n + 1)] for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): dp[i][j] = dp[i + 1][j + 1] + 1 if na[i] == nc[j] else max(dp[i + 1][j], dp[i][j + 1]) keep, i, j = [False] * n, 0, 0 while i < n and j < m: if na[i] == nc[j]: keep[i] = True i += 1 j += 1 elif dp[i + 1][j] >= dp[i][j + 1]: i += 1 else: j += 1 return keep def _sim(x: str, y: str) -> bool: """Loose match for substitutions that are clearly the same word (partial words, plural, apostrophes).""" if x == y: return True if len(x) >= 3 and len(y) >= 3 and (x.startswith(y) or y.startswith(x)): return True return False def align(h: list[str], a: list[str]) -> list[int | None]: """For every hyp word, the index of the a word it aligns to (match/substitution), or None (insertion).""" nh, na = [norm_word(w) for w in h], [norm_word(w) for w in a] n, m = len(nh), len(na) INF = 10 ** 9 cost = [[INF] * (m + 1) for _ in range(n + 1)] back = [[None] * (m + 1) for _ in range(n + 1)] cost[0][0] = 0 for i in range(n + 1): for j in range(m + 1): c = cost[i][j] if c == INF: continue if i < n and j < m: s = c + (0 if nh[i] == na[j] else (0.5 if _sim(nh[i], na[j]) else 1.0)) if s < cost[i + 1][j + 1]: cost[i + 1][j + 1], back[i + 1][j + 1] = s, (i, j, "sub") if i < n and c + 1 < cost[i + 1][j]: cost[i + 1][j], back[i + 1][j] = c + 1, (i, j, "ins") if j < m and c + 1 < cost[i][j + 1]: cost[i][j + 1], back[i][j + 1] = c + 1, (i, j, "del") out: list[int | None] = [None] * n i, j = n, m while (i, j) != (0, 0): pi, pj, op = back[i][j] if op == "sub": out[pi] = pj i, j = pi, pj return out def join_kept(tokens: list[str], keep: list[bool]) -> str: """Re-join kept tokens. A sentence end on a dropped token moves to the previous kept token; a comma left at a sentence end becomes that end; sentence starts are capitalised (never lower-cased).""" out: list[str] = [] first: list[bool] = [] # out[i] starts its sentence pending_end = None dropped_comma = False # the dropped run just before this point ended with a comma for tok, k in zip(tokens, keep): if not k: m = _SENT_END.search(tok) if m and out: pending_end = m.group(0) dropped_comma = tok.endswith(",") continue if pending_end and out: prev = out[-1].rstrip(",;:") if not _SENT_END.search(prev): prev += pending_end out[-1] = prev elif dropped_comma and out and out[-1].endswith(",") and not first[-1]: # "could, you know, get" -> "could get"; a sentence-initial "Yes, uh, I" keeps "Yes," out[-1] = out[-1][:-1] pending_end = None dropped_comma = False first.append(not out or bool(_SENT_END.search(out[-1]))) out.append(tok) if out: if pending_end: prev = out[-1].rstrip(",;:") out[-1] = prev if _SENT_END.search(prev) else prev + pending_end out[-1] = re.sub(r"[,;:]+$", "", out[-1]) if not _SENT_END.search(out[-1]) else out[-1] if tokens and _SENT_END.search(tokens[-1]) and not _SENT_END.search(out[-1]): out[-1] += _SENT_END.search(tokens[-1]).group(0) text = " ".join(out) text = re.sub(r"^[,;:\s]+", "", text) return capitalise_sentences(text) def capitalise_sentences(text: str) -> str: def up(m): return m.group(1) + m.group(2).upper() text = re.sub(r"^(\W*)(\w)", up, text) return re.sub(r"([.?!]\s+\W*)(\w)", up, text) def deletion_target(hyp: str, a: str, c: str) -> tuple[str, dict]: """Phonon hyp with the words DisfluencySpeech removes (a -> c) removed. Returns (target, stats).""" h, wa, wc = hyp.split(), words(a), words(c) keep_a = lcs_keep(wa, wc) hw_idx = [i for i, t in enumerate(h) if norm_word(t)] # punctuation-only hyp tokens are dropped hw = [h[i] for i in hw_idx] amap = align(hw, wa) keep = [False] * len(h) n_sub = n_ins = 0 for k, i in enumerate(hw_idx): j = amap[k] if j is None: n_ins += 1 keep[i] = norm_word(h[i]) not in FILLERS else: same = norm_word(h[i]) == norm_word(wa[j]) if not same: n_sub += 1 # a substituted word is only dropped when it is clearly the removed word (or a filler): when unsure, keep keep[i] = keep_a[j] or not (same or _sim(norm_word(h[i]), norm_word(wa[j])) or norm_word(h[i]) in FILLERS) # discourse words that carry meaning stay, unless they are a repeat of the next word ("now now") if not keep[i] and norm_word(h[i]) in PROTECT and not ( i + 1 < len(h) and norm_word(h[i + 1]) == norm_word(h[i])): keep[i] = True target = join_kept(h, keep) stats = {"hyp_words": len(hw), "a_words": len(wa), "a_removed": keep_a.count(False), "c_coverage": sum(keep_a) / max(1, len(wc)), "sub": n_sub, "ins": n_ins, "dropped": sum(1 for i in hw_idx if not keep[i])} return target, stats