From 58107c100d518e290f3b97d0c9b684679d6d58ec Mon Sep 17 00:00:00 2001 From: Hani Mohanad <164931686+snygginghani@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:27:29 +0300 Subject: [PATCH] Handle empty reference batches in WER and CER --- metrics/cer/cer.py | 3 ++- metrics/wer/wer.py | 3 ++- tests/test_speech_metrics.py | 26 ++++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 tests/test_speech_metrics.py diff --git a/metrics/cer/cer.py b/metrics/cer/cer.py index a9ff290e4..4323a7d65 100644 --- a/metrics/cer/cer.py +++ b/metrics/cer/cer.py @@ -177,4 +177,5 @@ def _compute(self, predictions, references, concatenate_texts=False): incorrect += measures.substitutions + measures.deletions + measures.insertions total += measures.substitutions + measures.deletions + measures.hits - return incorrect / total + # With no reference characters, JiWER counts only insertions. + return incorrect / total if total else incorrect diff --git a/metrics/wer/wer.py b/metrics/wer/wer.py index f63aad021..ca4d6782f 100644 --- a/metrics/wer/wer.py +++ b/metrics/wer/wer.py @@ -115,4 +115,5 @@ def _compute(self, predictions=None, references=None, concatenate_texts=False): measures = jiwer.process_words(reference, prediction) incorrect += measures.substitutions + measures.deletions + measures.insertions total += measures.substitutions + measures.deletions + measures.hits - return incorrect / total + # With no reference words, JiWER counts only insertions. + return incorrect / total if total else incorrect diff --git a/tests/test_speech_metrics.py b/tests/test_speech_metrics.py new file mode 100644 index 000000000..0fa7cb721 --- /dev/null +++ b/tests/test_speech_metrics.py @@ -0,0 +1,26 @@ +from pathlib import Path + +import pytest + +import evaluate + + +@pytest.mark.parametrize("metric_name", ["wer", "cer"]) +@pytest.mark.parametrize( + ("references", "predictions", "expected_wer", "expected_cer"), + [ + (["", ""], ["", ""], 0, 0), + (["", ""], ["alpha beta", "a"], 3, 11), + ([" ", ""], ["alpha beta", "a"], 3, 11), + (["hello world", ""], ["hello there", "x"], 1, 6 / 11), + ], +) +def test_speech_metric_with_empty_references(metric_name, references, predictions, expected_wer, expected_cer): + jiwer = pytest.importorskip("jiwer") + if hasattr(jiwer, "compute_measures"): + pytest.skip("Empty references require JiWER 4 or later") + + metric_path = Path(__file__).resolve().parents[1] / "metrics" / metric_name + metric = evaluate.load(str(metric_path), keep_in_memory=True) + expected = {"wer": expected_wer, "cer": expected_cer}[metric_name] + assert metric.compute(references=references, predictions=predictions) == expected