Download scripts/generate_batch.py from TTS-AGI/speech-performance-arena: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/spaces/TTS-AGI/speech-performance-arena/resolve/main/scripts/generate_batch.py
- Command line
-
hf download hf://spaces/TTS-AGI/speech-performance-arena/scripts/generate_batch.py
-
curl -L -o generate_batch.py https://huggingface.co/spaces/TTS-AGI/speech-performance-arena/resolve/main/scripts/generate_batch.py
10.4 kB
| #!/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() | |