"""Shared deterministic dedup + precision-reject helpers. Used by both the one-shot pool merger and the production corruption pipeline so the two can never drift apart on what counts as a duplicate or a forbidden span. """ import re from collections import defaultdict from typing import List # --- Tier-1 parity (vox app/src-tauri/src/services/stt/itn.rs) ----------------- # INVARIANT: these two regexes must stay byte-equivalent to itn.rs, otherwise the # dataset gate will pass spans that production has already stripped. NON_LEXICAL_FILLER_RE = re.compile(r"(?i)\b(um+|uh+|er+|ah+|hmm+)\b[,;]?\s*") PUNCT_TRIM = ".,;:!?\"'()" # Tier 1 (vox itn.rs) already strips these deterministically — a synthetic span # matching them is a wasted training signal, so it is rejected before the judge. TIER1 = re.compile(r"^[,.\s]*(um+|uh+|er+|ah+|hmm+)[,.\s]*$", re.IGNORECASE) # Words whose deletion is never safe: pronouns, articles, and the conjunctions that # invariant 7 protects. Deleting a bare "the," or "and," is far more likely to be a # wrong label than a real disfluency, so such examples are dropped, not repaired. PROTECTED = {"it", "they", "them", "he", "she", "we", "you", "a", "an", "the", "and", "but", "so", "i", "my", "your", "his", "her", "our", "their", "me", "him", "us", "them"} PRON = {"it", "they", "them", "he", "she", "we", "you", "a", "an", "the"} NONWORD_RE = re.compile(r"[^a-z0-9 ]+") # Any surviving Tier-1 hesitation marker. Tier 1 deletes these upstream, so a label # containing one describes text that can never reach Tier 2 in production. TIER1_ANY = re.compile(r"\b(um+|uh+|er+|ah+|hmm+)\b", re.IGNORECASE) def norm_tokens(text: str) -> frozenset: """Normalization for near-dedup: lowercase, strip punctuation, token set.""" return frozenset(NONWORD_RE.sub(" ", text.lower()).split()) def near_dup(cand: frozenset, kept: List[frozenset], threshold: float = 0.85) -> bool: """Token-set Jaccard against kept fingerprints. Exact-text dedup is insufficient: template collapse emits near-identical sentences ("Deploy on Tuesday wait no Wednesday." x6 variants). """ if not cand: return True for other in kept: inter = len(cand & other) if inter and inter / len(cand | other) >= threshold: return True return False CUE_RE = re.compile( r"(actually|wait no|i mean|sorry|scratch that|rather|correction|" r"no,|no wait|^no—|—.*—)", re.IGNORECASE) EMDASH_RE = re.compile(r"[—–-]") FILLER_ONLY = re.compile(r"^[,.\s]*(like|so|well|you know)[,.\s]*$", re.IGNORECASE) def shape_reject(ex) -> str: """Pre-judge structural screen: spans must LOOK like disfluencies. Bare grammar fixes ("make"->"makes"), synonym swaps ("middle"->"centre") and insertions with no disfluency marker die here mechanically instead of depending on judge consistency. """ for s in ex.spans: t = s.text.strip() if ex.category == "REPAIR": if not CUE_RE.search(ex.raw_text): return f"REPAIR without audible cue in raw: {t[:40]!r}" if not CUE_RE.search(t) and not EMDASH_RE.search(t): return f"REPAIR span carries no cue: {t[:40]!r}" if not (s.target or "").strip(): return "REPAIR span missing target" else: # DELETE: filler-only, cue-led supersession, or truncated false start if FILLER_ONLY.match(t): continue if CUE_RE.search(t): continue if EMDASH_RE.search(t): continue return f"DELETE span has no disfluency shape: {t[:40]!r}" return "" def apply_tier1_prestrip(text: str) -> str: """Simulate the two Tier-1 steps that run BEFORE Tier 2, without ITN. Mirrors vox `itn.rs`: strip non-lexical hesitation markers (um/uh/er/ah/hmm), then collapse consecutive identical word tokens ("at at" -> "at"). Purpose: a Tier-2 span that this function already deletes can never appear in production, so training on it is wasted signal that also inflates eval scores with a task the model will never be asked to do. """ text = NON_LEXICAL_FILLER_RE.sub("", text) out: List[str] = [] words = text.split() i = 0 while i < len(words): cur = words[i].strip(PUNCT_TRIM) if i + 1 < len(words) and cur and cur.lower() == words[i + 1].strip(PUNCT_TRIM).lower(): i += 1 continue out.append(words[i]) i += 1 return " ".join(out) def already_gone_by_tier1(raw_text: str, span_text: str) -> bool: """True if Tier 1 would have removed this span before Tier 2 ever sees it.""" stripped = span_text.strip() if not stripped: return False return stripped not in apply_tier1_prestrip(raw_text) def deterministic_reject(ex) -> str: """Precision-first pre-judge screen. Returns reason ('' = pass).""" if TIER1_ANY.search(ex.clean_text or ""): return "Tier-1 hesitation marker survives in clean_text" for s in ex.spans: t = s.text.strip() if TIER1.match(t) or TIER1_ANY.search(t): return f"tier1-duplicative span {t!r}" if t.lower().strip(",. ") in PROTECTED: return f"protected-word span (pronoun/article/conjunction) {t!r}" return "" class NearDup: """Exact Jaccard >= t rejection, bucketed by token count. J(A,B) <= min(|A|,|B|) / max(|A|,|B|), so any pair reaching J >= t must have token counts within a factor t. Bucketing on length is therefore lossless and turns the O(n^2) sweep into per-bucket sweeps, which matters at Layer 3 scale. """ def __init__(self, threshold: float = 0.85): self.t = threshold self.buckets: dict[int, list] = defaultdict(list) def seen(self, fp: frozenset) -> bool: n = len(fp) if not n: return True lo = max(1, int(n * self.t)) for size in range(lo, int(n / self.t) + 2): for other in self.buckets.get(size, ()): inter = len(fp & other) if inter and inter / len(fp | other) >= self.t: return True return False def add(self, fp: frozenset) -> None: self.buckets[len(fp)].append(fp)