minhanh29's picture
Add official standalone scorer + rewrite README (robustness, SEO, ZeroTTS links) (#3)
b982e77
Raw
History Blame Contribute Delete
15.4 kB
"""Self-contained metric implementations for ZeroBench-TTS.
No TTS model is ever loaded here — this module only reads finished wavs and
scores them:
WER two ASRs (openai/whisper-large-v3 + vinai/PhoWhisper-large), min taken,
against the expanded reference set from ``references.py``
SSIM cosine similarity of microsoft/wavlm-base-plus-sv x-vectors between
the generated clip and the benchmark's reference clip
UTMOS UTMOSv2 naturalness MOS (optional — see ``UTMOSScorer``)
SIL excess leading / trailing / mid-utterance silence, in seconds
Everything loads once per process and is reused across items.
"""
from __future__ import annotations
import re
import unicodedata
import numpy as np
DEFAULT_ASR = ("openai/whisper-large-v3", "vinai/PhoWhisper-large")
#: Reference policies, in reporting order. See ``score_all_policies``.
POLICIES = ("strict", "norm", "robust")
# ── text normalization + WER ──────────────────────────────────────────────────
def normalize_for_cer(text: str) -> str:
"""lowercase, NFC-normalize, strip punctuation, collapse whitespace."""
text = unicodedata.normalize("NFC", text.lower())
text = re.sub(r"[^\w\s]", "", text, flags=re.UNICODE)
text = re.sub(r"\s+", " ", text).strip()
return text
def _levenshtein_seq(a, b) -> int:
if a == b:
return 0
if not a:
return len(b)
if not b:
return len(a)
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i] + [0] * len(b)
for j, cb in enumerate(b, 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (0 if ca == cb else 1))
prev = cur
return prev[-1]
def word_error_rate(hyp: str, ref: str) -> float:
"""WER = edit_distance(words) / len(ref_words), clamped to [0, 1]. Callers
normalize with :func:`normalize_for_cer` first."""
ref_words, hyp_words = ref.split(), hyp.split()
if not ref_words:
return 0.0 if not hyp_words else 1.0
try:
import jiwer
m = jiwer.process_words(ref, hyp)
dist = m.substitutions + m.deletions + m.insertions
except ImportError:
dist = _levenshtein_seq(hyp_words, ref_words)
return float(min(max(dist / len(ref_words), 0.0), 1.0))
def score_wer_flat(pred: str, references: list[str]) -> tuple[float, str]:
"""min WER over an explicit list of whole-sentence references."""
hyp = normalize_for_cer(pred)
best, best_ref = 1.0, references[0] if references else ""
for ref in references:
if not ref:
continue
w = word_error_rate(hyp, normalize_for_cer(ref))
if w < best:
best, best_ref = w, ref
return best, best_ref
def score_all_policies(transcripts: dict[str, str], text: str,
text_normalized: str = "") -> dict:
"""WER of every ASR transcript under all three reference policies.
``transcripts`` maps an ASR label -> its transcript of the same clip.
Returns ``wer_<policy>`` (min across ASRs — the reported number),
``wer_<policy>_<asr>`` per ASR, and which ASR / reference won ``robust``.
"""
from .references import best_wer
normalized = text_normalized if text_normalized and text_normalized != text else ""
out: dict = {}
winners: dict[str, tuple[float, str, str]] = {}
for policy in POLICIES:
per_asr: dict[str, tuple[float, str]] = {}
for label, hyp in transcripts.items():
if policy == "strict":
wer, ref = score_wer_flat(hyp, [text])
elif policy == "norm":
wer, ref = score_wer_flat(hyp, [text] + ([normalized] if normalized else []))
else:
wer, ref = best_wer(hyp, text, [normalized] if normalized else [])
per_asr[label] = (wer, ref)
out[f"wer_{policy}_{label}"] = round(wer, 6)
label = min(per_asr, key=lambda k: per_asr[k][0])
wer, ref = per_asr[label]
out[f"wer_{policy}"] = round(wer, 6)
winners[policy] = (wer, ref, label)
out["wer"] = out["wer_robust"] # headline
out["wer_matched_reference"] = winners["robust"][1]
out["wer_matched_asr"] = winners["robust"][2]
return out
# ── ASR ───────────────────────────────────────────────────────────────────────
def asr_label(model_id: str) -> str:
"""Short, column-safe name for an ASR checkpoint."""
tail = model_id.split("/")[-1].lower()
if "phowhisper" in tail:
return "pho"
if "whisper-large-v3" in tail:
return "wlv3"
return re.sub(r"[^0-9a-z]+", "_", tail).strip("_")
class WhisperTranscriber:
"""Any Whisper-family checkpoint from `transformers`."""
def __init__(self, model_id: str = "openai/whisper-large-v3", device: str = "cuda"):
import torch
from transformers import WhisperForConditionalGeneration, WhisperProcessor
self.torch = torch
self.device = torch.device(device)
self.processor = WhisperProcessor.from_pretrained(model_id)
dtype = torch.float16 if self.device.type == "cuda" else torch.float32
self.model = (WhisperForConditionalGeneration
.from_pretrained(model_id, torch_dtype=dtype)
.to(self.device).eval())
for p in self.model.parameters():
p.requires_grad = False
def transcribe(self, wav_16k: np.ndarray, lang: str | None = "vi") -> str:
with self.torch.no_grad():
feats = self.processor(wav_16k, sampling_rate=16_000, return_tensors="pt")
feats = feats.input_features.to(self.device, dtype=self.model.dtype)
forced = (self.processor.get_decoder_prompt_ids(language=lang, task="transcribe")
if lang else None)
ids = self.model.generate(feats, forced_decoder_ids=forced, max_new_tokens=256)
return self.processor.batch_decode(ids, skip_special_tokens=True)[0].strip()
# ── speaker similarity ────────────────────────────────────────────────────────
class SSIMScorer:
"""Cosine similarity between WavLM-SV x-vectors of generated and reference audio."""
def __init__(self, model_id: str = "microsoft/wavlm-base-plus-sv", device: str = "cuda"):
import torch
from transformers import WavLMForXVector, Wav2Vec2FeatureExtractor
self.torch = torch
self.device = torch.device(device)
self.extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_id)
self.model = WavLMForXVector.from_pretrained(model_id).to(self.device).eval()
for p in self.model.parameters():
p.requires_grad = False
def embed(self, wav_16k: np.ndarray) -> np.ndarray:
with self.torch.no_grad():
inputs = self.extractor(wav_16k, sampling_rate=16_000, return_tensors="pt")
inputs = {k: v.to(self.device) for k, v in inputs.items()}
return self.model(**inputs).embeddings.squeeze(0).float().cpu().numpy()
def score(self, pred_wav_16k: np.ndarray, ref_wav_16k: np.ndarray) -> float:
a, b = self.embed(pred_wav_16k), self.embed(ref_wav_16k)
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-8))
# ── naturalness ───────────────────────────────────────────────────────────────
UTMOS_INSTALL_HINT = (
"UTMOSv2 is not installed. It is an optional dependency (WER and SSIM work "
"without it):\n"
" pip install git+https://github.com/sarulab-speech/UTMOSv2.git\n"
"Or pass --skip_utmos to report NaN for the UTMOS column."
)
class UTMOSScorer:
"""UTMOSv2 naturalness MOS. Optional — see :data:`UTMOS_INSTALL_HINT`.
UTMOSv2 ensembles over randomly sampled spectrogram crops, so an unseeded
call is NOT reproducible: scoring one clip three times in a row returns
e.g. 3.05 / 3.03 / 2.96. A benchmark number that moves between runs is not
a benchmark number, so the RNG is reset to ``seed`` before every clip. That
makes UTMOS a deterministic function of the audio, which is what lets two
people scoring the same wavs get the same figure.
"""
def __init__(self, device: str = "cuda", seed: int = 42):
try:
import utmosv2
except ImportError as e: # pragma: no cover
raise ImportError(UTMOS_INSTALL_HINT) from e
self.model = utmosv2.create_model(pretrained=True)
self.seed = seed
def _reseed(self) -> None:
import random
import torch
random.seed(self.seed)
np.random.seed(self.seed)
torch.manual_seed(self.seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(self.seed)
def score(self, wav_16k: np.ndarray) -> float:
self._reseed()
mos = self.model.predict(data=wav_16k, sr=16_000)
if hasattr(mos, "item"):
return float(mos.item())
if isinstance(mos, (list, np.ndarray)):
return float(mos[0])
return float(mos)
# ── silence hygiene (no model) ────────────────────────────────────────────────
class SilenceScorer:
"""How much *unwanted* silence a clip carries — long lead-in, long tail, long
internal pauses.
Nothing in WER/SSIM/UTMOS penalizes dead air: an ASR happily transcribes a
clip that opens with 1.5 s of nothing, the x-vector is unaffected, and UTMOS
rates the audio quality of silence as fine. ``librosa.effects.split`` gates
frame energy at ``top_db`` below the clip's own peak; whatever it drops is
silence. ``excess_silence`` ignores the silence a natural utterance is
allowed (``max_edge_sec`` per end, ``max_mid_sec`` per internal pause).
"""
def __init__(self, top_db: float = 35.0, frame_length: int = 1024,
hop_length: int = 256, max_edge_sec: float = 0.1,
max_mid_sec: float = 0.3):
self.top_db = top_db
self.frame_length = frame_length
self.hop_length = hop_length
self.max_edge_sec = max_edge_sec
self.max_mid_sec = max_mid_sec
def score(self, wav_16k: np.ndarray, sr: int = 16_000) -> dict:
import librosa
wav = np.asarray(wav_16k, dtype=np.float32).reshape(-1)
dur = len(wav) / sr
dead = {"lead_silence": dur, "trail_silence": 0.0, "max_mid_silence": 0.0,
"total_mid_silence": 0.0, "excess_silence": dur,
"speech_duration": 0.0, "duration": dur}
if (len(wav) < self.frame_length or not np.any(np.isfinite(wav))
or float(np.abs(wav).max()) <= 0.0):
return dead
intervals = librosa.effects.split(wav, top_db=self.top_db,
frame_length=self.frame_length,
hop_length=self.hop_length)
if len(intervals) == 0:
return dead
lead = float(intervals[0][0]) / sr
trail = float(len(wav) - intervals[-1][1]) / sr
gaps = [float(intervals[k][0] - intervals[k - 1][1]) / sr
for k in range(1, len(intervals))]
excess = (max(0.0, lead - self.max_edge_sec) + max(0.0, trail - self.max_edge_sec)
+ sum(max(0.0, g - self.max_mid_sec) for g in gaps))
return {
"lead_silence": lead, "trail_silence": trail,
"max_mid_silence": max(gaps) if gaps else 0.0,
"total_mid_silence": float(sum(gaps)),
"excess_silence": excess,
"speech_duration": float(sum(e - s for s, e in intervals)) / sr,
"duration": dur,
}
# ── audio io ──────────────────────────────────────────────────────────────────
def load_wav_16k(path: str) -> np.ndarray:
"""Read any wav as mono float32 at 16 kHz."""
import soundfile as sf
wav, sr = sf.read(str(path), dtype="float32", always_2d=False)
wav = np.asarray(wav, dtype=np.float32)
if wav.ndim > 1:
wav = wav.mean(axis=1)
return resample_to_16k(wav.reshape(-1), sr)
def resample_to_16k(wav: np.ndarray, sr: int) -> np.ndarray:
if sr == 16_000:
return wav.astype(np.float32)
try:
import torch
import torchaudio
t = torch.from_numpy(wav.astype(np.float32)).unsqueeze(0)
return torchaudio.functional.resample(t, sr, 16_000).squeeze(0).numpy()
except ImportError:
import librosa
return librosa.resample(wav.astype(np.float32), orig_sr=sr, target_sr=16_000)
# ── the bundle ────────────────────────────────────────────────────────────────
class MetricSuite:
"""Loads every scorer once. Instantiate a single time per process."""
def __init__(self, device: str = "cuda", asr_models=DEFAULT_ASR,
skip_utmos: bool = False, silence_top_db: float = 35.0,
silence_max_edge_sec: float = 0.1, silence_max_mid_sec: float = 0.3):
self.asr: dict[str, WhisperTranscriber] = {}
for model_id in asr_models:
print(f"[zerobench] loading ASR {model_id} ...", flush=True)
self.asr[asr_label(model_id)] = WhisperTranscriber(model_id, device=device)
print("[zerobench] loading SSIM (WavLM-SV) ...", flush=True)
self.ssim = SSIMScorer(device=device)
self.utmos = None
if not skip_utmos:
print("[zerobench] loading UTMOS (UTMOSv2) ...", flush=True)
self.utmos = UTMOSScorer(device=device)
self.silence = SilenceScorer(top_db=silence_top_db,
max_edge_sec=silence_max_edge_sec,
max_mid_sec=silence_max_mid_sec)
def score(self, pred_wav_16k: np.ndarray, ref_wav_16k: np.ndarray,
text: str, text_normalized: str = "", lang: str = "vi") -> dict:
transcripts = {label: a.transcribe(pred_wav_16k, lang=lang)
for label, a in self.asr.items()}
sil = self.silence.score(pred_wav_16k, 16_000)
return {
**{f"transcript_{k}": v for k, v in transcripts.items()},
**score_all_policies(transcripts, text, text_normalized),
"ssim": self.ssim.score(pred_wav_16k, ref_wav_16k),
"utmos": self.utmos.score(pred_wav_16k) if self.utmos else float("nan"),
"excess_silence": sil["excess_silence"],
"lead_silence": sil["lead_silence"],
"trail_silence": sil["trail_silence"],
"max_mid_silence": sil["max_mid_silence"],
"duration_sec": len(pred_wav_16k) / 16_000,
}