vox-tier2-backup / scripts /compiler.py
addyo07's picture
Tier-2 parking snapshot 2026-10-04
46e27b5 verified
Raw History Blame Contribute Delete
6.81 kB
"""
Deterministic Span Compiler & Slice-Cut Verifier.
Single-label non-autoregressive speech disfluency excision.
No target strings, no generative repairs — pure substring-to-offset compilation,
orphan comma absorption, and 100% roundtrip reconstruction assertions.
"""
import re
from typing import List, Optional, Tuple
from schema import DatasetExample, RawCandidate, Span
def clean_punctuation_whitespace(text: str) -> str:
"""
Deterministic post-excision cleanup matching Vox's Tier 1 itn.rs runtime:
- Collapses duplicate spaces
- Collapses spaces before punctuation: "word , next" -> "word, next"
- Collapses multiple commas: "word, , next" -> "word, next"
- Collapses comma followed by terminal punctuation: ",." -> "."
- Trims leading/trailing whitespace
"""
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\s+([,.\?!।;:])", r"\1", text)
text = re.sub(r",\s*,+", ",", text)
text = re.sub(r",\s*([.\?!।])", r"\1", text)
return text.strip()
def compile_candidate_to_example(
candidate: RawCandidate,
example_id: str
) -> Tuple[Optional[DatasetExample], Optional[str]]:
"""
Deterministically computes character spans from disfluent substrings and
verifies 100% roundtrip reconstruction against clean_text via slice cuts.
"""
raw = candidate.raw_text
clean = candidate.clean_text.strip()
category = "CLEAN" if (not candidate.disfluent_spans and raw.strip() == clean) else "DISFLUENCY"
# Boundary Gate: closed terminal sentences only (. ? ! ।).
if not raw.strip() or raw.strip()[-1] not in ".?!।":
return None, f"Boundary Gate: raw_text must end with closed terminal (.?!।), got '{raw[-20:]}'"
if not clean or clean[-1] not in ".?!।":
return None, f"Boundary Gate: clean_text must end with closed terminal (.?!।), got '{clean[-20:]}'"
# Case 1: CLEAN negative control
if category == "CLEAN":
if candidate.disfluent_spans:
return None, "CLEAN category cannot contain disfluent spans"
if raw.strip() != clean:
return None, f"CLEAN raw_text must equal clean_text (got raw='{raw}', clean='{clean}')"
return DatasetExample(
id=example_id,
category="CLEAN",
raw_text=raw,
clean_text=clean,
spans=[]
), None
# Case 2: Speech Disfluency excision
if not candidate.disfluent_spans:
return None, "DISFLUENCY category must contain at least one disfluent span"
computed_spans: List[Span] = []
search_cursor = 0
for span_str in candidate.disfluent_spans:
target_str = span_str
if not target_str or not target_str.strip():
return None, "Empty disfluent span string: must name a non-empty verbatim substring"
start_idx = raw.find(target_str, search_cursor)
if start_idx == -1:
start_idx = raw.find(target_str)
if start_idx == -1:
return None, f"Disfluent span '{target_str}' not found in raw_text"
end_idx = start_idx + len(target_str)
orig_start, orig_end = start_idx, end_idx
# Orphan Comma Absorption: absorb surrounding hesitation punctuation
leading_text = raw[:start_idx]
leading_stripped = leading_text.rstrip(" ")
if leading_stripped.endswith(","):
comma_pos = len(leading_stripped) - 1
start_idx = comma_pos
target_str = raw[start_idx:end_idx]
trailing_text = raw[end_idx:]
trailing_stripped = trailing_text.lstrip(" ")
if trailing_stripped.startswith(","):
comma_offset = len(trailing_text) - len(trailing_stripped) + 1
end_idx += comma_offset
target_str = raw[start_idx:end_idx]
computed_spans.append(
Span(
label="speech disfluency",
span=(start_idx, end_idx),
text=target_str,
confidence=1.0
)
)
search_cursor = end_idx
# Orphan Comma Fallback: if absorbing commas breaks roundtrip, retry bare span
if (orig_start, orig_end) != (start_idx, end_idx):
bare_span = Span(label="speech disfluency", span=(orig_start, orig_end),
text=raw[orig_start:orig_end], confidence=1.0)
rest = [s for s in computed_spans if s.span[0] >= computed_spans[-1].span[1]]
ok, _ = verify_roundtrip(raw, computed_spans[:-1] + [bare_span] + rest, clean)
if ok:
computed_spans[-1] = bare_span
search_cursor = orig_end
# Sort spans by start offset
computed_spans.sort(key=lambda s: s.span[0])
# Check for overlapping spans
for i in range(len(computed_spans) - 1):
if computed_spans[i].span[1] > computed_spans[i + 1].span[0]:
return None, f"Overlapping spans detected: {computed_spans[i]} and {computed_spans[i+1]}"
# Verify 100% Roundtrip Reconstruction via slice cut
is_valid, reconstructed = verify_roundtrip(raw, computed_spans, clean)
if not is_valid:
return None, f"Roundtrip assertion failed: reconstructed '{reconstructed}' != clean '{clean}'"
return DatasetExample(
id=example_id,
category="DISFLUENCY",
raw_text=raw,
clean_text=clean,
spans=computed_spans
), None
def verify_roundtrip(raw_text: str, spans: List[Span], expected_clean: str) -> Tuple[bool, str]:
"""
Executes deterministic slice cuts on raw_text, collapses whitespace/commas,
and checks exact equality with expected_clean.
"""
result_chars = []
last_idx = 0
for span in sorted(spans, key=lambda s: s.span[0]):
start, end = span.span
prefix = raw_text[last_idx:start]
result_chars.append(prefix)
# Disfluency excision: if excision causes two adjacent word characters to collide, insert single space
full_so_far = "".join(result_chars).rstrip()
remaining_suffix = raw_text[end:].lstrip()
if full_so_far and remaining_suffix:
if full_so_far[-1].isalnum() and remaining_suffix[0].isalnum():
result_chars.append(" ")
last_idx = end
result_chars.append(raw_text[last_idx:])
raw_reconstructed = "".join(result_chars)
reconstructed = clean_punctuation_whitespace(raw_reconstructed)
expected_clean_norm = clean_punctuation_whitespace(expected_clean)
# Post-excision sentence capitalization parity (matches Vox Tier 1 itn.rs normalizer):
if reconstructed and expected_clean_norm and expected_clean_norm[0].isupper():
reconstructed = reconstructed[0].upper() + reconstructed[1:]
return (reconstructed == expected_clean_norm), reconstructed