File size: 6,453 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 | #!/usr/bin/env python3
"""Generate a balanced, resumable sparse task × TTS-system audio corpus."""
from __future__ import annotations
import argparse
import itertools
import json
import random
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_PROFILES = (
"gemini_3_1_flash_tts",
"eleven_v3",
"fish_s2_1_pro",
"minimax_speech_2_8_hd",
"cartesia_sonic_3_5",
"openai_gpt_4o_mini_tts",
"openai_gpt_audio_1_5",
"breeze_tts_2_voice_design",
"resemble_dramabox",
)
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("--systems-per-task", type=int, default=3)
parser.add_argument("--profile", action="append", dest="profiles")
parser.add_argument("--seed", type=int, default=20260913)
parser.add_argument("--profile-workers", type=int, default=3)
parser.add_argument("--provider-workers", type=int, default=2)
parser.add_argument("--retries", type=int, default=2)
parser.add_argument("--plan-only", action="store_true")
return parser.parse_args()
def balanced_plan(task_ids: list[str], profiles: list[str], width: int, seed: int) -> dict[str, list[str]]:
if not 2 <= width <= len(profiles):
raise ValueError("systems-per-task must be between 2 and the number of profiles")
rng = random.Random(seed)
model_counts = {profile: 0 for profile in profiles}
pair_counts = {pair: 0 for pair in itertools.combinations(sorted(profiles), 2)}
triples = list(itertools.combinations(profiles, width))
plan: dict[str, list[str]] = {}
shuffled_tasks = task_ids.copy()
rng.shuffle(shuffled_tasks)
for task_id in shuffled_tasks:
scored = []
for choice in triples:
pairs = [tuple(sorted(pair)) for pair in itertools.combinations(choice, 2)]
score = (
max(pair_counts[pair] for pair in pairs),
sum(pair_counts[pair] for pair in pairs),
max(model_counts[profile] for profile in choice),
sum(model_counts[profile] for profile in choice),
rng.random(),
)
scored.append((score, choice, pairs))
_, choice, pairs = min(scored, key=lambda item: item[0])
plan[task_id] = list(choice)
for profile in choice:
model_counts[profile] += 1
for pair in pairs:
pair_counts[pair] += 1
return {task_id: plan[task_id] for task_id in task_ids}
def run_profile(args: argparse.Namespace, profile: str, task_ids: list[str]) -> tuple[str, int]:
output = args.output_dir / profile
output.mkdir(parents=True, exist_ok=True)
command = [
sys.executable,
str(ROOT / "scripts/generate_batch.py"),
str(args.pool.resolve()),
str(args.keys.resolve()),
"--output-dir", str(output.resolve()),
"--profile", profile,
"--max-workers", str(args.provider_workers),
"--retries", str(args.retries),
]
if args.hypr_key_source:
command.extend(["--hypr-key-source", str(args.hypr_key_source.resolve())])
for task_id in task_ids:
command.extend(["--task-id", task_id])
with (output / "run.log").open("a", encoding="utf-8") as log:
result = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=False)
return profile, result.returncode
def main() -> None:
args = parse_args()
profiles = args.profiles or list(DEFAULT_PROFILES)
document = json.loads(args.pool.read_text(encoding="utf-8"))
task_ids = [task["id"] for task in document["tasks"]]
args.output_dir.mkdir(parents=True, exist_ok=True)
plan_path = args.output_dir / "plan.json"
if plan_path.exists():
plan_doc = json.loads(plan_path.read_text(encoding="utf-8"))
plan = plan_doc["assignments"]
if plan_doc["task_ids"] != task_ids or plan_doc["profiles"] != profiles:
raise SystemExit("existing plan does not match the requested corpus or profiles")
else:
plan = balanced_plan(task_ids, profiles, args.systems_per_task, args.seed)
model_counts = {profile: sum(profile in selected for selected in plan.values()) for profile in profiles}
pair_counts = {
" / ".join(pair): sum(set(pair) <= set(selected) for selected in plan.values())
for pair in itertools.combinations(sorted(profiles), 2)
}
plan_doc = {
"version": "0.1.0",
"pool": str(args.pool.resolve()),
"task_ids": task_ids,
"profiles": profiles,
"systems_per_task": args.systems_per_task,
"seed": args.seed,
"clip_count": len(task_ids) * args.systems_per_task,
"comparison_count": len(task_ids) * (args.systems_per_task * (args.systems_per_task - 1) // 2),
"model_counts": model_counts,
"pair_counts": pair_counts,
"assignments": plan,
}
plan_path.write_text(json.dumps(plan_doc, indent=2) + "\n", encoding="utf-8")
print(json.dumps({key: plan_doc[key] for key in ("clip_count", "comparison_count", "model_counts")}, indent=2), flush=True)
if args.plan_only:
return
tasks_by_profile = {profile: [task_id for task_id in task_ids if profile in plan[task_id]] for profile in profiles}
failures = []
with ThreadPoolExecutor(max_workers=args.profile_workers) as executor:
futures = {executor.submit(run_profile, args, profile, tasks): profile for profile, tasks in tasks_by_profile.items()}
for future in as_completed(futures):
profile, returncode = future.result()
print(f"PROFILE {profile} exit={returncode}", flush=True)
if returncode:
failures.append(profile)
summary = {"profiles": len(profiles), "failed_profiles": failures, "plan": str(plan_path)}
(args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
print(json.dumps(summary, indent=2))
raise SystemExit(1 if failures else 0)
if __name__ == "__main__":
main()
|