File size: 10,367 Bytes
10a8395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Generate a resumable multi-task, multi-provider Speech Performance Arena batch."""

from __future__ import annotations

import argparse
import json
import random
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from voice_acting_rewriter import RewritePipeline  # noqa: E402
from voice_acting_rewriter.generation import (  # noqa: E402
    ADAPTER_VERSION,
    atomic_json,
    check_generated_content,
    default_adapters,
    GeneratedContentError,
    generation_cache_key,
    load_credentials,
    ProviderRequestError,
    prepare_content_retry,
    probe_audio,
    save_generated_audio,
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("pool", type=Path)
    parser.add_argument("keys", type=Path)
    parser.add_argument("--hypr-key-source", type=Path)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--task-id", action="append", dest="task_ids", help="repeat to select tasks")
    parser.add_argument("--profile", action="append", dest="profiles", help="repeat to select model profiles")
    parser.add_argument("--max-workers", type=int, default=3)
    parser.add_argument("--retries", type=int, default=1, help="retries after the first attempt")
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--skip-content-qc", action="store_true", help="skip transcript refusal/meta-speech checks")
    return parser.parse_args()


def run_job(adapter: Any, credentials: dict[str, str], rewrite: dict[str, Any], output: Path, retries: int, content_qc: bool = True) -> dict[str, Any]:
    started = time.time()
    errors = []
    effective_rewrite = rewrite
    for attempt in range(1, retries + 2):
        try:
            generated = adapter.generate(credentials, effective_rewrite)
            qc_content = check_generated_content(generated, use_asr=True) if content_qc else {"status": "skipped"}
            actual_output = output.with_suffix(f".{generated.extension}")
            qc = save_generated_audio(actual_output, generated)
            result = {"status": "ok", "attempts": attempt, "elapsed_seconds": round(time.time() - started, 3), "file": str(actual_output), "content_type": generated.content_type, "provider_metadata": generated.metadata, "content_qc": qc_content, "qc": qc}
            if errors:
                result["rejected_attempts"] = errors
            if effective_rewrite is not rewrite:
                result["retry_prompt"] = effective_rewrite.get("content_retry")
                result["effective_tts_payload"] = effective_rewrite.get("tts_payload")
            return result
        except Exception as error:
            detail = {"attempt": attempt, "type": type(error).__name__, "message": str(error)}
            if isinstance(error, GeneratedContentError):
                detail.update({"reason": error.reason, "transcript": error.transcript, "transcript_source": error.source})
                effective_rewrite = prepare_content_retry(rewrite, error)
            errors.append(detail)
            if isinstance(error, ProviderRequestError) and not error.retryable:
                break
            if attempt <= retries:
                time.sleep(min(2 ** (attempt - 1), 8) + random.random() * 0.25)
    return {"status": "error", "attempts": len(errors), "elapsed_seconds": round(time.time() - started, 3), "errors": errors}

def main() -> None:
    args = parse_args()
    if args.max_workers < 1 or args.retries < 0:
        raise SystemExit("--max-workers must be positive and --retries cannot be negative")

    pool = json.loads(args.pool.read_text(encoding="utf-8"))
    tasks_by_id = {task["id"]: task for task in pool["tasks"]}
    task_ids = args.task_ids or list(tasks_by_id)
    unknown_tasks = sorted(set(task_ids) - set(tasks_by_id))
    if unknown_tasks:
        raise SystemExit(f"unknown task IDs: {', '.join(unknown_tasks)}")

    adapters = default_adapters()
    profile_names = args.profiles or list(adapters)
    unknown_profiles = sorted(set(profile_names) - set(adapters))
    if unknown_profiles:
        raise SystemExit(f"unknown profiles: {', '.join(unknown_profiles)}")

    credentials = load_credentials(args.keys, args.hypr_key_source)
    benchmark_version = pool["meta"].get("source_benchmark_version", pool["meta"].get("version"))
    if not benchmark_version:
        raise SystemExit("prompt pool metadata needs source_benchmark_version or version")
    pipeline = RewritePipeline(ROOT)
    output_dir = args.output_dir.resolve()
    manifest_path = output_dir / "manifest.json"
    if manifest_path.exists() and not args.overwrite:
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    else:
        manifest = {
            "manifest_version": "0.2.0",
            "purpose": "multi-task engineering pilot; not benchmark evidence",
            "adapter_version": ADAPTER_VERSION,
            "benchmark_version": benchmark_version,
            "created_at_unix": int(time.time()),
            "pool": str(args.pool.resolve()),
            "jobs": {},
        }
    manifest["requested_task_ids"] = task_ids
    manifest["requested_profiles"] = profile_names
    atomic_json(manifest_path, manifest)

    pending: list[tuple[str, Any, dict[str, str], dict[str, Any], Path]] = []
    cached = 0
    unavailable = 0
    for task_id in task_ids:
        task = tasks_by_id[task_id]
        for profile_name in profile_names:
            adapter = adapters[profile_name]
            job_id = f"{task_id}/{profile_name}"
            available, reason = adapter.available(credentials)
            if not available:
                manifest["jobs"][job_id] = {"task_id": task_id, "profile_name": profile_name, "status": "unavailable", "reason": reason}
                unavailable += 1
                continue

            try:
                rewrite = pipeline.rewrite(task, profile_name, benchmark_version=benchmark_version)
            except Exception as error:
                manifest["jobs"][job_id] = {
                    "task_id": task_id,
                    "task_title": task.get("title"),
                    "track": task.get("track"),
                    "profile_name": profile_name,
                    "status": "rewrite_error",
                    "error_type": type(error).__name__,
                    "error": str(error),
                }
                atomic_json(manifest_path, manifest)
                continue
            cache_key = generation_cache_key(rewrite, profile_name)
            job_dir = output_dir / task_id / profile_name
            rewrite_path = job_dir / "rewrite.json"
            audio_path = job_dir / f"audio.{adapter.extension}"
            existing = manifest["jobs"].get(job_id, {})
            if not args.overwrite and existing.get("status") == "ok" and existing.get("generation_cache_key") == cache_key and audio_path.exists():
                try:
                    qc = probe_audio(audio_path)
                    if qc["sha256"] == existing.get("result", {}).get("qc", {}).get("sha256"):
                        existing["cached"] = True
                        existing["result"]["qc"] = qc
                        cached += 1
                        continue
                except Exception:
                    pass

            atomic_json(rewrite_path, rewrite)
            manifest["jobs"][job_id] = {
                "task_id": task_id,
                "task_title": task.get("title"),
                "track": task.get("track"),
                "profile_name": profile_name,
                "provider_model": rewrite["provider_model"],
                "profile_version": rewrite["profile_version"],
                "rewrite_cache_key": rewrite["cache_key"],
                "generation_cache_key": cache_key,
                "rewrite_file": str(rewrite_path.relative_to(output_dir)),
                "status": "planned" if args.dry_run else "pending",
            }
            if not args.dry_run:
                pending.append((job_id, adapter, credentials, rewrite, job_dir / "audio"))

    atomic_json(manifest_path, manifest)
    if args.dry_run:
        print(json.dumps({"dry_run": True, "tasks": len(task_ids), "profiles": len(profile_names), "planned": sum(job["status"] == "planned" for job in manifest["jobs"].values()), "cached": cached, "unavailable": unavailable, "manifest": str(manifest_path)}, indent=2))
        return

    completed = 0
    failed = 0
    with ThreadPoolExecutor(max_workers=min(args.max_workers, max(1, len(pending)))) as executor:
        futures = {executor.submit(run_job, adapter, job_credentials, rewrite, audio_base, args.retries, not args.skip_content_qc): job_id for job_id, adapter, job_credentials, rewrite, audio_base in pending}
        for future in as_completed(futures):
            job_id = futures[future]
            result = future.result()
            if result.get("file"):
                result["file"] = str(Path(result["file"]).relative_to(output_dir))
            manifest["jobs"][job_id]["status"] = result["status"]
            manifest["jobs"][job_id]["result"] = result
            if result["status"] == "ok":
                completed += 1
            else:
                failed += 1
            atomic_json(manifest_path, manifest)
            print(f"{result['status'].upper():5} {job_id} ({result['elapsed_seconds']}s)", flush=True)

    statuses = [job["status"] for job in manifest["jobs"].values()]
    failures = statuses.count("error") + statuses.count("rewrite_error")
    summary = {
        "tasks": len(task_ids),
        "profiles": len(profile_names),
        "ok": statuses.count("ok"),
        "cached": cached,
        "failed": failures,
        "unavailable": statuses.count("unavailable"),
        "manifest": str(manifest_path),
    }
    manifest["summary"] = summary
    manifest["updated_at_unix"] = int(time.time())
    atomic_json(manifest_path, manifest)
    print(json.dumps(summary, indent=2))
    raise SystemExit(1 if failures else 0)


if __name__ == "__main__":
    main()