vox-tier2-backup / scripts /profile_disfluency.py
addyo07's picture
Tier-2 parking snapshot 2026-10-04
46e27b5 verified
Raw History Blame Contribute Delete
7.39 kB
#!/usr/bin/env python3
"""Deterministic stratum profiler for a Tier-2 disfluency dataset.
Answers three questions that a schema/roundtrip QA gate cannot:
1. Which disfluency archetypes are actually represented, and in what quantity?
2. How much of the DISFLUENCY half is machine-substituted filler (not human speech)?
3. Which trivial surface features predict the CLEAN/DISFLUENCY label?
(A dataset that a one-line rule solves is degenerate and must be rejected.)
Usage:
venv/bin/python sandbox/scripts/profile_disfluency.py <dataset.jsonl> [--filler-bank PATH]
Exit code 0 always; this is a reporter, not a gate. Gate thresholds live in qa_gate.py.
"""
import argparse
import json
import re
import sys
from collections import Counter
sys.path.insert(0, "/opt/vox/sandbox/scripts")
from dedup import already_gone_by_tier1
# --- Archetype cues -----------------------------------------------------------
# TRUE self-correction: speaker audibly abandons one plan and states another.
# "I mean" is deliberately NOT here — in this corpus it is overwhelmingly a
# parenthetical hedge ("..., I mean, it was classic TREK"), i.e. a filler.
SUPERSESSION_CUE = re.compile(
r"\b(wait no|no wait|scratch that|sorry|correction|i apologize|my mistake|"
r"or instead|make that|i said|actually)\b", re.I)
# Filler that survives Tier 1 and is genuinely ambiguous (delete vs keep).
FILLER_PHRASE = re.compile(
r"^[\s,.]*("
r"well|so|so then|and so|like|anyway|basically|right|okay|ok|alright|now|oh|yeah|"
r"you know|you see|i mean|i guess|i think|kind of|sort of|pretty much|"
r"of course|naturally|honestly|seriously|to be honest|by the way|whatever|"
r"i mean that|i dont know|dunno|you get it|that said|in fact|indeed|"
r"at least|well then|well i|anyways|anyhow"
r")[\s,.]*$", re.I)
WORD = re.compile(r"[A-Za-z0-9']+")
def words(text):
return [w.lower() for w in WORD.findall(text)]
def classify(raw, span):
"""Assign one deterministic archetype to a single span."""
text = span["text"]
before = raw[: span["span"][0]]
sw = words(text)
# 0. Duplicates of upstream Tier 1 — must never appear in a Tier-2 dataset.
if already_gone_by_tier1(raw, text):
return "tier1_duplicate"
# 1. Partial phrase echo ("The client, the client is waiting") — survives Tier 1
# because only *consecutive identical* tokens are collapsed upstream.
if sw:
bw = words(before)
for k in range(min(len(sw), 6), 0, -1):
if len(bw) >= k and bw[-k:] == sw[:k]:
return "repetition"
# 2. True supersession: a correction cue governs material that gets dropped.
if SUPERSESSION_CUE.search(text):
return "supersession"
# 3. Filler / discourse marker: bare hesitation, no propositional content.
if FILLER_PHRASE.match(text.strip(" ,.")):
return "filler"
# 4. Everything else is an abandoned stem / false start.
return "false_start"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("dataset")
ap.add_argument("--filler-bank", default="/opt/vox/sandbox/corpus/filler_bank.json")
ap.add_argument("--sample", type=int, default=0, help="report only the first N CLEAN spans")
args = ap.parse_args()
bank = set()
try:
with open(args.filler_bank) as f:
bank = {s.lower().strip().strip(",. ") for s in json.load(f)}
except Exception:
pass
rows = [json.loads(l) for l in open(args.dataset) if l.strip()]
clean = [r for r in rows if r["category"] == "CLEAN"]
dis = [r for r in rows if r["category"] == "DISFLUENCY"]
spans = [(r, s) for r in dis for s in r["spans"]]
print(f"dataset: {args.dataset}")
print(f"rows: {len(rows)} CLEAN: {len(clean)} DISFLUENCY: {len(dis)} spans: {len(spans)}")
# --- 1. Archetype coverage -------------------------------------------------
arche = Counter(classify(r["raw_text"], s) for r, s in spans)
print("\n[1] ARCHETYPE COVERAGE (spans)")
for k, v in arche.most_common():
print(f" {k:12s} {v:6d} {round(100 * v / max(len(spans), 1), 1):5.1f}%")
# --- 2. Machine-substituted filler vs human speech -------------------------
if bank:
n_bank = sum(1 for _, s in spans if s["text"].lower().strip().strip(",. ") in bank)
bank_by_arche = Counter(
classify(r["raw_text"], s) for r, s in spans
if s["text"].lower().strip().strip(",. ") in bank)
print("\n[2] MACHINE-SUBSTITUTED FILLER (span text == filler_bank entry)")
print(f" {n_bank}/{len(spans)} spans ({round(100 * n_bank / max(len(spans), 1), 1)}%)")
for k, v in bank_by_arche.most_common():
print(f" as {k:12s} {v:6d}")
# --- 3. Span geometry -----------------------------------------------------
lead = sum(1 for _, s in spans if s["span"][0] == 0)
internal = sum(1 for _, s in spans if re.search(r"[.?!]\s+[A-Z]", s["text"]))
multi_sent = sum(1 for r in dis if re.search(r"[.?!]\s+[A-Z]", r["raw_text"]))
print("\n[3] SHAPE (must match production: ONE closed sentence per example)")
print(f" examples spanning >1 sentence : {multi_sent}/{len(dis)}"
f" ({round(100 * multi_sent / max(len(dis), 1), 1)}%)")
print(f" spans starting at char 0 : {lead}/{len(spans)}"
f" ({round(100 * lead / max(len(spans), 1), 1)}%)")
print(f" spans containing a sentence break : {internal}/{len(spans)}")
# --- 4. Trivial-feature baselines -----------------------------------------
wl_c = sorted(len(r["raw_text"].split()) for r in clean)
wl_d = sorted(len(r["raw_text"].split()) for r in dis)
med = lambda v: v[len(v) // 2] if v else 0
print("\n[4] LENGTH DISTRIBUTION")
print(f" CLEAN words median {med(wl_c):3d} p90 {wl_c[int(len(wl_c) * .9)] if wl_c else 0:3d}")
print(f" DISFLUENCY words median {med(wl_d):3d} p90 {wl_d[int(len(wl_d) * .9)] if wl_d else 0:3d}")
def acc(pred):
return round(100 * sum(1 for r in rows
if (r["category"] == "DISFLUENCY") == pred(r["raw_text"]))
/ max(len(rows), 1), 1)
best = max(((acc(lambda t, w=w: len(t.split()) >= w), w)
for w in range(3, 40)), default=(0, 0))
opener = re.compile(r"^\W*(well|yeah|oh|so|okay|ok|right|alright|now)\b", re.I)
cue = re.compile(r"\b(you know|i mean|you see|i guess|sort of|kind of)\b", re.I)
print("\n[5] TRIVIAL BASELINES (no model). A degenerate dataset scores high here.")
print(f" always CLEAN : {acc(lambda t: False)}%")
print(f" best word-count stump (>= {best[1]:2d} words) : {best[0]}%")
print(f" sentence-opener OR cue marker : "
f"{acc(lambda t: bool(opener.match(t)) or bool(cue.search(t)))}%")
print(f" combined : "
f"{acc(lambda t: len(t.split()) >= best[1] or bool(opener.match(t)) or bool(cue.search(t)))}%")
# --- 6. Hard-negative coverage -------------------------------------------
if args.sample:
bank_hits = sum(1 for r in clean[: args.sample]
if any(b in r["raw_text"].lower() for b in bank))
print(f"\n[6] first {args.sample} CLEAN examples containing a filler_bank phrase: {bank_hits}")
if __name__ == "__main__":
sys.exit(main())