Datasets:
File size: 6,809 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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | """
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
|