Datasets:
File size: 6,329 Bytes
46e27b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | """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)
|