Evaluation scripts for the Open TTS Leaderboard: https://huggingface.co/spaces/hf-audio/open_tts_leaderboard
Python
Add indic-tiny-tts (Hindi, 22M) evaluation backend (#46)
Sulabhf48fe2323234
diff --git a/README.md b/README.mdindex 007c024..025b037 100644--- a/README.md+++ b/README.md@@ -152,7 +152,7 @@ flowchart LR- **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 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.+The stages are separate jobs because the TTS, ASR and speaker-similarity models have conflicting dependencies: stage 1 uses the backend's own image (usually a Docker Space, or a public registry image such as `pytorch/pytorch`), and stages 2-4 share [bezzam/evals](https://huggingface.co/spaces/bezzam/evals).| Stage | Flavor | Hardware ||---|---|---|@@ -231,9 +231,11 @@ Seamless is fast and batched, so most of each of its generation jobs (~1 min per> - make a new folder to evaluate the new model, linking it to a documentation page with usage> - use batch inference if possible, with max batch size of 32> - implement the TTFA probe if the model supports streaming-> - (if you give it permission to your HF account) make a Docker Space to run the model via HF Jobs, taking inspiration from one of the existing configurations [here](https://huggingface.co/collections/bezzam/tts-eval)+> - (if you give it permission to your HF account) make a Docker Space to run the model via HF Jobs, taking inspiration from one of the existing configurations [here](https://huggingface.co/collections/bezzam/tts-eval), or skip the Space if a public registry image plus a few `pip install`s is enough1. **Create the environment image.** Create a **public** [Docker Space](https://huggingface.co/new-space?sdk=docker) (HF Jobs can't pull private ones), e.g. `YOUR_USERNAME/evals-<backend>`, whose `Dockerfile` installs the model's dependencies. It only needs the Dockerfile; the eval scripts are injected at runtime. See the existing Spaces [here](https://huggingface.co/collections/bezzam/tts-eval). Models that run with `transformers` can instead be added to the [transformers/](transformers/) backend.++ **No Space needed for light dependencies.** If an existing public image on a Docker registry (e.g. `pytorch/pytorch` on Docker Hub) already has the heavy dependencies, skip the Space: pass that image to `hf jobs run` and `pip install` the remaining packages at the start of the job command. [indic-tiny-tts/submit_jobs.sh](indic-tiny-tts/submit_jobs.sh) is an example (`GEN_IMAGE` + `GEN_PIP_DEPS`). Use a Space when the install is slow or fragile (compiled extensions, system packages, pinned forks), so every job doesn't redo it.2. **Write `<backend>/run_eval.py`**, which evaluates one dataset split. The shared helpers in [scripts/run_eval_utils.py](scripts/run_eval_utils.py) handle the parts common to every backend, so the script mostly contains the model-specific code. It should:- synthesize the `text` column, cloning from `prompt_audio` / `prompt_text` when `--voice_clone` is set (off by default)- time generation only, after `--warmup_steps` untimed warm-up batches (default 2), so RTFx is fair@@ -242,7 +244,7 @@ Seamless is fast and batched, so most of each of its generation jobs (~1 min per[kokoro/run_eval.py](kokoro/run_eval.py) is a short fixed-voice example, and [voxcpm2/run_eval.py](voxcpm2/run_eval.py) is a voice-cloning example.3. **Write `<backend>/submit_jobs.sh`**, which sources [scripts/tts_jobs_common.sh](scripts/tts_jobs_common.sh) and then:- - sets `TTS_SPACE` (your Docker Space) and `RUN_EVAL_INJECT="$(inject_run_eval)"`+ - sets `TTS_SPACE` (your Docker Space), or its own registry image if it doesn't use a Space, and `RUN_EVAL_INJECT="$(inject_run_eval)"`- defines `generate_stage()`, the `hf jobs run` command for stage 1- sets `SUPPORTS_VOICE_CLONE=true` if the model can clone, and optionally defines `supports_language()` to skip splits the model can't synthesize- sets `DATASET_CONFIGS` and `MODEL_CONFIGS`, then calls `run_pipeline`diff --git a/indic-tiny-tts/run_eval.py b/indic-tiny-tts/run_eval.pynew file mode 100644index 0000000..8215ed6--- /dev/null+++ b/indic-tiny-tts/run_eval.py@@ -0,0 +1,141 @@+"""+TTS synthesis for the Open TTS Leaderboard (indic-tiny-tts Hindi backend, stage 1).++indic-tiny-tts-hindi (sulabhkatiyar/indic-tiny-tts-hindi) is a 22.5M-parameter single-language model+(Matcha-style flow-matching acoustic model + Vocos vocoder, 24 kHz, character input, no eSpeak). It is+not on PyPI and not loadable with `transformers`: the HF repo itself ships the runtime package+`indic_tiny_tts/`. This script downloads the repo at a pinned revision, puts the download directory on+`sys.path`, and loads `TinyTTS` in-process.++The model has two fixed voices (`female`, `male`) and no voice cloning, so only the default-voice+("no cloning") table applies: one voice per run (`--voice`, default `male`). There is no batch API, so+rows are processed serially (batch size 1). The raw dataset text goes straight to the model (its bundled+text normaliser spells out digits etc.); the leaderboard normaliser is applied at scoring time only.++Weights are CC-BY-4.0 (trained on AI4Bharat Rasa Hindi only); code and Vocos vocoder are MIT.+Known limitation: the front-end is Devanagari-only, so Latin tokens in the input (e.g. "5G", "3D" in+MiniMax Hindi) are dropped.++Stage 2 (`transformers/transcribe.py`) fills `pred_text` with Qwen3-ASR; stage 4+(`normalizer.eval_utils.score_results`, run locally) computes WER + RTFx. Fixed voice, so no SIM stage.+"""++import argparse+import os+import sys+import time++import numpy as np+import soundfile as sf+import torch+from huggingface_hub import snapshot_download+from tqdm import tqdm++from run_eval_utils import (+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,+ pending_batches, print_model_size, print_next_steps, set_seed, warm_up, wav_rel_path, write_entry,+)++# The released model's native sample rate (config.json "sample_rate"; checked against tts.sample_rate below).+SAMPLING_RATE = 24_000+# Only the files the runtime needs: skip the ONNX graphs, sample wavs and card images.+IGNORE_PATTERNS = ["onnx/*", "samples/*", "assets/*"]+++def load_model(args):+ """Download the pinned repo revision, import its bundled package from there, and build TinyTTS."""+ local_dir = snapshot_download(args.model_id, revision=args.revision, ignore_patterns=IGNORE_PATTERNS)+ # snapshot dirs are named after the resolved commit sha+ print(f"Model snapshot: {local_dir} (requested revision: {args.revision or 'default branch'})")+ if args.revision and len(args.revision) == 40 and os.path.basename(local_dir) != args.revision:+ raise RuntimeError(f"snapshot {os.path.basename(local_dir)} does not match requested revision {args.revision}")+ sys.path.insert(0, local_dir)+ from indic_tiny_tts import TinyTTS++ tts = TinyTTS.from_pretrained(local_dir, device=args.device)+ if tts.sample_rate != SAMPLING_RATE:+ raise RuntimeError(f"model sample rate {tts.sample_rate} != {SAMPLING_RATE}")+ if args.voice not in tts.voices:+ raise ValueError(f"unknown voice {args.voice!r}; choose from {sorted(tts.voices)}")+ return tts+++def main(args):+ if args.ttfa_probe != 0:+ raise SystemExit("--ttfa_probe is not implemented for this backend (non-streaming model).")+ set_seed(args.seed)++ tts = load_model(args)+ print(f"Loaded indic-tiny-tts ({args.model_id}, lang={tts.lang}, voice={args.voice}, device={tts.device})")+ print_model_size(tts.acoustic, tts.vocoder)++ is_cuda = tts.device.type == "cuda"++ def synth_one(text, seed):+ """Synthesize one text with the default pipeline (chunking + pauses included).+ Return (audio_1d_numpy, elapsed_s); elapsed covers the whole synthesize() call."""+ if is_cuda:+ torch.cuda.synchronize()+ start = time.perf_counter()+ audio = tts.synthesize(text, voice=args.voice, speed=args.speed, seed=seed)+ if is_cuda:+ torch.cuda.synchronize()+ elapsed = time.perf_counter() - start+ if audio.size == 0: # e.g. a text with nothing speakable (Latin-only); keep the row, as the other backends do+ print(f"WARNING: empty audio for text {text[:60]!r}")+ audio = np.zeros(1, dtype=np.float32)+ return audio.astype(np.float32, copy=False), elapsed++ # Layout: results/<model_safe>/{MODEL_<safe>_DATASET_<dsid>.jsonl, <dsid>/output_<id>.wav}.+ # Manifest paths are relative to model_dir so later stages resolve them wherever it is copied.+ paths = output_paths(args)+ model_dir, dataset_dir_name, manifest_path = paths.model_dir, paths.dataset_dir_name, paths.manifest_path++ dataset = load_tts_dataset(args)++ done_entries = load_done_entries(manifest_path, args.resume)+ manifest_file = open_manifest(manifest_path, done_entries)++ # Serial synthesis: one sample per "batch"; warm-up runs untimed on the first pending samples.+ starts = pending_batches(dataset, 1, done_entries, dataset_dir_name)+ warm_up(lambda batch: [synth_one(t, args.seed) for t in batch[args.text_column]], dataset, starts, 1, args.warmup_steps)+ set_seed(args.seed) # so warm-up does not shift the RNG stream of the timed run++ # ── Main loop: synthesize one sample at a time → write JSONL ─────────────+ for i in tqdm(starts, desc="Generating"):+ sample_id = dataset[i]["id"]+ text = dataset[i][args.text_column]++ # Store the path relative to model_dir (the manifest's dir); write to the full path.+ rel_path = wav_rel_path(dataset_dir_name, sample_id)+ path = os.path.join(model_dir, rel_path)++ # Per-call seed (base seed + dataset row index): deterministic and independent of --resume.+ audio, elapsed = synth_one(text, args.seed + i)+ sf.write(path, audio, SAMPLING_RATE)++ write_entry(manifest_file, manifest_entry(rel_path, len(audio) / SAMPLING_RATE, elapsed, text))+ manifest_file.flush()++ manifest_file.close()+ print("Results saved at path:", os.path.abspath(manifest_path))+ print_next_steps(voice_clone=False)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()++ parser.add_argument("--model_id", type=str, default="sulabhkatiyar/indic-tiny-tts-hindi", help="HF repo id of the model.")+ parser.add_argument("--revision", type=str, default=None,+ help="Model repo revision (full commit sha) to pin; submit_jobs.sh always passes one.")+ parser.add_argument("--voice", type=str, default="male", help="Built-in voice: 'female' or 'male'.")+ parser.add_argument("--speed", type=float, default=1.0, help="Speech speed multiplier.")+ add_common_args(parser)++ args = parser.parse_args()++ print("*" * 100)+ print(f"Generating TTS with {args.model_id} on {args.dataset_path} / {args.dataset} / {args.split}")+ print("*" * 100)++ main(args)diff --git a/indic-tiny-tts/submit_jobs.sh b/indic-tiny-tts/submit_jobs.shnew file mode 100755index 0000000..18326c2--- /dev/null+++ b/indic-tiny-tts/submit_jobs.sh@@ -0,0 +1,69 @@+#!/bin/bash+# HF Jobs TTS eval: indic-tiny-tts backend (Hindi, fixed voice -> 2 stages: generate -> transcribe -> score).+# Runs locally; submits HF Jobs. Usage:+# HF_TOKEN=hf_... RESULTS_BUCKET=YOUR_USERNAME/bucket [MODEL_REVISION=<full 40-char sha>] \+# bash indic-tiny-tts/submit_jobs.sh ["sulabhkatiyar/indic-tiny-tts-hindi"]+# Smoke test: add MAX_EVAL_SAMPLES=8 ONLY_LANGS=hi ONLY_DATASETS=minimax_eval+# Shared orchestration (stages 2/3, injection, logging, scoring) lives in scripts/tts_jobs_common.sh.+# Works on Linux and macOS bash 3.2 (no associative arrays).+source "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/scripts/tts_jobs_common.sh"++# ── Backend config ───────────────────────────────────────────────────────────+# Stage-1 environment: no Docker Space needed. The job runs on the public PyTorch image below and+# pip-installs the few eval-loop deps at job start (seconds). indic_tiny_tts itself is NOT pip-installed:+# run_eval.py downloads the pinned model repo and imports the package it ships (its deps: torch, numpy,+# safetensors, huggingface_hub).+GEN_IMAGE="${GEN_IMAGE:-pytorch/pytorch:2.7.1-cuda12.8-cudnn9-runtime}"+GEN_PIP_DEPS="${GEN_PIP_DEPS:-datasets soundfile tqdm huggingface_hub safetensors numpy}"+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability: don't override.+GEN_TIMEOUT="${GEN_TIMEOUT:-30m}" # 100 sentences of a 22M model take minutes; a hang must not burn H200 hours+DEFAULT_STAGES="generate transcribe" # fixed voice, Hindi: no SIM (no cloning), no UTMOS (English only)+RUN_EVAL_INJECT="$(inject_run_eval)"++# The model revision is pinned: a full 40-char commit sha of the HF model repo. MODEL_REVISION=main only+# with ALLOW_UNPINNED_REVISION=1 (smoke tests); the sha is recorded in the PR.+# Submitted revision: package version 0.1.0 of sulabhkatiyar/indic-tiny-tts-hindi (the public release).+MODEL_REVISION="${MODEL_REVISION:-e15ac436560eb24d115d47c0783f62f10a02d30a}"+if [[ ! "${MODEL_REVISION}" =~ ^[0-9a-f]{40}$ ]] && [[ "${ALLOW_UNPINNED_REVISION:-0}" != "1" ]]; then+ echo "indic-tiny-tts: set MODEL_REVISION to the full 40-char commit sha of the model repo (or ALLOW_UNPINNED_REVISION=1 for a throwaway run)." >&2+ exit 1+fi+# Built-in voice: 'female' or 'male'. One voice per run, one leaderboard row.+VOICE="${VOICE:-male}"+echo "indic-tiny-tts: revision=${MODEL_REVISION} voice=${VOICE} results bucket=${RESULTS_BUCKET}"++# Single-language (Hindi) model: skip every other split instead of burning a GPU job on garbage audio.+supports_language() { [[ "$1" == "hi" ]]; }++# ── Stage 1: TTS generation (the model synthesizes one sample at a time: no batch size) ──+generate_stage() {+ hf jobs run \+ --flavor "${FLAVOR}" --timeout "${GEN_TIMEOUT}" --secrets HF_TOKEN ${NAMESPACE_ARG} \+ --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${GEN_IMAGE}" \+ bash -c "+ ${RUN_EVAL_INJECT}+ pip install --no-cache-dir -q ${GEN_PIP_DEPS} &&+ cd /app/indic-tiny-tts && python run_eval.py \+ --model_id=${MODEL_ID} \+ --revision=${MODEL_REVISION} \+ --voice=${VOICE} \+ --dataset_path=${DATASET_PATH} \+ --dataset=${DATASET} \+ --split=${SPLIT} \+ --device=cuda:0 \+ --max_eval_samples=${MAX_EVAL_SAMPLES} &&+ mkdir -p /results &&+ cp -r results/${MODEL_SAFE} /results/+ "+}++# ── Datasets: "config split asr_language [dataset_path]". Hindi exists only in MiniMax (100 sentences). ──+DATASET_CONFIGS=(+ "tts hi hi ${MINIMAX_EVAL_PATH}"+)++# ── Models: "model_id" (CLI args override) ───────────────────────────────────+MODEL_CONFIGS=("sulabhkatiyar/indic-tiny-tts-hindi")+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")++run_pipelinediff --git a/normalizer/data_utils.py b/normalizer/data_utils.pyindex 67434ba..74861a7 100644--- a/normalizer/data_utils.py+++ b/normalizer/data_utils.py@@ -2,6 +2,7 @@ import reimport num2wordsfrom normalizer import EnglishTextNormalizer, BasicMultilingualTextNormalizer+from normalizer.hindi import normalize_hi_numbers_after, normalize_hi_numbers_beforeclass MultilingualNormalizer(BasicMultilingualTextNormalizer):@@ -37,8 +38,12 @@ class MultilingualNormalizer(BasicMultilingualTextNormalizer):def __call__(self, s, lang=None):if lang == "vi":s = self._normalize_vi_numbers(s)+ elif lang == "hi":+ s = normalize_hi_numbers_before(s)s = super().__call__(s)- if lang is not None:+ if lang == "hi":+ s = normalize_hi_numbers_after(s)+ elif lang is not None:s = self._normalize_numbers(s, lang)return sdiff --git a/normalizer/hindi.py b/normalizer/hindi.pynew file mode 100644index 0000000..7d42c08--- /dev/null+++ b/normalizer/hindi.py@@ -0,0 +1,95 @@+"""Hindi number words for WER scoring: num2words has no Hindi converter.++Number words follow num2words master (lang_HI.py).+"""++import re++_BELOW_100 = (+ "शून्य", "एक", "दो", "तीन", "चार",+ "पाँच", "छः", "सात", "आठ", "नौ",+ "दस", "ग्यारह", "बारह", "तेरह", "चौदह",+ "पंद्रह", "सोलह", "सत्रह", "अट्ठारह", "उन्नीस",+ "बीस", "इक्कीस", "बाईस", "तेईस", "चौबीस",+ "पच्चीस", "छब्बीस", "सत्ताईस", "अट्ठाईस", "उनतीस",+ "तीस", "इकत्तीस", "बत्तीस", "तैंतीस", "चौंतीस",+ "पैंतीस", "छत्तीस", "सैंतीस", "अड़तीस", "उनतालीस",+ "चालीस", "इकतालीस", "बयालीस", "तैंतालीस", "चौवालीस",+ "पैंतालीस", "छियालीस", "सैंतालीस", "अड़तालीस", "उनचास",+ "पचास", "इक्यावन", "बावन", "तिरेपन", "चौवन",+ "पचपन", "छप्पन", "सत्तावन", "अट्ठावन", "उनसठ",+ "साठ", "इकसठ", "बासठ", "तिरसठ", "चौंसठ",+ "पैंसठ", "छियासठ", "सड़सठ", "अड़सठ", "उनहत्तर",+ "सत्तर", "इकहत्तर", "बहत्तर", "तिहत्तर", "चौहत्तर",+ "पचहत्तर", "छिहत्तर", "सतहत्तर", "अठहत्तर", "उनासी",+ "अस्सी", "इक्यासी", "बयासी", "तिरासी", "चौरासी",+ "पचासी", "छियासी", "सतासी", "अट्ठासी", "नवासी",+ "नब्बे", "इक्यानवे", "बानवे", "तिरानवे", "चौरानवे",+ "पचानवे", "छियानवे", "सत्तानवे", "अट्ठानवे", "निन्यानवे",+)+_HIGH = (+ (100_000_000_000, "ख़रब"),+ (1_000_000_000, "अरब"),+ (10_000_000, "करोड़"),+ (100_000, "लाख"),+ (1_000, "हज़ार"),+)+# ASR spelling variants+_VARIANTS = {+ "सतानवे": "सत्तानवे",+ "उन्नासी": "उनासी",+ "अठहतर": "अठहत्तर",+ "सतहतर": "सतहत्तर",+ "छिहतर": "छिहत्तर",+ "पचहतर": "पचहत्तर",+ "चौहतर": "चौहत्तर",+ "तिहतर": "तिहत्तर",+ "बहतर": "बहत्तर",+ "इकहतर": "इकहत्तर",+ "उनहतर": "उनहत्तर",+ "अठावन": "अट्ठावन",+ "सतावन": "सत्तावन",+ "तिरपन": "तिरेपन",+ "छयालिस": "छियालीस",+ "चवालीस": "चौवालीस",+ "तैतालीस": "तैंतालीस",+ "छतीस": "छत्तीस",+ "बतीस": "बत्तीस",+ "इकतीस": "इकत्तीस",+ "अट्ठाइस": "अट्ठाईस",+ "सताइस": "सत्ताईस",+ "तेइस": "तेईस",+ "इकीस": "इक्कीस",+ "अठारह": "अट्ठारह",+ "छह": "छः",+ "पांच": "पाँच",+ "छे": "छः",+}++_DEV_DIGITS = "".join(chr(0x0966 + i) for i in range(10))+_D = "[0-9" + _DEV_DIGITS + "]"+# "10,000", "1,23,456", "1,234,567", but not "3,5"+_THOUSANDS = re.compile(f"(?<!{_D})(?:{_D}{{1,3}}(?:,{_D}{{2}})*,{_D}{{3}}|{_D}{{1,3}}(?:,{_D}{{3}})+)(?!,?{_D})")+++def cardinal(n):+ if n < 100:+ return _BELOW_100[n]+ if n < 1000:+ hundreds, rest = divmod(n, 100)+ return _BELOW_100[hundreds] + " सौ" + (" " + _BELOW_100[rest] if rest else "")+ value, word = next(item for item in _HIGH if n >= item[0])+ quotient, rest = divmod(n, value)+ return cardinal(quotient) + " " + word + (" " + cardinal(rest) if rest else "")+++def normalize_hi_numbers_before(text):+ # before punctuation is stripped+ text = _THOUSANDS.sub(lambda m: m.group().replace(",", ""), text)+ return text.replace("%", " प्रतिशत ")+++def normalize_hi_numbers_after(text):+ to_ascii = {ord(d): str(i) for i, d in enumerate(_DEV_DIGITS)}+ text = re.sub(_D + "+", lambda m: " " + cardinal(int(m.group().translate(to_ascii))) + " ", text)+ return " ".join(_VARIANTS.get(token, token) for token in text.split())