Download scripts/qc_batch.py from TTS-AGI/speech-performance-arena: direct link, hf CLI and curl.
- Browser
- Download file 7.09 kB
-
https://huggingface.co/spaces/TTS-AGI/speech-performance-arena/resolve/main/scripts/qc_batch.py
- Command line
-
hf download hf://spaces/TTS-AGI/speech-performance-arena/scripts/qc_batch.py
-
curl -L -o qc_batch.py https://huggingface.co/spaces/TTS-AGI/speech-performance-arena/resolve/main/scripts/qc_batch.py
7.09 kB
| #!/usr/bin/env python3 | |
| """Audit every generated clip in a batch manifest; optionally transcribe it.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| 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.generation import atomic_json, probe_audio # noqa: E402 | |
| from voice_acting_rewriter.quality import assess_clip, signal_metrics # noqa: E402 | |
| _TRANSCRIBER: Any = None | |
| def transcribe(path: Path, *, timeout: int = 90) -> str: | |
| from gradio_client import Client, handle_file | |
| global _TRANSCRIBER | |
| token = os.environ.get("HF_TOKEN", "").strip() | |
| token_path = Path.home() / ".cache/huggingface/token" | |
| if not token and token_path.exists(): | |
| token = token_path.read_text(encoding="utf-8").strip() | |
| if _TRANSCRIBER is None: | |
| _TRANSCRIBER = Client(os.environ.get("ASR_SPACE_ID", ""), token=token or None, verbose=False) | |
| job = _TRANSCRIBER.submit(audio=handle_file(str(path)), task="transcribe", api_name="/transcribe") | |
| result = job.result(timeout=timeout) | |
| if not isinstance(result, str): | |
| raise RuntimeError(f"unexpected transcription result: {result!r}") | |
| return result.strip() | |
| def render_markdown(report: dict[str, Any]) -> str: | |
| summary = report["summary"] | |
| lines = [ | |
| "# Generation QC report", | |
| "", | |
| f"Coverage: {summary['checked']} checked; {summary['pass']} pass, " | |
| f"{summary['warn']} warning, {summary['fail']} fail, {summary['missing']} missing.", | |
| "", | |
| "Warnings require inspection but do not automatically disqualify expressive speech.", | |
| "", | |
| "| Job | Status | Duration | WPS | ASR WER | Signal | Findings |", | |
| "|---|---:|---:|---:|---:|---|---|", | |
| ] | |
| for job in report["clips"]: | |
| probe = job.get("probe", {}) | |
| signal = job.get("signal", {}) | |
| assessment = job.get("assessment", {}) | |
| findings = assessment.get("failures", []) + assessment.get("warnings", []) | |
| rms = signal.get("rms_dbfs") | |
| clipping = signal.get("clipped_sample_fraction") | |
| signal_text = f"RMS {rms} dBFS; clip {clipping}" if rms is not None else "—" | |
| lines.append( | |
| f"| {job['job_id']} | {job['status']} | {probe.get('duration_seconds', '—')}s | " | |
| f"{assessment.get('words_per_second', '—')} | {assessment.get('asr_word_error_rate', '—')} | " | |
| f"{signal_text} | {', '.join(findings) or '—'} |" | |
| ) | |
| return "\n".join(lines) + "\n" | |
| def audit_manifest( | |
| manifest_path: Path, | |
| pool_path: Path | None, | |
| *, | |
| use_asr: bool = False, | |
| asr_timeout: int = 90, | |
| ) -> dict[str, Any]: | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| if pool_path: | |
| pool = json.loads(pool_path.read_text(encoding="utf-8")) | |
| tasks = {task["id"]: task for task in pool["tasks"]} | |
| else: | |
| task = manifest["task"] | |
| tasks = {task["id"]: task} | |
| jobs = manifest.get("jobs") | |
| if jobs is None: | |
| task_id = manifest["task"]["id"] | |
| jobs = { | |
| f"{task_id}/{result['provider']}": { | |
| "task_id": task_id, | |
| "profile_name": result["provider"], | |
| "status": result["status"], | |
| "result": {"file": result["file"]}, | |
| } | |
| for result in manifest.get("results", []) | |
| } | |
| clips: list[dict[str, Any]] = [] | |
| for job_id, job in sorted(jobs.items()): | |
| item: dict[str, Any] = {"job_id": job_id, "task_id": job.get("task_id"), "profile_name": job.get("profile_name")} | |
| if job.get("status") != "ok" or not job.get("result", {}).get("file"): | |
| item.update(status="missing", reason=f"generation status is {job.get('status', 'absent')}") | |
| clips.append(item) | |
| continue | |
| audio_path = manifest_path.parent / job["result"]["file"] | |
| try: | |
| probe = probe_audio(audio_path) | |
| signal = signal_metrics(audio_path) | |
| transcript = None | |
| asr_error = None | |
| if use_asr: | |
| cache_dir = manifest_path.parent / ".asr-cache" | |
| cache_path = cache_dir / f"{probe['sha256']}.txt" | |
| if cache_path.exists(): | |
| transcript = cache_path.read_text(encoding="utf-8").strip() | |
| else: | |
| try: | |
| transcript = transcribe(audio_path, timeout=asr_timeout) | |
| cache_dir.mkdir(parents=True, exist_ok=True) | |
| cache_path.write_text(transcript + "\n", encoding="utf-8") | |
| except Exception as error: | |
| asr_error = f"{type(error).__name__}: {error}" | |
| task = tasks[job["task_id"]] | |
| script_value = task["script"] | |
| script = script_value["text"] if isinstance(script_value, dict) else script_value | |
| assessment = assess_clip(probe=probe, signal=signal, script=script, transcript=transcript) | |
| if asr_error: | |
| assessment["warnings"].append("asr_unavailable") | |
| assessment["status"] = "warn" | |
| item.update(status=assessment["status"], file=job["result"]["file"], probe=probe, signal=signal, assessment=assessment) | |
| if transcript is not None: | |
| item["transcript"] = transcript | |
| if asr_error: | |
| item["asr_error"] = asr_error | |
| except Exception as error: | |
| item.update(status="fail", error=f"{type(error).__name__}: {error}") | |
| clips.append(item) | |
| counts = {status: sum(item["status"] == status for item in clips) for status in ("pass", "warn", "fail", "missing")} | |
| return { | |
| "qc_schema_version": "0.1.0", | |
| "manifest": str(manifest_path.resolve()), | |
| "pool": str(pool_path.resolve()) if pool_path else None, | |
| "asr_enabled": use_asr, | |
| "summary": {"checked": len(clips), **counts}, | |
| "clips": clips, | |
| } | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("manifest", type=Path) | |
| parser.add_argument("pool", type=Path, nargs="?", help="task pool; optional when the manifest embeds one task") | |
| parser.add_argument("--asr", action="store_true", help="transcribe with the configured Whisper Space") | |
| parser.add_argument("--asr-timeout", type=int, default=90, help="maximum seconds per ASR job") | |
| parser.add_argument("--output", type=Path, help="defaults to qc.json beside the manifest") | |
| args = parser.parse_args() | |
| output = args.output or args.manifest.parent / "qc.json" | |
| report = audit_manifest(args.manifest, args.pool, use_asr=args.asr, asr_timeout=args.asr_timeout) | |
| atomic_json(output, report) | |
| output.with_suffix(".md").write_text(render_markdown(report), encoding="utf-8") | |
| print(json.dumps(report["summary"], indent=2)) | |
| raise SystemExit(1 if report["summary"]["fail"] or report["summary"]["missing"] else 0) | |
| if __name__ == "__main__": | |
| main() | |