"""Check every deletion the cleanup model made, and undo the ones that are not disfluencies. Cleanup is deletion-only by design. The model output is aligned to the input (normalised words); each run of deleted input words must be one of: - fillers / discourse markers ("uh", "you know", "I mean", "well", "oh", ...), - a repeat or restart of what follows ("I I think", "we should, we need to", "an antipathy, an antipathy"), - a self-correction ("Tuesday, no, sorry, Wednesday": the run holds a correction word), otherwise those words are restored. If the output adds or changes words (not a deletion), the raw input is used. When nothing is restored the model's own punctuation/casing is kept; otherwise the text is rebuilt from the input tokens with the kept/restored words. Unambiguous fillers (uh, um, er, ah, ...) are always removed. Standard library only: the same code is inlined in both runners (tests/test_runners.py checks they match). """ from __future__ import annotations import re _EDGE = re.compile(r"^[^\w']+|[^\w']+$") _SENT_END = re.compile(r"[.?!]+$") HARD_FILLERS = {"uh", "um", "er", "erm", "ah", "eh", "hmm", "mm", "uhm", "mhm"} SOFT = {"uh", "um", "er", "erm", "ah", "eh", "hmm", "mm", "uhm", "mhm"} # "Oh, Bartley" keeps its "Oh" # fillers only when written with a comma ("like,", "Well,") or opening a sentence ("So I went"): # "He well knew", "so angry", "like music" keep them COMMA_SOFT = {"like", "just", "basically", "see", "anyway", "now", "well", "so", "okay", "ok", "yeah"} PHRASES = [("you", "know"), ("i", "mean"), ("kind", "of"), ("sort", "of"), ("you", "see"), ("i", "guess"), ("let's", "see"), ("let", "me", "see")] STOP = {"the", "a", "an", "and", "or", "but", "to", "of", "in", "on", "at", "for", "with", "is", "are", "was", "were", "be", "it", "this", "that", "i", "you", "we", "they", "he", "she", "my", "your", "our", "do", "does", "did", "have", "has", "had", "will", "would", "can", "could", "if", "so", "as", "by", "from", "not", "no", "there"} CORRECTION = {"no", "sorry", "wait", "rather", "meant", "mean", "actually", "scratch", "correction"} def _norm(w: str) -> str: return _EDGE.sub("", w.lower()).replace("’", "'") def _lcs_pairs(a: list[str], b: list[str]) -> list[tuple[int, int]]: """LCS that keeps the LATER copy of repeated words (in a restart the later words are the correction).""" n, m = len(a), len(b) ra, rb = a[::-1], b[::-1] return [(n - 1 - i, m - 1 - j) for i, j in reversed(_lcs_left(ra, rb))] def _lcs_left(a: list[str], b: list[str]) -> list[tuple[int, int]]: n, m = len(a), len(b) 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 a[i] == b[j] else max(dp[i + 1][j], dp[i][j + 1]) pairs, i, j = [], 0, 0 while i < n and j < m: if a[i] == b[j]: pairs.append((i, j)) i += 1 j += 1 elif dp[i + 1][j] >= dp[i][j + 1]: i += 1 else: j += 1 return pairs def _only_fillers(span: list[str]) -> bool: k = 0 while k < len(span): for ph in PHRASES: if tuple(span[k:k + len(ph)]) == ph: k += len(ph) break else: if span[k] not in SOFT: return False k += 1 return True def _strip_fillers(span: list[str]) -> list[str]: out, k = [], 0 while k < len(span): for ph in PHRASES: if tuple(span[k:k + len(ph)]) == ph: k += len(ph) break else: if span[k] not in SOFT: out.append(span[k]) k += 1 return out def span_ok(span: list[str], after: list[str], before: list[str] = (), tokens: list[str] = (), starts: list[bool] = ()) -> bool: """span: deleted normalised words; after/before: the normalised input words around it; tokens/starts: the span's original tokens (with punctuation) and whether each opens a sentence.""" tokens = tokens or span starts = starts or [False] * len(span) mapped = [("uh" if w in COMMA_SOFT and (t.endswith(",") or st) else w) for w, t, st in zip(span, tokens, starts)] if _only_fillers(mapped): return True core = _strip_fillers(mapped) # "like, the" -> "the": then check for a repeat if not core: return True if list(after[:len(core)]) == core or list(before[-len(core):]) == core: return True # exact repeat: "I I", "to to", "we should, we should" content = [w for w in core if w not in STOP] if len(content) == 1: # one word: only a near repeat counts ("deliberate where, deliberate cold"), window = set(before[-2:]) | set(after[:3]) # or a comma-marked false start of a word said soon after if tokens and tokens[-1].endswith(",") and content[0] in set(before[-12:]) | set(after[:12]): return True else: window = set(before[-(len(span) + 6):]) | set(after[:len(span) + 6]) if content and sum(w in window for w in content) >= max(1, 0.5 * len(content)): return True # restart: "the Librem 14 does, Librem 14, running" if not content and after and core[0] == after[0]: return True # "we want, we need": restart of function words if not content and tokens[-1].endswith(",") and core[-1] in set(before[-3:]) | set(after[:3]): return True # "any there, free ... out there" wrong = [w for w in core if w not in CORRECTION] # "Tuesday, no, sorry," -> the replaced item if len(span) <= 8 and any(w in CORRECTION for w in span[1:]) and 1 <= len(wrong) <= 4: return True # self-correction return False def capitalise(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 rebuild(tokens: list[str], keep: list[bool]) -> str: out: list[str] = [] pending = None for t, k in zip(tokens, keep): if not k: m = _SENT_END.search(t) if m and out: pending = m.group(0) continue if pending and out and not _SENT_END.search(out[-1]): out[-1] = out[-1].rstrip(",;:") + pending pending = None out.append(t) if out and pending and not _SENT_END.search(out[-1]): out[-1] = out[-1].rstrip(",;:") + pending if out and not _SENT_END.search(out[-1]): out[-1] = out[-1].rstrip(",;:") if tokens and _SENT_END.search(tokens[-1]): out[-1] += _SENT_END.search(tokens[-1]).group(0) return capitalise(re.sub(r"^[,;:\s]+", "", " ".join(out))) def drop_hard_fillers(text: str) -> str: toks = text.split() keep = [_norm(t) not in HARD_FILLERS for t in toks] return text if all(keep) else rebuild(toks, keep) def repair(raw: str, cleaned: str) -> tuple[str, int]: """Return (text, number of restored spans); -1 when the output changed words and the raw text was used. Two alignments are tried (keep the later / the earlier copy of repeated words); if either explains every deletion, the model's output stands.""" first = _repair(raw, cleaned, _lcs_pairs) if first[1] <= 0: return first second = _repair(raw, cleaned, _lcs_left) return second if second[1] == 0 else first def _repair(raw: str, cleaned: str, align) -> tuple[str, int]: toks = raw.split() idx = [i for i, t in enumerate(toks) if _norm(t)] a = [_norm(toks[i]) for i in idx] b = [_norm(t) for t in cleaned.split() if _norm(t)] pairs = align(a, b) if len(pairs) < len(b): # the model added or changed words return drop_hard_fillers(raw), -1 kept = {i for i, _ in pairs} keep_w = [k in kept for k in range(len(a))] restored = 0 k = 0 while k < len(a): if keep_w[k]: k += 1 continue e = k while e < len(a) and not keep_w[e]: e += 1 starts = [idx[q] == 0 or bool(_SENT_END.search(toks[idx[q] - 1])) for q in range(k, e)] if not span_ok(a[k:e], a[e:], a[:k], [toks[idx[q]] for q in range(k, e)], starts): for q in range(k, e): keep_w[q] = True restored += 1 k = e if restored == 0: return drop_hard_fillers(cleaned), 0 keep = [False] * len(toks) for k, i in enumerate(idx): keep[i] = keep_w[k] and a[k] not in HARD_FILLERS return rebuild(toks, keep), restored