Datasets:
File size: 10,762 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | #!/usr/bin/env python3
"""
Zero-Waste Disfluency Salvage Engine.
1. Deterministic cue-swapper for retractions / repetitive cues (0 GPU compute).
2. Qwen 3.5 9B salvage worker (Ollama port 11434 with thought bypass) for false starts and clean rejects.
"""
import json
import os
import re
import sys
import time
import urllib.request
from collections import Counter
from typing import Optional, Dict, Any, List
sys.path.insert(0, "/opt/vox/sandbox/scripts")
from corrupt_from_clean import normalize_span_stem, get_span_prefix2
CORPUS_PATH = "/opt/vox/sandbox/corpus/disfluency_15k.jsonl"
BAK_FS_PATH = "/opt/vox/temp/backups/disfluency_15k.jsonl.bak_repetitive_fs"
REJECTS_PATH = "/opt/vox/temp/backups/disfluency_15k_rejects.jsonl"
RETRACTION_CUES = [
"or rather", "scratch that", "make that", "correction", "actually I meant",
"let me rephrase", "sorry no", "no wait", "that is to say", "I mean",
"whoops", "rather", "check that", "strike that", "wait scratch that",
"excuse me", "pardon me", "no I mean", "or I should say", "actually"
]
def load_current_corpus_state():
stem_counts = Counter()
prefix2_counts = Counter()
committed_clean = set()
total_committed = 0
if os.path.exists(CORPUS_PATH):
with open(CORPUS_PATH) as f:
for line in f:
d = json.loads(line)
committed_clean.add(d["clean_text"])
total_committed += 1
for s in d.get("spans", []):
text = s.get("text", "")
stem = normalize_span_stem(text)
stem_counts[stem] += 1
pfx = get_span_prefix2(text)
if pfx and len(pfx.split()) >= 2:
prefix2_counts[pfx] += 1
return committed_clean, stem_counts, prefix2_counts, total_committed
def deterministic_cue_swap(example: Dict[str, Any], stem_counts: Counter, prefix2_counts: Counter, max_span: int = 10, max_pfx: int = 15) -> Optional[Dict[str, Any]]:
"""Deterministically swap saturated cue words with an unsaturated cue word."""
spans = example.get("spans", [])
if len(spans) != 1:
return None
span_info = spans[0]
span_text = span_info.get("text", "")
span_range = span_info.get("span", [])
raw_text = example.get("raw_text", "")
clean_text = example.get("clean_text", "")
# Look for known cue phrases inside span
matched_cue = None
for cue in ["wait no", "sorry", "I mean", "actually", "no wait", "well anyway"]:
if cue.lower() in span_text.lower():
matched_cue = cue
break
if not matched_cue:
return None
# Try replacement cues in order of least frequency
for rep in RETRACTION_CUES:
# Case preservation
pat = re.compile(re.escape(matched_cue), re.IGNORECASE)
new_span_text = pat.sub(rep, span_text, count=1)
if new_span_text == span_text:
continue
new_stem = normalize_span_stem(new_span_text)
new_pfx = get_span_prefix2(new_span_text)
if stem_counts[new_stem] >= max_span:
continue
if new_pfx and len(new_pfx.split()) >= 2 and prefix2_counts[new_pfx] >= max_pfx:
continue
# Build new raw text
start, end = span_range
new_raw_text = raw_text[:start] + new_span_text + raw_text[end:]
new_end = start + len(new_span_text)
# Strict roundtrip validation
reconstructed_clean = new_raw_text[:start] + new_raw_text[new_end:]
if reconstructed_clean != clean_text:
continue
# Accepted
stem_counts[new_stem] += 1
if new_pfx and len(new_pfx.split()) >= 2:
prefix2_counts[new_pfx] += 1
new_ex = dict(example)
new_ex["raw_text"] = new_raw_text
new_ex["spans"] = [{
"label": "speech disfluency",
"span": [start, new_end],
"text": new_span_text,
"confidence": 1.0,
"origin": "salvage:deterministic_swap"
}]
return new_ex
return None
def query_qwen(prompt: str, temp: float = 0.4, timeout: float = 8.0) -> Optional[str]:
"""Query Qwen 3.5 9B with thought bypass for fast completion."""
payload = json.dumps({
"model": "qwen3.5:9b",
"prompt": prompt,
"stream": False,
"raw": True,
"options": {"temperature": temp, "num_predict": 150}
}).encode("utf-8")
req = urllib.request.Request(
"http://127.0.0.1:11434/api/generate",
data=payload,
headers={"Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
data = json.loads(resp.read().decode("utf-8"))
return data.get("response", "")
except Exception as e:
return None
def qwen_salvage(clean_text: str, stem_counts: Counter, prefix2_counts: Counter, max_span: int = 10, max_pfx: int = 15) -> Optional[Dict[str, Any]]:
"""Ask Qwen 3.5 9B to generate a diverse disfluency with negative constraints."""
# Find top saturated prefixes to ban
banned = [p for p, c in prefix2_counts.most_common(12) if c >= (max_pfx - 3)]
banned_str = ", ".join([f'"{b}"' for b in banned[:8]]) if banned else '"because i", "if we"'
prompt = f"""<|im_start|>system
You are an expert speech disfluency annotator.
Given a clean sentence, produce a natural spoken version with exactly ONE realistic speech disfluency (repetition, retraction, hesitation, or restart).
Rules:
1. Do NOT start the disfluent span with: {banned_str}.
2. Output STRICT JSON only.
Format:
{{"raw_text": "...", "span_text": "..."}}
Example:
{{"raw_text": "Regarding the, yes I am also looking for information.", "span_text": "Regarding the, "}}
<|im_end|>
<|im_start|>user
Clean sentence: "{clean_text}"
Generate disfluent version:
<|im_end|>
<|im_start|>assistant
<|thought|>
Generating diverse disfluency avoiding banned prefixes.
<|endofthought|>
{{"raw_text":\""""
raw_resp = query_qwen(prompt, temp=0.5)
if not raw_resp:
return None
full_json_str = '{"raw_text":' + raw_resp.strip()
# Find JSON boundaries
m = re.search(r'\{.*\}', full_json_str, re.DOTALL)
if not m:
return None
try:
data = json.loads(m.group(0))
raw_text = data.get("raw_text", "").strip()
span_text = data.get("span_text", "")
if not raw_text or not span_text:
return None
# Verify span in raw_text
idx = raw_text.find(span_text)
if idx == -1:
return None
start = idx
end = idx + len(span_text)
# Verify roundtrip
reconstructed = raw_text[:start] + raw_text[end:]
if reconstructed != clean_text:
return None
stem = normalize_span_stem(span_text)
pfx = get_span_prefix2(span_text)
if stem_counts[stem] >= max_span:
return None
if pfx and len(pfx.split()) >= 2 and prefix2_counts[pfx] >= max_pfx:
return None
# Accepted
stem_counts[stem] += 1
if pfx and len(pfx.split()) >= 2:
prefix2_counts[pfx] += 1
return {
"category": "DISFLUENCY",
"raw_text": raw_text,
"clean_text": clean_text,
"spans": [{
"label": "speech disfluency",
"span": [start, end],
"text": span_text,
"confidence": 1.0,
"origin": "salvage:qwen3.5_worker"
}]
}
except Exception:
return None
def main():
print("=== Starting Disfluency Salvage Engine ===")
committed_clean, stem_counts, prefix2_counts, total_committed = load_current_corpus_state()
print(f"Current committed records: {total_committed}")
print(f"Tracking {len(stem_counts)} unique stems, {len(prefix2_counts)} 2-word prefixes")
salvaged_deterministic = 0
salvaged_qwen = 0
# Collect clean sentences to salvage
salvage_pool: List[Dict[str, Any]] = []
# 1. From repetitive false start backup
if os.path.exists(BAK_FS_PATH):
with open(BAK_FS_PATH) as f:
for line in f:
d = json.loads(line)
c = d.get("clean_text")
if c and c not in committed_clean:
salvage_pool.append(d)
# 2. From judge rejects
if os.path.exists(REJECTS_PATH):
with open(REJECTS_PATH) as f:
for line in f:
d = json.loads(line)
c = d.get("clean_text")
if c and c not in committed_clean:
salvage_pool.append({"clean_text": c})
print(f"Candidates available for salvage: {len(salvage_pool)}")
OUT_PATH = "/opt/vox/temp/salvaged_qwen.jsonl"
with open(OUT_PATH, "a", encoding="utf-8") as out:
for idx, item in enumerate(salvage_pool):
clean = item.get("clean_text")
if clean in committed_clean:
continue
# Step 1: Try deterministic cue swap if item has raw_text and spans
res = None
if "raw_text" in item and "spans" in item:
res = deterministic_cue_swap(item, stem_counts, prefix2_counts)
if res:
res["id"] = f"vxb_syn_{total_committed + 1:05d}"
out.write(json.dumps(res, ensure_ascii=False) + "\n")
out.flush()
committed_clean.add(clean)
total_committed += 1
salvaged_deterministic += 1
print(f"[{total_committed:5d}] Salvaged (Deterministic): {res['spans'][0]['text']!r}")
continue
# Step 2: Try Qwen salvage worker
res = qwen_salvage(clean, stem_counts, prefix2_counts)
if res:
res["id"] = f"vxb_syn_{total_committed + 1:05d}"
out.write(json.dumps(res, ensure_ascii=False) + "\n")
out.flush()
committed_clean.add(clean)
total_committed += 1
salvaged_qwen += 1
print(f"[{total_committed:5d}] Salvaged (Qwen Worker): {res['spans'][0]['text']!r}")
else:
pass
if (idx + 1) % 50 == 0:
print(f"Progress: {idx+1}/{len(salvage_pool)} | Det: {salvaged_deterministic} | Qwen: {salvaged_qwen} | Total: {total_committed}")
print(f"\n=== Salvage Complete ===")
print(f"Deterministic Salvaged: {salvaged_deterministic}")
print(f"Qwen Salvaged: {salvaged_qwen}")
print(f"Total Committed in Corpus: {total_committed}")
if __name__ == "__main__":
main()
|