File size: 33,827 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
#!/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()