vox-tier2-backup / scripts /salvage_engine.py
addyo07's picture
Tier-2 parking snapshot 2026-10-04
46e27b5 verified
Raw History Blame Contribute Delete
10.8 kB
#!/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()