Skip to content

Evaluation scripts for the Open TTS Leaderboard: https://huggingface.co/spaces/hf-audio/open_tts_leaderboard

Python

Add optional Korean KOMOS evaluation (#26)

Sangchun Ha5257fe601ad1
diff --git a/README.md b/README.md
index adad334..007c024 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@ While human preference is the ultimate decider, **arenas cannot scale to keep up
1. **Intelligibility**: word/character error rate (WER and CER) between the target text and the generated audio's transcript, using [Qwen3 ASR](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) (top ranking open-source model on the [Open ASR Leaderboard](https://huggingface.co/spaces/hf-audio/open_asr_leaderboard)).
2. **Speed**: inverse real-time factor (RTFx) for batched offline inference on an H200 GPU, and time-to-first-audio (TTFA) for quantifying streaming batch size 1 latency on an A100 GPU and CPU.
3. **Speaker similarity** by computing the cosine similarity (SIM) between [WavLM speaker embeddings](https://huggingface.co/bezzam/wavlm_large_finetune_seed_tts_eval) of the generated audio and the reference clip. Note that not all models support voice cloning, so those models are omitted from this evaluation.
-4. **Naturalness**: predicted MOS (1-5) with [UTMOS22 strong](https://github.com/tarepan/SpeechMOS) (UTMOS). UTMOS22 is trained on English only, so it is reported for `en` only.
+4. **Naturalness**: predicted MOS (1-5) with [UTMOS22 strong](https://github.com/tarepan/SpeechMOS) (UTMOS). UTMOS22 is trained on English only, so it is reported for `en` only. An optional [KOMOS](https://github.com/upskyy/komos) pilot reports Korean predicted MOS for `ko`.
By relying on objective metrics **evaluating a model drops from a couple weeks (for collecting votes) to a couple hours** ⚡
@@ -108,7 +108,7 @@ facebook/seamless-m4t-v2-large: RTFx = 21.19
Each model family has its own folder (e.g. [kokoro/](kokoro/), [voxcpm2/](voxcpm2/), [transformers/](transformers/)) with a `submit_jobs.sh` that is run **locally** and submits HF Jobs to HF servers. The orchestration shared by all backends lives in [scripts/tts_jobs_common.sh](scripts/tts_jobs_common.sh).
-For each (model, dataset split) pair, the pipeline runs four sequential HF Jobs (three if the model is not voice cloning), followed by scoring on your machine. The splits of a model run in parallel; models run one after another.
+For each (model, dataset split) pair, the pipeline runs four sequential HF Jobs (three if the model is not voice cloning), followed by scoring on your machine. An opt-in `komos` job can also score Korean audio. The splits of a model run in parallel; models run one after another.
```mermaid
flowchart LR
@@ -122,6 +122,7 @@ flowchart LR
asr["<b>2. Transcribe</b><br/>Qwen3-ASR · L4"]
sim["<b>3. Speaker similarity</b><br/>WavLM-SV · L4"]
utmos["<b>4. UTMOS</b><br/>UTMOS22 · L4"]
+ komos["<b>Optional: KOMOS</b><br/>Korean MOS · L4"]
end
ds[("Private datasets<br/>seed_tts_eval / cv3_eval")]
@@ -129,11 +130,13 @@ flowchart LR
submit --> gen --> asr -->|voice cloning only| sim --> utmos
asr --> utmos
+ asr -->|optional, Korean only| komos
ds --> gen
gen -->|wavs + manifest| bucket
asr <-->|pred_text| bucket
sim <-->|sim| bucket
utmos -->|UTMOS_*.json| bucket
+ komos -->|KOMOS_*.json| bucket
bucket -->|manifests only| score
```
@@ -141,13 +144,15 @@ flowchart LR
2. **Transcribe** (`transcribe`): [transformers/transcribe.py](transformers/transcribe.py) transcribes the wavs with [Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf), using the split's language as a hint.
3. **Speaker similarity** (`sim`, voice cloning only): [transformers/score_similarity.py](transformers/score_similarity.py) compares each generated clip with its reference prompt, using the [Seed TTS Eval](https://github.com/BytedanceSpeech/seed-tts-eval#metrics) speaker-verification model (WavLM-large + ECAPA-TDNN, mirrored [here](https://huggingface.co/bezzam/wavlm_large_finetune_seed_tts_eval)).
4. **UTMOS** (`utmos`, `UTMOS_LANGS` only): [transformers/score_utmos.py](transformers/score_utmos.py) predicts a MOS for each wav with UTMOS22 strong.
-5. **Score** (on your machine): the model's manifests are synced to `./results/<model>` and scored per language:
+5. **KOMOS** (`komos`, optional, Korean only): [transformers/score_komos.py](transformers/score_komos.py) scores Korean audio with `komos==0.0.2` and a pinned checkpoint in an isolated environment.
+6. **Score** (on your machine): the model's manifests are synced to `./results/<model>` and scored per language:
- **WER** after text normalization (CER for `zh`, `ja`, `ko`)
- **RTFx**: total audio duration divided by total generation time, measured in stage 1
- **SIM**: mean speaker similarity, for voice cloning only
- **UTMOS**: mean predicted MOS
+ - **KOMOS**: Korean-only mean over successfully scored files, with coverage and model provenance; no composite average
-The stages are separate jobs because the TTS, ASR and speaker-similarity models have conflicting dependencies: stage 1 uses the backend's own Docker Space image, and stages 2-4 share [bezzam/evals](https://huggingface.co/spaces/bezzam/evals).
+The stages are separate jobs because the TTS, ASR and speaker-similarity models have conflicting dependencies: stage 1 uses the backend's own Docker Space image, and stages 2-4 share [bezzam/evals](https://huggingface.co/spaces/bezzam/evals). The optional KOMOS job uses that image to create a fresh Python virtual environment and install `komos==0.0.2` (Python >=3.10, PyTorch 2.8.0 (CUDA 12.8 wheels, matching the shared image) and Transformers >=5.14.1,<5.17), leaving the other stages' dependencies unchanged. The job bootstraps `uv` to create the environment without requiring Ubuntu's optional `python3-venv` package.
| Stage | Flavor | Hardware |
|---|---|---|
@@ -155,6 +160,7 @@ The stages are separate jobs because the TTS, ASR and speaker-similarity models
| 2. Transcribe | `l4x1` | 1x Nvidia L4 (24 GB) |
| 3. Speaker similarity | `l4x1` | 1x Nvidia L4 (24 GB) |
| 4. UTMOS | `l4x1` | 1x Nvidia L4 (24 GB) |
+| Optional KOMOS | `l4x1` | 1x Nvidia L4 (24 GB); CPU supported via the local CLI |
RTFx is measured in stage 1, so every model is generated on the **same** flavor (`h200`); don't override `FLAVOR` in a backend. See the [HF Jobs documentation](https://huggingface.co/docs/huggingface_hub/main/en/guides/jobs#select-the-hardware) for pricing.
@@ -169,7 +175,7 @@ Useful environment variables (see [scripts/tts_jobs_common.sh](scripts/tts_jobs_
| `MAX_EVAL_SAMPLES` | `-1` (all) | Cap samples per split, e.g. `8` for a smoke test |
| `ONLY_LANGS` | (all) | Only run the configured splits for these languages, e.g. `"en zh"` |
| `ONLY_DATASETS` | (all) | Only run the configured splits of these dataset repos (name after the namespace), e.g. `"minimax_eval"` |
-| `STAGES` | `generate transcribe sim utmos` | Subset of stages, e.g. `"transcribe sim"` to re-score existing wavs |
+| `STAGES` | `generate transcribe sim utmos` | Subset of stages, e.g. `"transcribe sim"` to re-score existing wavs. Add the optional `komos` stage to score Korean (`ko`) outputs |
| `VOICE_CLONE` | `false` | Clone the prompt speaker (backends that support both modes) |
| `ASR_OVERWRITE` / `SIM_OVERWRITE` | `false` | Recompute `pred_text` / `sim` instead of resuming. SIM is always recomputed when `generate` runs; set `SIM_OVERWRITE=true` only to re-score existing audio with `STAGES="sim"` |
| `ORG_NAME` | (none) | Run the jobs under an organization's namespace |
diff --git a/normalizer/eval_utils.py b/normalizer/eval_utils.py
index 536f1c1..753de58 100644
--- a/normalizer/eval_utils.py
+++ b/normalizer/eval_utils.py
@@ -1,6 +1,8 @@
import os
import glob
import json
+import math
+from dataclasses import dataclass
import re
import unicodedata
from difflib import SequenceMatcher
@@ -210,6 +212,38 @@ def read_utmos(manifest_path: str, manifest: list):
return round(sum(vals) / len(vals), 3) if vals else None
+# KOMOS is a Korean-only diagnostic; it never enters composite/ranking averages.
+KOMOS_LANGUAGES = {"ko"}
+
+
+@dataclass(frozen=True, slots=True)
+class KomosResult:
+ """Per-manifest MOS, coverage and serialized scoring provenance."""
+
+ score: float | None = None
+ count: int = 0
+ model: str | None = None
+
+
+def read_komos(manifest_path: str, manifest: list) -> KomosResult:
+ """Read a KOMOS sidecar, matching the plain or SIM-fork manifest's audio rows."""
+ stem = os.path.basename(manifest_path).removesuffix(".jsonl")
+ for suffix in SIM_BACKEND_SUFFIXES:
+ stem = stem.removesuffix(f"_{suffix}")
+ sidecar = os.path.join(os.path.dirname(manifest_path), f"KOMOS_{stem}.json")
+ if not os.path.exists(sidecar):
+ return KomosResult()
+ with open(sidecar, encoding="utf-8") as source:
+ data = json.load(source)
+ values = [data["scores"].get(row.get("audio_filepath")) for row in manifest]
+ valid = [float(v) for v in values
+ if type(v) in (int, float) and math.isfinite(v) and 1 <= v <= 5]
+ return KomosResult(
+ round(sum(valid) / len(valid), 3) if valid else None,
+ len(valid), json.dumps(data["komos_model"], sort_keys=True),
+ )
+
+
def score_results(directory: str, model_id: str = None, multilingual: bool = None, csv_only: bool = False, language: str = "en", manifests: list = None, sim_backend: str = "wavlm_seed_tts"):
"""
Scores all result files in a directory and returns a composite score over all evaluated datasets.
@@ -360,6 +394,7 @@ def score_results(directory: str, model_id: str = None, multilingual: bool = Non
sims = [datum["sim"] for datum in manifest if isinstance(datum.get("sim"), (int, float))]
sim = round(100 * sum(sims) / len(sims), 2) if sims else None
utmos = read_utmos(result_file, manifest) if language in UTMOS_LANGUAGES else None
+ komos = read_komos(result_file, manifest) if language in KOMOS_LANGUAGES else KomosResult()
if use_cer:
# Per-character alignment (merge_compounds is moot). The headline CJK number is the
@@ -416,7 +451,7 @@ def score_results(directory: str, model_id: str = None, multilingual: bool = Non
extra = {"ins": total_ins, "del": total_del, "sub": total_sub}
# `wer` holds the headline error rate; `metric` says whether it is a WER or a CER. For CJK
# it is the lenient CER, with `cer_unnormalized` the seed-tts-eval-comparable number.
- results[result_key] = {"wer": wer, "metric": "CER" if use_cer or per_char else "WER", "cer_unnormalized": cer_unnormalized, "audio_length": audio_length, "inference_time": inference_time, "rtfx": rtfx, "sim": sim, "utmos": utmos, **extra}
+ results[result_key] = {"wer": wer, "metric": "CER" if use_cer or per_char else "WER", "cer_unnormalized": cer_unnormalized, "audio_length": audio_length, "inference_time": inference_time, "rtfx": rtfx, "sim": sim, "utmos": utmos, "komos": komos.score, "komos_count": komos.count, "komos_model": komos.model, **extra}
# Name the manifests whose SIM was dropped, even under csv_only, so a blank SIM is explained.
if stale_sim_files:
@@ -442,6 +477,9 @@ def score_results(directory: str, model_id: str = None, multilingual: bool = Non
metrics += f", SIM = {v['sim']:0.2f} %"
if v.get("utmos") is not None:
metrics += f", UTMOS = {v['utmos']:0.3f}"
+ if v.get("komos") is not None:
+ metrics += f", KOMOS = {v['komos']:0.3f} ({v['komos_count']} files)"
+ metrics += f", KOMOS model = {v['komos_model']}"
print(metrics)
# composite WER should be computed over all datasets and with the same key
diff --git a/scripts/open_results_pr.py b/scripts/open_results_pr.py
index 29d487b..4294b9d 100644
--- a/scripts/open_results_pr.py
+++ b/scripts/open_results_pr.py
@@ -64,7 +64,7 @@ sys.path.insert(0, REPO_ROOT) # so `from normalizer import ...` resolves regard
from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download # noqa: E402
-from normalizer.eval_utils import SIM_BACKEND_SUFFIXES, UTMOS_COLUMN_LANGUAGES, default_multilingual, score_results # noqa: E402
+from normalizer.eval_utils import SIM_BACKEND_SUFFIXES, UTMOS_COLUMN_LANGUAGES, KOMOS_LANGUAGES, default_multilingual, score_results # noqa: E402
# Where the results live, and where they are published.
RESULTS_BUCKET = "hf-audio/tts_leaderboard_h200"
@@ -358,6 +358,8 @@ def collect_values(target, header_languages, records, scored, scored_xvector):
values[f"{language} SIM"] = fmt(result["sim"])
if result.get("utmos") is not None:
values[f"{language} UTMOS"] = fmt(result["utmos"])
+ if language in KOMOS_LANGUAGES and result.get("komos") is not None:
+ values[f"{language} KOMOS"] = fmt(result["komos"])
if target.xvector_sim:
legacy = scored_xvector.get(dataset_id)
if legacy is not None and legacy.get("sim") is not None:
@@ -471,6 +473,13 @@ def add_utmos_columns(published, languages):
return extend_header(published, header)
+def add_komos_columns(published, languages):
+ """Append the Korean KOMOS column without adding an average."""
+ columns = [f"{lang} KOMOS" for lang in languages if lang in KOMOS_LANGUAGES]
+ missing = [column for column in columns if column not in published.header]
+ return extend_header(published, published.header + missing) if missing else published
+
+
def add_note_column(published):
"""Append the `Note` column to a header without one."""
if NOTE_COLUMN in published.header:
@@ -630,6 +639,7 @@ def main():
help="Where to sync results (default: <repo>/results, same place submit_jobs.sh uses).",
)
parser.add_argument("--utmos_bucket", default=None, help="Bucket with the UTMOS sidecars (default: --bucket).")
+ parser.add_argument("--komos_bucket", default=None, help="Bucket with KOMOS sidecars (default: --bucket).")
parser.add_argument("--skip_sync", action="store_true", help="Score already-downloaded results.")
parser.add_argument(
"--clean",
@@ -696,6 +706,8 @@ def main():
sys.exit(1)
if args.utmos_bucket:
sync_bucket(args.utmos_bucket, model_folder, local_dir, args.hf_token, include="UTMOS_*.json")
+ if args.komos_bucket:
+ sync_bucket(args.komos_bucket, model_folder, local_dir, args.hf_token, include="KOMOS_*.json")
if not os.path.isdir(model_dir):
print(f"ERROR: no results directory for {args.model_id}: {model_dir}", file=sys.stderr)
sys.exit(1)
@@ -781,6 +793,8 @@ def main():
continue
if any(column.endswith(" UTMOS") for column in values):
published = add_utmos_columns(published, languages)
+ if any(column.endswith(" KOMOS") for column in values):
+ published = add_komos_columns(published, languages)
# An empty --note only clears an existing note; it never adds the column.
extra = {}
if args.note:
diff --git a/scripts/tts_jobs_common.sh b/scripts/tts_jobs_common.sh
index 40369ea..00cc990 100644
--- a/scripts/tts_jobs_common.sh
+++ b/scripts/tts_jobs_common.sh
@@ -48,6 +48,7 @@ FLAVOR="${FLAVOR:-h200}"
# Stage 2/3 flavors are not timed (WER/SIM are hardware-independent), so a cheaper GPU is fine.
ASR_FLAVOR="${ASR_FLAVOR:-l4x1}" # stage 2 flavor
SIM_FLAVOR="${SIM_FLAVOR:-l4x1}" # stage 3 flavor
+KOMOS_FLAVOR="${KOMOS_FLAVOR:-l4x1}" # optional Korean MOS stage
UTMOS_FLAVOR="${UTMOS_FLAVOR:-l4x1}" # stage 4 flavor
MAX_EVAL_SAMPLES="${MAX_EVAL_SAMPLES:--1}" # -1 = all; set e.g. 8 to smoke-test
# Restrict a run to some of the backend's DATASET_CONFIGS: space-separated asr_language codes
@@ -76,11 +77,13 @@ ASR_OVERWRITE="${ASR_OVERWRITE:-false}"
UTMOS_OVERWRITE="${UTMOS_OVERWRITE:-false}"
# Languages (asr_language) that get stage 4; keep in sync with UTMOS_LANGUAGES in normalizer/eval_utils.py.
UTMOS_LANGS="${UTMOS_LANGS:-en}"
-MAX_AUDIO_SECONDS="${MAX_AUDIO_SECONDS:-30}" # clip cap for ASR + SIM + UTMOS (0 = no cap)
+# Same for the optional `komos` stage, which only runs on Korean (ko) splits.
+KOMOS_OVERWRITE="${KOMOS_OVERWRITE:-false}"
+MAX_AUDIO_SECONDS="${MAX_AUDIO_SECONDS:-30}" # clip cap for ASR + SIM + UTMOS + KOMOS (0 = no cap)
# Clone each sample's prompt speaker (+ SIM stage) on backends that support it; false = the model's
# own fixed/default voice. Ignored by fixed-voice backends.
VOICE_CLONE="${VOICE_CLONE:-false}"
-# Which stages to run (subset of: generate transcribe sim utmos). Skip generate to re-score the
+# Which stages to run (subset of: generate transcribe sim utmos komos). Skip generate to re-score the
# bucket's existing wavs, e.g. STAGES="transcribe sim" or STAGES="sim". Precedence (resolved in
# run_pipeline): user env STAGES > backend DEFAULT_STAGES > "generate transcribe sim utmos".
@@ -139,6 +142,8 @@ TRANSCRIBE_INJECT="$(inject_cmd "${REPO_ROOT}/transformers/transcribe.py" /app/t
SIM_INJECT="$(inject_cmd "${REPO_ROOT}/transformers/score_similarity.py" /app/transformers/score_similarity.py)"
UTMOS_INJECT="$(inject_cmd "${REPO_ROOT}/transformers/score_utmos.py" /app/transformers/score_utmos.py)"
+KOMOS_INJECT="$(inject_cmd "${REPO_ROOT}/transformers/score_komos.py" /app/transformers/score_komos.py)"
+
# ── Default hooks (backends override as needed) ─────────────────────────────
# voice_clone_mode [suffix_prefix] — sets CLONE / MODE_SUFFIX / VOICE_CLONE_FLAG from VOICE_CLONE.
# A backend variant that shares a model id passes its own prefix (e.g. "_rl"), so MODE_SUFFIX
@@ -261,6 +266,23 @@ utmos_stage() {
"
}
+# Separate job/environment: KOMOS requires Transformers 5 and must not change UTMOS/ASR deps.
+komos_stage() {
+ local KOMOS_OVERWRITE_FLAG=""
+ { [[ "${KOMOS_OVERWRITE}" == "true" ]] || stage_enabled generate; } && KOMOS_OVERWRITE_FLAG=" --overwrite"
+ hf jobs run \
+ --flavor "${KOMOS_FLAVOR}" --timeout 4h --secrets HF_TOKEN ${NAMESPACE_ARG} \
+ --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${SCORER_IMAGE}" \
+ bash -c "
+ ${KOMOS_INJECT}
+ python -m pip install uv &&
+ uv venv --python python /tmp/komos-env &&
+ uv pip install --python /tmp/komos-env/bin/python 'torch==2.8.0' --index-url https://download.pytorch.org/whl/cu128 &&
+ uv pip install --python /tmp/komos-env/bin/python 'komos==0.0.2' &&
+ /tmp/komos-env/bin/python /app/transformers/score_komos.py --manifest_paths ${BUCKET_MANIFEST} --max_rows=${MAX_EVAL_SAMPLES} --max_audio_seconds=${MAX_AUDIO_SECONDS} --device=cuda:0${KOMOS_OVERWRITE_FLAG}
+ "
+}
+
# ── Wait for a model's chains, report failures, then sync + score locally ────
# Uses PIDS/TAGS/CHAIN_LOGS set by run_pipeline. Returns non-zero (and skips scoring) on failure.
_wait_and_score() {
@@ -303,6 +325,8 @@ _wait_and_score() {
[[ -s "./results/${MODEL_FOLDER}/${name}" ]] || missing+=("${name}")
stage_enabled utmos && utmos_language "${LANGS[$i]}" && [[ ! -s "./results/${MODEL_FOLDER}/UTMOS_${name%.jsonl}.json" ]] &&
missing+=("UTMOS_${name%.jsonl}.json")
+ stage_enabled komos && [[ "${LANGS[$i]}" == ko ]] && [[ ! -s "./results/${MODEL_FOLDER}/KOMOS_${name%.jsonl}.json" ]] &&
+ missing+=("KOMOS_${name%.jsonl}.json")
done
[[ ${#missing[@]} -eq 0 ]] && break
done
@@ -415,6 +439,7 @@ run_pipeline() {
stage_enabled transcribe && run_stage transcribe_stage
stage_enabled sim && [[ "${CLONE}" == "true" ]] && run_stage sim_stage
stage_enabled utmos && utmos_language "${ASR_LANG}" && run_stage utmos_stage
+ stage_enabled komos && [[ "${ASR_LANG}" == ko ]] && run_stage komos_stage
true # ensure subshell exit status is 0 when the last `&&` chain is a skipped stage
) > "${CHAIN_LOG}" 2>&1 &
PIDS+=("$!"); TAGS+=("${DATASET_PATH##*/}/${DATASET}/${SPLIT}"); CHAIN_LOGS+=("${CHAIN_LOG}")
diff --git a/transformers/score_komos.py b/transformers/score_komos.py
new file mode 100644
index 0000000..112e055
--- /dev/null
+++ b/transformers/score_komos.py
@@ -0,0 +1,205 @@
+# /// script
+# requires-python = ">=3.10"
+# dependencies = ["komos==0.0.2"]
+# ///
+# Run: uv run --script transformers/score_komos.py --manifest_paths <Korean manifest> --device cpu
+
+"""Resumable Korean MOS sidecars for the Open TTS Leaderboard.
+
+Run in a separate environment with komos==0.0.2. The generation manifest is
+read-only; scores and checkpoint/preprocessing provenance live in KOMOS_*.json.
+"""
+
+import argparse
+import json
+import math
+from dataclasses import dataclass
+from importlib.metadata import version
+from pathlib import Path
+from typing import Final, Protocol, TypedDict
+
+import numpy as np
+import soundfile as sf
+from numpy.typing import NDArray
+
+MODEL_ID: Final = "upskyy/komos"
+MODEL_REVISION: Final = "c558983b9777d4f01aa61003b151dea37db0cc2d"
+KOMOS_VERSION: Final = "0.0.2"
+MIN_AUDIO_SECONDS: Final = 0.1
+
+
+class ScoringModel(Protocol):
+ """KOMOS capability used by the manifest scorer."""
+
+ def score_long_form(self, audio: NDArray[np.float32], sr: int) -> float:
+ """Score a complete mono waveform up to the backend's 60-second limit."""
+ ...
+
+
+class Provenance(TypedDict):
+ model_id: str
+ revision: str
+ komos_version: str
+ method: str
+ max_audio_seconds: float
+ min_audio_seconds: float
+
+
+class Sidecar(TypedDict):
+ komos_model: Provenance
+ scores: dict[str, float | None]
+ errors: dict[str, str]
+
+
+@dataclass(frozen=True, slots=True)
+class ScoreOptions:
+ """Preprocessing, output and resume policy for one scoring run."""
+
+ output_dir: Path | None = None
+ max_rows: int = -1
+ overwrite: bool = False
+ save_every: int = 100
+ max_audio_seconds: float = 30.0
+
+ def __post_init__(self) -> None:
+ if self.save_every <= 0:
+ message = "save_every must be positive"
+ raise ValueError(message)
+ if (
+ not math.isfinite(self.max_audio_seconds)
+ or not 0 <= self.max_audio_seconds <= 60
+ ):
+ message = "max_audio_seconds must be between 0 (no clipping) and 60"
+ raise ValueError(message)
+
+
+def score_manifest(
+ model: ScoringModel, manifest_path: Path, options: ScoreOptions
+) -> Path:
+ """Resume per-file scoring without modifying a generation or ASR manifest."""
+ with manifest_path.open(encoding="utf-8") as source:
+ entries = [json.loads(line) for line in source if line.strip()]
+ if options.max_rows > 0:
+ entries = entries[: options.max_rows]
+ out_path = (
+ options.output_dir or manifest_path.parent
+ ) / f"KOMOS_{manifest_path.stem}.json"
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ provenance: Provenance = {
+ "model_id": MODEL_ID,
+ "revision": MODEL_REVISION,
+ "komos_version": KOMOS_VERSION,
+ "method": "score_long_form",
+ "max_audio_seconds": options.max_audio_seconds,
+ "min_audio_seconds": MIN_AUDIO_SECONDS,
+ }
+ scores: dict[str, float | None] = {}
+ errors: dict[str, str] = {}
+ if out_path.exists() and not options.overwrite:
+ previous = json.loads(out_path.read_text(encoding="utf-8"))
+ if previous.get("komos_model") != provenance:
+ message = f"{out_path}: scoring provenance changed; use --overwrite"
+ raise ValueError(message)
+ scores = previous["scores"]
+ errors = previous.get("errors", {})
+
+ def save() -> None:
+ """Atomically replace the sidecar so an interrupted save remains resumable."""
+ data: Sidecar = {"komos_model": provenance, "scores": scores, "errors": errors}
+ temporary = out_path.with_suffix(".json.tmp")
+ temporary.write_text(json.dumps(data, allow_nan=False), encoding="utf-8")
+ temporary.replace(out_path)
+
+ todo = dict.fromkeys(
+ e["audio_filepath"]
+ for e in entries
+ if e.get("audio_filepath") and e["audio_filepath"] not in scores
+ )
+ print(f"{manifest_path}: {len(todo)}/{len(entries)} rows to score -> {out_path}")
+ for n, rel in enumerate(todo, 1):
+ try:
+ with sf.SoundFile(manifest_path.parent / rel) as audio:
+ sr = audio.samplerate
+ frames = (
+ int(options.max_audio_seconds * sr)
+ if options.max_audio_seconds
+ else -1
+ )
+ speech = audio.read(
+ frames=frames, dtype="float32", always_2d=True
+ ).mean(axis=1)
+ except (OSError, sf.LibsndfileError) as exc:
+ errors[rel] = str(exc) # Missing/unreadable audio is retried on resume.
+ print(f" WARNING: could not load {rel}: {exc}")
+ else:
+ if len(speech) < MIN_AUDIO_SECONDS * sr:
+ scores[rel] = None
+ errors[rel] = "Audio shorter than 0.1 seconds"
+ else:
+ # Do not hide inference/device failures or silently truncate >60s with cap=0.
+ score = float(model.score_long_form(speech, sr=sr))
+ if not math.isfinite(score) or not 1 <= score <= 5:
+ save()
+ message = f"Invalid KOMOS score for {rel}: {score}"
+ raise ValueError(message)
+ scores[rel] = round(score, 6)
+ errors.pop(rel, None)
+ if n % options.save_every == 0:
+ save()
+ save()
+ valid = [
+ scores[e["audio_filepath"]]
+ for e in entries
+ if scores.get(e.get("audio_filepath")) is not None
+ ]
+ if valid:
+ print(
+ f" KOMOS = {sum(valid) / len(valid):.3f} over {len(valid)}/{len(entries)} rows"
+ )
+ return out_path
+
+
+def get_parser() -> argparse.ArgumentParser:
+ """Build the scorer CLI, following score_utmos.py's manifest/output flags."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--manifest_paths", type=Path, nargs="+", required=True)
+ parser.add_argument("--output_dir", type=Path, default=None)
+ parser.add_argument("--max_rows", type=int, default=-1)
+ parser.add_argument("--overwrite", action="store_true")
+ parser.add_argument("--save_every", type=int, default=100)
+ parser.add_argument(
+ "--max_audio_seconds",
+ type=float,
+ default=30.0,
+ help="Evaluate this prefix (<=60s); 0 scores full files up to 60s.",
+ )
+ parser.add_argument(
+ "--device", default="cpu", help="PyTorch device (default: cpu)."
+ )
+ return parser
+
+
+def main() -> None:
+ """Load one pinned checkpoint and score every requested Korean manifest."""
+ args = get_parser().parse_args()
+ options = ScoreOptions(
+ args.output_dir,
+ args.max_rows,
+ args.overwrite,
+ args.save_every,
+ args.max_audio_seconds,
+ )
+ if version("komos") != KOMOS_VERSION:
+ message = f"Install komos=={KOMOS_VERSION} to reproduce this scoring protocol"
+ raise RuntimeError(message)
+ from komos import KOMOS
+
+ model = (
+ KOMOS.from_pretrained(MODEL_ID, revision=MODEL_REVISION).to(args.device).eval()
+ )
+ for manifest_path in args.manifest_paths:
+ score_manifest(model, manifest_path, options)
+
+
+if __name__ == "__main__":
+ main()