Datasets:
Download scripts/corrupt_from_clean.py from addyo07/vox-tier2-backup: direct link, hf CLI and curl.
- Browser
- Download file 33.8 kB
-
https://huggingface.co/datasets/addyo07/vox-tier2-backup/resolve/main/scripts/corrupt_from_clean.py
- Command line
-
hf download hf://datasets/addyo07/vox-tier2-backup/scripts/corrupt_from_clean.py
-
curl -L -o corrupt_from_clean.py https://huggingface.co/datasets/addyo07/vox-tier2-backup/resolve/main/scripts/corrupt_from_clean.py
33.8 kB
| #!/usr/bin/env python3 | |
| """ | |
| Corruption-from-CLEAN synthesis driver for Vox Speech Disfluency Refinement. | |
| Single label: "speech disfluency". Zero target fields. | |
| The LLM outputs ONLY two fields: | |
| 1. corrupted_text (the corrupted spoken utterance) | |
| 2. disfluent_spans (the exact substrings added to be excised) | |
| Multi-Archetype Generation: | |
| Speech disfluency is NOT just conversational filler words ("like", "you know"). | |
| It covers 4 distinct natural speech archetypes: | |
| 1. REPETITION: Redundant words, lexical echoes, repeated phrases/conjunctions ("we need to we need to", "in the, in the", "and also and also") | |
| 2. FALSE_START: Abandoned stems and sentence starters with conjunctions ("Because I thought, well anyway...", "If we could, but actually...", "And then we, so what happened was...") | |
| 3. RETRACTION: Spoken verbal self-corrections with verbal cues ("Tuesday, wait no, Wednesday", "ten, scratch that, twenty", "send to Bob, I mean, Alice") | |
| 4. DISCOURSE: Discourse markers and parenthetical hesitations ("well", "you know", "I mean", "I guess you could say") | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import random | |
| import re | |
| import sys | |
| import threading | |
| import time | |
| from collections import Counter | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from typing import Dict, Any, List, Optional, Tuple, Set | |
| import requests | |
| sys.path.insert(0, "/opt/vox/sandbox/scripts") | |
| try: | |
| from compiler import compile_candidate_to_example | |
| from schema import DatasetExample, RawCandidate, Span | |
| from dedup import NearDup, apply_tier1_prestrip, deterministic_reject, norm_tokens | |
| from judge import BatchJudge, audit_dataset | |
| except ImportError: | |
| from sandbox.scripts.compiler import compile_candidate_to_example | |
| from sandbox.scripts.schema import DatasetExample, RawCandidate, Span | |
| from sandbox.scripts.dedup import NearDup, apply_tier1_prestrip, deterministic_reject, norm_tokens | |
| from sandbox.scripts.judge import BatchJudge, audit_dataset | |
| OLLAMA_URL = "http://127.0.0.1:11434/api/chat" | |
| # Two independent generation backends, pinned one-per-worker and run CONCURRENTLY. | |
| # L1-GEN-009 measured that Ollama generation collapses under concurrent streams on | |
| # this box, so each backend gets exactly one stream; parallelism comes from the two | |
| # servers, never from stacking requests on a single one. | |
| BACKENDS = { | |
| # ollama on the GPU instance using gemma4:12b. | |
| "ollama": {"kind": "ollama", "url": OLLAMA_URL, "model": "gemma4:12b"}, | |
| } | |
| ARCHETYPES = { | |
| "repetition": { | |
| "desc": "Spoken repetition or redundant words (e.g. repeating a word, conjunction, preposition, or entire phrase: 'we should we should', 'in the, in the', 'and also, and also', 'the server, the server').", | |
| "examples": [ | |
| ("We should examine the log files.", "We should we should examine the log files.", ["we should "]), | |
| ("The client is waiting for our response.", "The client, the client is waiting for our response.", ["The client, "]), | |
| ("In the end everything worked out fine.", "In the, in the end everything worked out fine.", ["in the, "]), | |
| ("And we need to notify the entire team.", "And, and we need to notify the entire team.", ["And, "]), | |
| ("Please verify the signature before sending.", "Please, please verify the signature before sending.", ["Please, "]), | |
| ("They found several security vulnerabilities.", "They found, they found several security vulnerabilities.", ["they found, "]), | |
| ("After the meeting we can discuss the proposal.", "After, after the meeting we can discuss the proposal.", ["After, "]), | |
| ("You can download the package from the portal.", "You can, you can download the package from the portal.", ["You can, "]), | |
| ] | |
| }, | |
| "false_start": { | |
| "desc": "An abandoned clause, false start, or spoken restart. The speaker begins saying one thought or syntactic structure, cuts themselves off, and starts their sentence over. Patterns include aborted clauses, interrupted questions, abandoned conditionals, or sentence-initial/mid-sentence restarts. MUST be linguistically varied and natural.", | |
| "examples": [ | |
| ("Let's deploy the update tonight.", "If we could— but actually let's deploy the update tonight.", ["If we could— but actually "]), | |
| ("We need to upgrade the database version.", "Regarding our plan to— well actually we need to upgrade the database version.", ["Regarding our plan to— well actually "]), | |
| ("The transaction failed due to network timeout.", "When they submitted the— so what happened was the transaction failed due to network timeout.", ["When they submitted the— so what happened was "]), | |
| ("You can find the documentation on the intranet.", "Where did we put— okay you can find the documentation on the intranet.", ["Where did we put— okay "]), | |
| ("The report will be ready by Thursday morning.", "As far as completing the— well the report will be ready by Thursday morning.", ["As far as completing the— well "]), | |
| ("We should consider alternative vendors.", "It might be better to— or rather we should consider alternative vendors.", ["It might be better to— or rather "]), | |
| ("Please send the tracking number to the customer.", "Could you check if— actually please send the tracking number to the customer.", ["Could you check if— actually "]), | |
| ("Our team finished the sprint ahead of schedule.", "In terms of progress on the— so our team finished the sprint ahead of schedule.", ["In terms of progress on the— so "]), | |
| ("There are several flights available tomorrow.", "Looking at the morning— well there are several flights available tomorrow.", ["Looking at the morning— well "]), | |
| ("The conference was postponed until next month.", "Did they announce when— anyway the conference was postponed until next month.", ["Did they announce when— anyway "]), | |
| ("Customers reported issues when checking out.", "Because when people try to— customers reported issues when checking out.", ["Because when people try to— "]), | |
| ("The algorithm converges much faster with a smaller rate.", "We tested whether the— the algorithm converges much faster with a smaller rate.", ["We tested whether the— "]), | |
| ] | |
| }, | |
| "retraction": { | |
| "desc": "A spoken verbal self-correction with an audible cue ('Tuesday, wait no, Wednesday', 'ten, scratch that, twenty', 'send to Bob, actually, send to Alice', 'five, sorry, six').", | |
| "examples": [ | |
| ("The meeting is scheduled for Wednesday at noon.", "The meeting is scheduled for Tuesday, wait no, Wednesday at noon.", ["Tuesday, wait no, "]), | |
| ("Please send this report to Alice.", "Please send this report to Bob, actually make that Alice.", ["Bob, actually make that "]), | |
| ("We have four available slots remaining.", "We have two, scratch that, four available slots remaining.", ["two, scratch that, "]), | |
| ("Call Dr. Harris regarding the test results.", "Call Dr. Evans, I mean, Dr. Harris regarding the test results.", ["Dr. Evans, I mean, "]), | |
| ("We should aim for fifteen participants.", "We should aim for twelve, sorry, fifteen participants.", ["twelve, sorry, "]), | |
| ("The server is running on port 8080.", "The server is running on port 3000, wait no, 8080.", ["port 3000, wait no, "]), | |
| ("The package will arrive by Friday.", "The package will arrive by Thursday, correction, Friday.", ["Thursday, correction, "]), | |
| ("She works in the finance department.", "She works in legal, actually make that finance.", ["legal, actually make that "]), | |
| ] | |
| }, | |
| "discourse": { | |
| "desc": "A conversational discourse marker or parenthetical hesitation ('well', 'you know', 'I mean', 'I guess you could say').", | |
| "examples": [ | |
| ("This requires a complete rewrite of the parser.", "This requires, I mean, a complete rewrite of the parser.", ["I mean, "]), | |
| ("We should optimize the search index first.", "Well, we should optimize the search index first.", ["Well, "]), | |
| ("The system is running out of disk space.", "The system is, you know, running out of disk space.", ["you know, "]), | |
| ("That decision had significant consequences.", "That decision, I guess you could say, had significant consequences.", ["I guess you could say, "]), | |
| ("The performance gains were quite noticeable.", "The performance gains were, well, quite noticeable.", ["well, "]), | |
| ("Nobody expected that kind of response.", "Nobody, honestly, expected that kind of response.", ["honestly, "]), | |
| ("We need to adjust our expectations accordingly.", "We need to, you see, adjust our expectations accordingly.", ["you see, "]), | |
| ("That was probably the best option available.", "That was, I suppose, the best option available.", ["I suppose, "]), | |
| ] | |
| } | |
| } | |
| PROMPT_TEMPLATE = """<task> | |
| Corrupt the input clean sentence into ONE natural spoken-disfluency example using the requested SPEECH ARCHETYPE: | |
| Archetype: {archetype_name} | |
| Archetype Description: {archetype_desc} | |
| CRITICAL RULES: | |
| 1. Every word and punctuation mark outside the disfluent span MUST remain 100% identical to the input sentence. | |
| 2. Excising the disfluent span(s) MUST recreate the input clean sentence exactly. Do NOT delete or alter any clean words or punctuation. | |
| 3. Return ONLY two fields: `corrupted_text` and `disfluent_spans`. | |
| 4. `disfluent_spans` MUST contain the exact verbatim substrings to excise, matching the exact casing in `corrupted_text`. | |
| 5. FORBIDDEN PATTERNS: | |
| - Do NOT use generic conversational filler preambles like "I mean", "I was wondering", "I think", "Basically", or "So I mean". | |
| - A false start MUST contain an aborted thought, interrupted clause, or abandoned sentence fragment (e.g. "If we could—", "When they—", "Regarding our—", "Could you check—"). | |
| 6. DO NOT delete, shorten, or excise valid sentence-initial subject pronouns ('I', 'We', 'It', 'You', 'They') unless part of a complete spoken repetition or multi-word restart (e.g., 'We should we should', NEVER deleting 'We'). | |
| 7. VARY your disfluent phrasing widely! Adapt the disfluent thought to the specific topic/context of the input sentence. DO NOT reuse the same stock phrase across different sentences. | |
| {banned_block}</task> | |
| <examples> | |
| {examples_block} | |
| </examples> | |
| <inputs> | |
| Input: {input_sentence} | |
| </inputs> | |
| Respond with JSON only: | |
| {{"corrupted_text": "...", "disfluent_spans": ["..."]}} | |
| """ | |
| def normalize_span_stem(text: str) -> str: | |
| cleaned = re.sub(r"[^a-z0-9\s]", "", text.lower()).strip() | |
| return re.sub(r"\s+", " ", cleaned) | |
| def get_span_prefix2(text: str) -> str: | |
| stem = normalize_span_stem(text) | |
| words = stem.split() | |
| return " ".join(words[:2]) if len(words) >= 2 else (words[0] if words else "") | |
| def eligible_clean(sent: str) -> bool: | |
| s = sent.strip() | |
| if not s or s[-1] not in ".?": | |
| return False | |
| if any(c in s for c in ':";“”‘’!—–()[]'): | |
| return False | |
| words = s.split() | |
| if not (6 <= len(words) <= 24): | |
| return False | |
| if not words[0][0].isalpha() or not words[0][0].isupper(): | |
| return False | |
| return True | |
| RETRACTION_REPLACEMENT_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 try_deterministic_cue_swap(ex: DatasetExample, stem_counts: Counter, prefix2_counts: Counter, max_span_repeat: int, max_prefix_repeat: int) -> Optional[DatasetExample]: | |
| if len(ex.spans) != 1: | |
| return None | |
| s = ex.spans[0] | |
| matched_cue = None | |
| for cue in ["wait no", "sorry", "I mean", "actually", "no wait", "well anyway"]: | |
| if cue.lower() in s.text.lower(): | |
| matched_cue = cue | |
| break | |
| if not matched_cue: | |
| return None | |
| for rep in RETRACTION_REPLACEMENT_CUES: | |
| pat = re.compile(re.escape(matched_cue), re.IGNORECASE) | |
| new_span_text = pat.sub(rep, s.text, count=1) | |
| if new_span_text == s.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_repeat: | |
| continue | |
| if new_pfx and len(new_pfx.split()) >= 2 and prefix2_counts[new_pfx] >= max_prefix_repeat: | |
| continue | |
| start, end = s.span | |
| new_raw = ex.raw_text[:start] + new_span_text + ex.raw_text[end:] | |
| new_end = start + len(new_span_text) | |
| # Strict roundtrip validation | |
| if new_raw[:start] + new_raw[new_end:] != ex.clean_text: | |
| continue | |
| return DatasetExample( | |
| id=ex.id, | |
| category=ex.category, | |
| raw_text=new_raw, | |
| clean_text=ex.clean_text, | |
| spans=[Span( | |
| label="speech disfluency", | |
| span=(start, new_end), | |
| text=new_span_text, | |
| confidence=1.0, | |
| origin="salvage:deterministic_swap" | |
| )] | |
| ) | |
| return None | |
| def build_prompt(sentence: str, archetype_key: str, rng: Optional[random.Random] = None, | |
| banned_prefixes: Optional[List[str]] = None) -> str: | |
| arch = ARCHETYPES[archetype_key] | |
| ex_list = list(arch["examples"]) | |
| if rng is not None and len(ex_list) > 3: | |
| sampled_ex = rng.sample(ex_list, 3) | |
| else: | |
| sampled_ex = ex_list[:3] | |
| ex_lines = [] | |
| for clean_in, corrupted_out, spans in sampled_ex: | |
| ex_lines.append(f"Input: {clean_in}\nResponse:\n" + json.dumps({ | |
| "corrupted_text": corrupted_out, | |
| "disfluent_spans": spans | |
| }, indent=2)) | |
| examples_block = "\n\n".join(ex_lines) | |
| banned_block = "" | |
| if banned_prefixes: | |
| banned_str = ", ".join([f'"{b}"' for b in banned_prefixes]) | |
| banned_block = ( | |
| f"8. BANNED OPENINGS (NEVER start the disfluent span with any of these saturated prefixes): {banned_str}.\n" | |
| " Use creative domain-specific vocabulary, interrupted actions, or unique phrasing instead!\n" | |
| ) | |
| return PROMPT_TEMPLATE.format( | |
| archetype_name=archetype_key.upper(), | |
| archetype_desc=arch["desc"], | |
| examples_block=examples_block, | |
| input_sentence=sentence, | |
| banned_block=banned_block | |
| ) | |
| def call_model(sentence: str, archetype_key: str, model_name: str, timeout: int = 25, | |
| backend: str = "ollama", rng: Optional[random.Random] = None, | |
| banned_prefixes: Optional[List[str]] = None) -> Optional[dict]: | |
| prompt = build_prompt(sentence, archetype_key, rng=rng, banned_prefixes=banned_prefixes) | |
| cfg = BACKENDS.get(backend, BACKENDS["ollama"]) | |
| if cfg["kind"] == "openai": | |
| payload = { | |
| "model": cfg["model"], | |
| "messages": [{"role": "user", "content": prompt}], | |
| "temperature": 0.85, | |
| "top_p": 0.95, | |
| # Must exceed the JSON the prompt's indented few-shot examples imply. | |
| # At 512 llama-server returned finish_reason="length" with the object | |
| # cut mid-string, which surfaced as 70% unparseable ("llm_empty"). | |
| "max_tokens": 1024, | |
| } | |
| else: | |
| payload = { | |
| "model": cfg["model"], | |
| "messages": [{"role": "user", "content": prompt}], | |
| "stream": False, | |
| "think": False, | |
| "format": "json", | |
| "options": {"temperature": 0.85, "top_p": 0.95, "num_predict": 256}, | |
| } | |
| resp = requests.post(cfg["url"], json=payload, timeout=timeout) | |
| resp.raise_for_status() | |
| body = resp.json() | |
| content = (body["choices"][0]["message"].get("content") or "") if "choices" in body \ | |
| else body.get("message", {}).get("content", "") | |
| cleaned = re.sub(r"^```(?:json)?\s*", "", content.strip(), flags=re.MULTILINE) | |
| cleaned = re.sub(r"\s*```$", "", cleaned, flags=re.MULTILINE).strip() | |
| m = re.search(r"\{.*\}", cleaned, flags=re.DOTALL) | |
| if m: | |
| return json.loads(m.group(0)) | |
| return None | |
| def process_sentence(sentence: str, archetype_key: str, model: str, | |
| backend: str = "ollama", | |
| timeout: int = 25, | |
| rng: Optional[random.Random] = None, | |
| banned_prefixes: Optional[List[str]] = None) -> Tuple[Optional[DatasetExample], str]: | |
| try: | |
| data = call_model(sentence, archetype_key, model, timeout=timeout, backend=backend, rng=rng, | |
| banned_prefixes=banned_prefixes) | |
| if not data: | |
| return None, "llm_empty" | |
| raw_text = (data.get("corrupted_text") or data.get("raw_text") or "").strip() | |
| spans = data.get("disfluent_spans") or data.get("spans") or [] | |
| if isinstance(spans, str): | |
| spans = [spans] | |
| norm_spans = [s if isinstance(s, str) else (s.get("text", "") if isinstance(s, dict) else str(s)) for s in spans] | |
| norm_spans = [s for s in norm_spans if s and s.strip()] | |
| if not raw_text or not norm_spans: | |
| return None, "missing_fields" | |
| cand = RawCandidate( | |
| raw_text=raw_text, | |
| clean_text=sentence, | |
| disfluent_spans=norm_spans | |
| ) | |
| ex, why = compile_candidate_to_example(cand, "tmp") | |
| if ex is None: | |
| return None, f"compile:{why[:40]}" | |
| # Tier-1 parity: never train on a span that itn.rs already removed upstream. | |
| if any(s.text.strip() and s.text.strip() not in apply_tier1_prestrip(ex.raw_text) | |
| for s in ex.spans): | |
| return None, "screen:tier1_duplicate" | |
| # Protected words / surviving hesitation markers -> drop rather than repair. | |
| why_screen = deterministic_reject(ex) | |
| if why_screen: | |
| return None, f"screen:{why_screen[:40]}" | |
| # Provenance so synthetic data is auditable against the same mixture gate. | |
| for compiled in ex.spans: | |
| compiled.origin = f"synthetic:{archetype_key}" | |
| return ex, "ok" | |
| except Exception as e: | |
| return None, f"err:{type(e).__name__}" | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--clean", default="/opt/vox/sandbox/corpus/clean_50k.jsonl") | |
| parser.add_argument("--output", default="/opt/vox/sandbox/corpus/disfluency_synthetic.jsonl") | |
| parser.add_argument("--target", type=int, default=500) | |
| parser.add_argument("--workers", type=int, default=4) | |
| parser.add_argument("--model", default=None, | |
| help="unused; backends carry their own model. Kept for CLI compat.") | |
| parser.add_argument("--backends", default="ollama", | |
| help="comma-separated generation backends, run CONCURRENTLY") | |
| parser.add_argument("--judge", default="ollama", | |
| choices=["ollama", "llamacpp", "none"], | |
| help="judge backend; 'none' disables judging (compile-only)") | |
| parser.add_argument("--judge-url", default="http://127.0.0.1:11434") | |
| parser.add_argument("--judge-model", default="gemma4:12b") | |
| parser.add_argument("--judge-batch", type=int, default=15) | |
| parser.add_argument("--judge-workers", type=int, default=1) | |
| parser.add_argument("--chunk", type=int, default=120, | |
| help="candidates generated per round before judging") | |
| parser.add_argument("--max-rounds", type=int, default=1000, | |
| help="safety bound on generate->judge->refill rounds") | |
| parser.add_argument("--gen-workers", type=int, default=4, | |
| help="concurrent calls PER BACKEND (not total)") | |
| parser.add_argument("--gen-timeout", type=int, default=25, | |
| help="hard per-generation-call timeout (s)") | |
| parser.add_argument("--judge-timeout", type=int, default=75, | |
| help="hard per-judge-batch timeout (s)") | |
| parser.add_argument("--deadline", type=float, default=86400.0, | |
| help="abort the whole run after this many seconds") | |
| parser.add_argument("--rejects-log", default=None, | |
| help="path to log all judge rejections with full reasons") | |
| parser.add_argument("--max-span-repeat", type=int, default=12, | |
| help="hard cap on occurrences of identical normalized span stem") | |
| parser.add_argument("--max-prefix-repeat", type=int, default=25, | |
| help="hard cap on occurrences of identical 2-word span prefixes") | |
| parser.add_argument("--seed", type=int, default=42) | |
| args = parser.parse_args() | |
| rng = random.Random(args.seed) | |
| print(f"Loading clean sentences from {args.clean}...") | |
| pool = [] | |
| with open(args.clean, "r", encoding="utf-8") as f: | |
| for line in f: | |
| try: | |
| d = json.loads(line) | |
| s = d.get("raw_text") or d.get("clean_text") | |
| if eligible_clean(s): | |
| pool.append(s.strip()) | |
| except Exception: | |
| continue | |
| pool = list(dict.fromkeys(pool)) | |
| rng.shuffle(pool) | |
| print(f"Eligible unique clean pool: {len(pool)}") | |
| committed_keys: Set[str] = set() | |
| committed_cleans: Set[str] = set() | |
| dedup = NearDup(0.85) | |
| stem_counts = Counter() | |
| prefix2_counts = Counter() | |
| judged_pass = 0 | |
| if os.path.exists(args.output): | |
| with open(args.output, "r", encoding="utf-8") as f: | |
| for line in f: | |
| try: | |
| d = json.loads(line) | |
| committed_keys.add(d["raw_text"].strip().lower()) | |
| committed_cleans.add(d["clean_text"].strip().lower()) | |
| dedup.add(norm_tokens(d["raw_text"])) | |
| for s in d.get("spans", []): | |
| raw_s = s.get("text", "") | |
| stem = normalize_span_stem(raw_s) | |
| pfx = get_span_prefix2(raw_s) | |
| stem_counts[stem] += 1 | |
| if pfx and len(pfx.split()) >= 2: | |
| prefix2_counts[pfx] += 1 | |
| judged_pass += 1 | |
| except Exception: | |
| continue | |
| total_committed = len(committed_keys) | |
| print(f"Already committed in {args.output}: {total_committed}/{args.target}") | |
| if total_committed >= args.target: | |
| print("Target already achieved!") | |
| return | |
| judge = None | |
| if args.judge != "none": | |
| judge = BatchJudge(args.judge, args.judge_url, args.judge_model, | |
| timeout=args.judge_timeout) | |
| print(f"Judge: {args.judge_model} via {args.judge} @ {args.judge_url}") | |
| T0 = time.time() | |
| deadline = T0 + args.deadline | |
| backend_names = [b.strip() for b in args.backends.split(",") if b.strip() in BACKENDS] | |
| if not backend_names: | |
| backend_names = ["ollama"] | |
| print(f"Generation backends (concurrent, one stream each): {backend_names}") | |
| lock = threading.Lock() | |
| counters = Counter() | |
| counters["attempts"] = 0 | |
| judge_reasons = Counter() | |
| pool_idx = 0 | |
| round_no = 0 | |
| archetype_choices = ["repetition", "false_start", "retraction", "discourse"] | |
| # Sample weights: 30% repetition, 30% false_start, 25% retraction, 15% discourse | |
| archetype_weights = [0.30, 0.30, 0.25, 0.15] | |
| def next_items(count): | |
| nonlocal pool_idx | |
| items = [] | |
| while len(items) < count and pool_idx < len(pool): | |
| sent = pool[pool_idx] | |
| pool_idx += 1 | |
| if sent.strip().lower() in committed_cleans: | |
| continue | |
| arch = rng.choices(archetype_choices, weights=archetype_weights, k=1)[0] | |
| items.append((sent, arch)) | |
| return items | |
| pools = {b: ThreadPoolExecutor(max_workers=args.gen_workers, thread_name_prefix=f"gen-{b}") | |
| for b in backend_names} | |
| executor = next(iter(pools.values())) | |
| try: | |
| # ROUND: generate a whole chunk across both backends concurrently, screen it, | |
| # then judge the ENTIRE chunk in parallel batches. Judging is the slow part, | |
| # so it runs as one wide parallel sweep rather than one serial batch per | |
| # round. Only judge-PASS examples are committed; failures are discarded and | |
| # the next round refills for them. | |
| while total_committed < args.target and pool_idx < len(pool) \ | |
| and round_no < args.max_rounds and time.time() < deadline: | |
| round_no += 1 | |
| left = deadline - time.time() # seconds of budget remaining | |
| need = min(args.chunk, max(20, int((args.target - total_committed) * 1.3))) | |
| items = next_items(need) | |
| if not items: | |
| break | |
| # Dynamic negative prefix extraction: ban openings that have accumulated >= 8 repeats | |
| top_banned = [p for p, c in prefix2_counts.most_common(25) if c >= 8] | |
| futures = {} | |
| for i, (sent, arch) in enumerate(items): | |
| backend = backend_names[i % len(backend_names)] | |
| futures[pools[backend].submit(process_sentence, sent, arch, None, | |
| backend, args.gen_timeout, rng, | |
| top_banned)] = (sent, arch, backend) | |
| accepted = [] | |
| try: | |
| for fut in as_completed(futures, timeout=max(10, left)): | |
| sent, arch, backend = futures[fut] | |
| with lock: | |
| counters["attempts"] += 1 | |
| ex, why = fut.result() | |
| with lock: | |
| counters[why] += 1 | |
| if not ex: | |
| continue | |
| raw_key = ex.raw_text.strip().lower() | |
| clean_key = ex.clean_text.strip().lower() | |
| with lock: | |
| if raw_key in committed_keys or clean_key in committed_cleans: | |
| counters["duplicate"] += 1 | |
| continue | |
| if dedup.seen(norm_tokens(ex.raw_text)): | |
| counters["near_dup"] += 1 | |
| continue | |
| # Span repetition ceiling & prefix ceiling | |
| span_capped = False | |
| for s in ex.spans: | |
| stem = normalize_span_stem(s.text) | |
| pfx = get_span_prefix2(s.text) | |
| if stem_counts[stem] >= args.max_span_repeat: | |
| span_capped = True | |
| break | |
| if pfx and len(pfx.split()) >= 2 and prefix2_counts[pfx] >= args.max_prefix_repeat: | |
| span_capped = True | |
| break | |
| if span_capped: | |
| swapped = try_deterministic_cue_swap(ex, stem_counts, prefix2_counts, args.max_span_repeat, args.max_prefix_repeat) | |
| if swapped is not None: | |
| ex = swapped | |
| counters["screen:salvaged_deterministic"] += 1 | |
| span_capped = False | |
| else: | |
| counters["screen:span_freq_capped"] += 1 | |
| continue | |
| accepted.append(ex) | |
| except TimeoutError: | |
| pass | |
| if not accepted: | |
| print(f"[round {round_no}] no candidates survived screening; refilling") | |
| continue | |
| if judge is not None: | |
| # Parallel sweep: judge_batch across workers, one verdict per item. | |
| sweep = ThreadPoolExecutor(max_workers=args.judge_workers) | |
| try: | |
| verdicts = list(sweep.map( | |
| lambda b: judge.audit_batch(b, retries=0), | |
| [accepted[i:i + args.judge_batch] | |
| for i in range(0, len(accepted), args.judge_batch)])) | |
| verdicts = [v for chunk in verdicts for v in chunk] | |
| except Exception as e: # noqa: BLE001 | |
| counters[f"judge_sweep_error:{type(e).__name__}"] += 1 | |
| verdicts = [] | |
| finally: | |
| sweep.shutdown(wait=False, cancel_futures=True) | |
| if len(verdicts) != len(accepted): | |
| counters["judge_missing"] += len(accepted) - len(verdicts) | |
| accepted = accepted[:len(verdicts)] | |
| for v, ex in zip(verdicts, accepted): | |
| with lock: | |
| if v.verdict != "PASS": | |
| counters["judge_FAIL"] += 1 | |
| if args.rejects_log: | |
| with open(args.rejects_log, "a", encoding="utf-8") as f_rej: | |
| rej_obj = { | |
| "raw_text": ex.raw_text, | |
| "clean_text": ex.clean_text, | |
| "spans": [s.text for s in ex.spans], | |
| "verdict": v.verdict, | |
| "reason": v.reason | |
| } | |
| f_rej.write(json.dumps(rej_obj, ensure_ascii=False) + "\n") | |
| f_rej.flush() | |
| for tag in ("category_accurate", "no_false_deletions", | |
| "number_entity_preserved"): | |
| if not getattr(v, tag, False): | |
| counters[f"judge_fail_{tag}"] += 1 | |
| for word in str(v.reason).replace("|", " ").split(): | |
| w = "".join(ch for ch in word if ch.isalpha()).lower() | |
| if len(w) > 6: | |
| judge_reasons[w] += 1 | |
| continue | |
| if dedup.seen(norm_tokens(ex.raw_text)): | |
| counters["near_dup"] += 1 | |
| continue | |
| dedup.add(norm_tokens(ex.raw_text)) | |
| committed_keys.add(ex.raw_text.strip().lower()) | |
| committed_cleans.add(ex.clean_text.strip().lower()) | |
| for s in ex.spans: | |
| stem = normalize_span_stem(s.text) | |
| pfx = get_span_prefix2(s.text) | |
| stem_counts[stem] += 1 | |
| if pfx and len(pfx.split()) >= 2: | |
| prefix2_counts[pfx] += 1 | |
| total_committed += 1 | |
| judged_pass += 1 | |
| ex.id = f"vxb_syn_{total_committed:05d}" | |
| with open(args.output, "a", encoding="utf-8") as f_out: | |
| f_out.write(json.dumps(ex.model_dump(), ensure_ascii=False) + "\n") | |
| f_out.flush() | |
| else: | |
| for ex in accepted: | |
| with lock: | |
| dedup.add(norm_tokens(ex.raw_text)) | |
| committed_keys.add(ex.raw_text.strip().lower()) | |
| committed_cleans.add(ex.clean_text.strip().lower()) | |
| for s in ex.spans: | |
| stem = normalize_span_stem(s.text) | |
| pfx = get_span_prefix2(s.text) | |
| stem_counts[stem] += 1 | |
| if pfx and len(pfx.split()) >= 2: | |
| prefix2_counts[pfx] += 1 | |
| total_committed += 1 | |
| judged_pass += 1 | |
| ex.id = f"vxb_syn_{total_committed:05d}" | |
| with open(args.output, "a", encoding="utf-8") as f_out: | |
| f_out.write(json.dumps(ex.model_dump(), ensure_ascii=False) + "\n") | |
| f_out.flush() | |
| if time.time() >= deadline: | |
| print(f"[round {round_no}] deadline {args.deadline:.0f}s reached; stopping") | |
| break | |
| attempts = counters["attempts"] | |
| yield_rate = round(100 * total_committed / max(attempts, 1), 1) | |
| print(f"[round {round_no}] committed {total_committed}/{args.target} | " | |
| f"judge-pass {judged_pass} | attempts {attempts} | yield {yield_rate}% | " | |
| f"chunk {len(items)} screened {len(accepted)} | " | |
| f"{dict(counters.most_common(4))}") | |
| sys.stdout.flush() | |
| finally: | |
| for pool_exec in pools.values(): | |
| pool_exec.shutdown(wait=False, cancel_futures=True) | |
| print(f"\nwall_seconds: {round(time.time() - T0, 1)}") | |
| print(f"FINAL: committed={total_committed}/{args.target} " | |
| f"(judge-passed={judged_pass}, attempts={counters['attempts']})") | |
| if args.target: | |
| print(f"End-to-end yield: {round(100 * total_committed / max(counters['attempts'], 1), 1)}%") | |
| print("Counters:", json.dumps(dict(counters.most_common(15)), indent=1)) | |
| if judge_reasons: | |
| print("Top judge failure words:", judge_reasons.most_common(20)) | |
| print("Summary stats:", dict(counters.most_common(10))) | |
| if __name__ == "__main__": | |
| main() | |