"""Speaker-safe test-set evaluation with WER/CER breakdowns.""" from __future__ import annotations import json import random from collections import defaultdict from pathlib import Path from typing import Any from buddi_asr.data.manifest import read_manifest, resolve_audio_path from buddi_asr.errors import OptionalDependencyError from buddi_asr.metrics import score_pairs from buddi_asr.text.normalization import normalize_for_metrics def _device_and_dtype(torch: Any, requested: str) -> tuple[str, Any]: if requested == "auto": if torch.cuda.is_available(): return "cuda", torch.float16 if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): return "mps", torch.float32 return "cpu", torch.float32 if requested == "cuda": return requested, torch.float16 return requested, torch.float32 def stratified_sample(records: list[Any], limit: int, seed: int) -> list[Any]: """Take `limit` records, spread evenly across speakers, deterministically. Benchmarking a dozen checkpoints over a full test split costs GPU hours that buy no extra confidence, so the split gets subsampled. Sampling uniformly would let the loudest speaker dominate a small draw and would move the score for reasons that have nothing to do with the model, so take from each speaker in turn instead. Seeded, because a benchmark whose numbers shift between runs cannot be compared against anything. """ if limit <= 0 or limit >= len(records): return records by_speaker: dict[str, list[Any]] = defaultdict(list) for record in records: by_speaker[record.speaker_id].append(record) rng = random.Random(seed) queues = [] for speaker in sorted(by_speaker): group = by_speaker[speaker][:] rng.shuffle(group) queues.append(group) rng.shuffle(queues) picked: list[Any] = [] position = 0 while len(picked) < limit: available = [queue for queue in queues if position < len(queue)] if not available: break for queue in available: picked.append(queue[position]) if len(picked) == limit: break position += 1 return picked def evaluate_hf_model( model_path: str | Path, manifest_path: str | Path, output_dir: str | Path, *, device: str = "auto", max_new_tokens: int = 128, batch_size: int = 1, limit: int = 0, seed: int = 42, ) -> dict[str, Any]: try: import librosa import torch from transformers import WhisperForConditionalGeneration, WhisperProcessor except ImportError as exc: raise OptionalDependencyError( "Evaluation dependencies are missing. Install: python -m pip install -e '.[train]'" ) from exc model_location = str(model_path) manifest_location = Path(manifest_path).resolve() destination = Path(output_dir).resolve() destination.mkdir(parents=True, exist_ok=True) selected_device, dtype = _device_and_dtype(torch, device) processor = WhisperProcessor.from_pretrained(model_location) if (Path(model_location) / "adapter_config.json").is_file(): try: from peft import PeftConfig, PeftModel except ImportError as exc: raise OptionalDependencyError( "Evaluating an adapter requires PEFT from the training dependencies" ) from exc peft_config = PeftConfig.from_pretrained(model_location) base = WhisperForConditionalGeneration.from_pretrained( peft_config.base_model_name_or_path, torch_dtype=dtype ) model = PeftModel.from_pretrained(base, model_location) else: model = WhisperForConditionalGeneration.from_pretrained(model_location, torch_dtype=dtype) model.to(selected_device) model.eval() records = list(read_manifest(manifest_location)) sampled = stratified_sample(records, limit, seed) rows: list[dict[str, Any]] = [] # Whisper pads every clip to the same 30 s window, so a batch costs one # forward pass instead of `batch_size` of them. Grouping by language keeps # that legal: the decoder prompt carries the language token, and one # `generate` call takes a single prompt for the whole batch. for index in range(0, len(sampled), max(1, batch_size)): chunk = sampled[index : index + max(1, batch_size)] for language in sorted({record.language for record in chunk}): group = [record for record in chunk if record.language == language] waveforms = [ librosa.load( resolve_audio_path(record, manifest_location), sr=16000, mono=True )[0] for record in group ] inputs = processor.feature_extractor( waveforms, sampling_rate=16000, return_tensors="pt" ) input_features = inputs.input_features.to(selected_device, dtype=dtype) generate_kwargs: dict[str, Any] = { "task": "transcribe", "max_new_tokens": max_new_tokens, } if language in {"ar", "en"}: generate_kwargs["language"] = language with torch.inference_mode(): generated = model.generate(input_features, **generate_kwargs) hypotheses = processor.tokenizer.batch_decode(generated, skip_special_tokens=True) for record, hypothesis in zip(group, hypotheses, strict=True): rows.append( { "source_file_id": record.metadata.get("source_file_id"), "speaker_id": record.speaker_id, "language": record.language, "dialect": record.dialect, "age_group": record.age_group, "source": record.source, "category": record.category, "reference": record.text, "hypothesis": hypothesis, "normalized_reference": normalize_for_metrics(record.text), "normalized_hypothesis": normalize_for_metrics(hypothesis), } ) predictions_path = destination / "predictions.jsonl" with predictions_path.open("w", encoding="utf-8", newline="\n") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") def score(group: list[dict[str, Any]]) -> dict[str, float | int]: return score_pairs( [row["reference"] for row in group], [row["hypothesis"] for row in group] ) breakdown_fields = ("language", "dialect", "age_group", "source", "category") breakdowns: dict[str, dict[str, Any]] = {} for field in breakdown_fields: groups: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in rows: groups[str(row[field])].append(row) breakdowns[field] = {name: score(group) for name, group in sorted(groups.items())} summary = { "model": model_location, "manifest": str(manifest_location), "device": selected_device, "overall": score(rows), "evaluated_utterances": len(rows), "manifest_utterances": len(records), "sample_seed": seed if limit else None, "breakdowns": breakdowns, "predictions": str(predictions_path), "warning": "Review predictions before sharing; transcript text may be sensitive.", } (destination / "metrics.json").write_text( json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) return summary