| |
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import json |
| import sys |
| from pathlib import Path |
| from time import perf_counter |
| from typing import Any |
|
|
| sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) |
|
|
| from romani_asr.env import configure_certifi |
| from romani_asr.manifest import read_manifest_csv |
| from romani_asr.metrics import compute_asr_metrics |
| from romani_asr.mms import normalize_for_mms_ctc, resolve_audio_path |
| from romani_asr.text import has_non_latin_script, normalize_for_metric |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description="Evaluate MMS/Wav2Vec2 CTC ASR.") |
| parser.add_argument("--manifest", type=Path, default=Path("artifacts/manifests/test.csv")) |
| parser.add_argument("--model-id", default="facebook/mms-1b-all") |
| parser.add_argument("--processor-dir", type=Path, default=None) |
| parser.add_argument( |
| "--adapter-dir", |
| type=Path, |
| default=None, |
| help="Directory containing adapter.<target_lang>.safetensors.", |
| ) |
| parser.add_argument("--target-lang", default="rmc-script_latin") |
| parser.add_argument("--output-dir", type=Path, required=True) |
| parser.add_argument("--limit", type=int, default=0) |
| parser.add_argument("--sampling-rate", type=int, default=16000) |
| parser.add_argument("--device", default="auto") |
| return parser.parse_args() |
|
|
|
|
| def default_device() -> str: |
| import torch |
|
|
| if torch.cuda.is_available(): |
| return "cuda" |
| if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): |
| return "mps" |
| return "cpu" |
|
|
|
|
| def load_audio(path: str, sampling_rate: int) -> Any: |
| import librosa |
|
|
| audio, _ = librosa.load(path, sr=sampling_rate, mono=True) |
| return audio |
|
|
|
|
| def load_local_adapter(model: Any, adapter_dir: Path, target_lang: str) -> None: |
| from safetensors.torch import load_file |
| from transformers.models.wav2vec2.modeling_wav2vec2 import ( |
| WAV2VEC2_ADAPTER_SAFE_FILE, |
| ) |
|
|
| adapter_path = adapter_dir / WAV2VEC2_ADAPTER_SAFE_FILE.format(target_lang) |
| adapter_state = load_file(str(adapter_path)) |
| adapter_weights = model._get_adapters() |
| missing = sorted(set(adapter_weights) - set(adapter_state)) |
| unexpected = sorted(set(adapter_state) - set(adapter_weights)) |
| if missing or unexpected: |
| raise ValueError( |
| "Adapter state does not match model adapter keys: " |
| f"missing={missing[:5]}, unexpected={unexpected[:5]}" |
| ) |
| for name, parameter in adapter_weights.items(): |
| parameter.data.copy_(adapter_state[name].to(parameter.device)) |
|
|
|
|
| def write_predictions(path: Path, rows: list[dict[str, Any]]) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| fieldnames = [ |
| "id", |
| "file_name", |
| "audio_path", |
| "reference", |
| "prediction", |
| "reference_metric", |
| "prediction_metric", |
| "reference_ctc", |
| "prediction_ctc", |
| "has_non_latin_script", |
| "duration_sec", |
| "latency_sec", |
| ] |
| with path.open("w", newline="", encoding="utf-8") as handle: |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) |
| writer.writeheader() |
| writer.writerows(rows) |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| configure_certifi() |
|
|
| import torch |
| from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor |
|
|
| records = read_manifest_csv(args.manifest) |
| if args.limit: |
| records = records[: args.limit] |
|
|
| processor_source = str(args.processor_dir or args.model_id) |
| processor = Wav2Vec2Processor.from_pretrained( |
| processor_source, |
| target_lang=args.target_lang, |
| ) |
| processor.tokenizer.set_target_lang(args.target_lang) |
|
|
| model = Wav2Vec2ForCTC.from_pretrained( |
| args.model_id, |
| target_lang=args.target_lang, |
| vocab_size=len(processor.tokenizer), |
| pad_token_id=processor.tokenizer.pad_token_id, |
| ignore_mismatched_sizes=True, |
| ) |
| if args.adapter_dir: |
| load_local_adapter(model, args.adapter_dir, args.target_lang) |
|
|
| device = default_device() if args.device == "auto" else args.device |
| model.to(device) |
| model.eval() |
|
|
| predictions: list[dict[str, Any]] = [] |
| for index, record in enumerate(records, start=1): |
| audio_path = resolve_audio_path(record["audio_path"]) |
| audio = load_audio(audio_path, args.sampling_rate) |
| started = perf_counter() |
| inputs = processor( |
| audio, |
| sampling_rate=args.sampling_rate, |
| return_tensors="pt", |
| padding=True, |
| ) |
| inputs = {key: value.to(device) for key, value in inputs.items()} |
| with torch.no_grad(): |
| logits = model(**inputs).logits |
| pred_ids = torch.argmax(logits, dim=-1)[0] |
| prediction = processor.decode(pred_ids) |
| latency_sec = perf_counter() - started |
|
|
| reference = record["transcript"] |
| predictions.append( |
| { |
| "id": record["id"], |
| "file_name": record["file_name"], |
| "audio_path": record["audio_path"], |
| "reference": reference, |
| "prediction": prediction, |
| "reference_metric": normalize_for_metric(reference), |
| "prediction_metric": normalize_for_metric(prediction), |
| "reference_ctc": normalize_for_mms_ctc(reference), |
| "prediction_ctc": normalize_for_mms_ctc(prediction), |
| "has_non_latin_script": has_non_latin_script(prediction), |
| "duration_sec": record["duration_sec"], |
| "latency_sec": f"{latency_sec:.4f}", |
| } |
| ) |
| print( |
| f"[{index}/{len(records)}] {record['file_name']} {latency_sec:.2f}s", |
| flush=True, |
| ) |
|
|
| references = [row["reference"] for row in predictions] |
| hypotheses = [row["prediction"] for row in predictions] |
| ctc_references = [row["reference_ctc"] for row in predictions] |
| ctc_hypotheses = [row["prediction_ctc"] for row in predictions] |
| metrics = { |
| "model_id": args.model_id, |
| "target_lang": args.target_lang, |
| "adapter_dir": str(args.adapter_dir) if args.adapter_dir else None, |
| "processor_dir": str(args.processor_dir) if args.processor_dir else None, |
| "manifest": str(args.manifest), |
| "count": len(predictions), |
| "diacritic_sensitive": compute_asr_metrics( |
| references, hypotheses, keep_diacritics=True |
| ), |
| "ascii_folded": compute_asr_metrics( |
| references, hypotheses, keep_diacritics=False |
| ), |
| "ctc_normalized": compute_asr_metrics( |
| ctc_references, ctc_hypotheses, keep_diacritics=True |
| ), |
| "non_latin_prediction_count": sum( |
| has_non_latin_script(row["prediction"]) for row in predictions |
| ), |
| "total_audio_hours": sum(float(row["duration_sec"]) for row in predictions) |
| / 3600, |
| "total_latency_sec": sum(float(row["latency_sec"]) for row in predictions), |
| } |
|
|
| args.output_dir.mkdir(parents=True, exist_ok=True) |
| write_predictions(args.output_dir / "predictions.csv", predictions) |
| (args.output_dir / "metrics.json").write_text( |
| json.dumps(metrics, indent=2, ensure_ascii=False), |
| encoding="utf-8", |
| ) |
| print(json.dumps(metrics, indent=2, ensure_ascii=False), flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|