File size: 8,815 Bytes
0beaa94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | #!/usr/bin/env python3
"""
bash example:
```
python3 evaluator.py verify.jsonl output.jsonl ./outputs
```
Evaluate ASR predictions against verify.jsonl reference.
Inputs:
- verify_jsonl: reference file with audio_path and ref_text
- pred_jsonl: prediction file with audio_path and pred_text
- report_dir: directory to write score.txt (optional)
Rules:
1. audio_path must strictly match one-to-one between prediction and reference
2. Convert pred_text from traditional to simplified Chinese before scoring
3. Compare ref_text and pred_text after removing all punctuation
4. A sample passes if edit distance between ref_text and pred_text is <= 2 characters
Output:
- score.txt: sentence accuracy percentage (plain float)
- error.jsonl: failed samples with audio_path, ref_text, pred_text, edit_distance
"""
import argparse
import json
import os
import re
import sys
from typing import Dict, List, Tuple
PUNCT_REGEX = re.compile(
r"[,。!?;:、“”‘’()()【】《》〈〉—…·,\.!\?;:\"'`\[\]\{\}\s]"
)
CHAR_TOLERANCE = 2
_OPENCC = None
def get_opencc():
global _OPENCC
if _OPENCC is None:
try:
from opencc import OpenCC
except ImportError as exc:
raise ImportError(
"opencc is required for traditional-to-simplified conversion. "
"Install with: pip install opencc-python-reimplemented"
) from exc
_OPENCC = OpenCC("t2s")
return _OPENCC
def to_simplified(text: str) -> str:
if not text:
return text
return get_opencc().convert(text)
def parse_args() -> argparse.Namespace:
script_dir = os.path.dirname(os.path.abspath(__file__))
default_verify = os.path.join(script_dir, "verify.jsonl")
default_pred = os.path.join(script_dir, "output.jsonl")
default_report_dir = os.path.join(script_dir, "outputs")
parser = argparse.ArgumentParser(
description="Evaluate ASR predictions against verify.jsonl.",
epilog="Example: python3 evaluator.py verify.jsonl output.jsonl ./outputs",
)
parser.add_argument(
"verify_jsonl",
nargs="?",
default=default_verify,
help=f"Reference jsonl path. Default: {default_verify}",
)
parser.add_argument(
"pred_jsonl",
nargs="?",
default=default_pred,
help=f"Prediction jsonl path. Default: {default_pred}",
)
parser.add_argument(
"report_dir",
nargs="?",
default=default_report_dir,
help=f"Report directory. Default: {default_report_dir}",
)
return parser.parse_args()
def normalize_text(text: str) -> str:
text = re.sub(r"^\[(RAW|NORM)\]\s*", "", text or "")
text = re.sub(PUNCT_REGEX, "", text)
return text.strip()
def norm_audio_path(path: str) -> str:
return os.path.normpath(str(path).strip())
def load_jsonl(path: str) -> List[dict]:
rows = []
with open(path, "r", encoding="utf-8") as f:
for line_no, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
rows.append(json.loads(line))
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid json at {path}:{line_no}: {exc}") from exc
if not rows:
raise ValueError(f"No rows found in {path}")
return rows
def load_verify_jsonl(path: str) -> List[Tuple[str, str]]:
rows = []
for idx, row in enumerate(load_jsonl(path), start=1):
audio = row.get("audio_path")
ref_text = row.get("ref_text")
if not audio:
raise ValueError(f"Missing audio_path in verify row {idx}")
if ref_text is None:
raise ValueError(f"Missing ref_text for audio_path: {audio}")
rows.append((norm_audio_path(audio), str(ref_text)))
return rows
def load_pred_jsonl(path: str) -> List[Tuple[str, str]]:
rows = []
for idx, row in enumerate(load_jsonl(path), start=1):
audio = row.get("audio_path")
pred_text = row.get("pred_text")
if not audio:
raise ValueError(f"Missing audio_path in prediction row {idx}")
if pred_text is None:
raise ValueError(f"Missing pred_text for audio_path: {audio}")
rows.append((norm_audio_path(audio), to_simplified(str(pred_text))))
return rows
def align_predictions(
ref_rows: List[Tuple[str, str]],
pred_rows: List[Tuple[str, str]],
) -> Tuple[List[str], List[str], List[str]]:
ref_map = {audio: ref for audio, ref in ref_rows}
ref_audios = [audio for audio, _ in ref_rows]
if len(pred_rows) != len(ref_rows):
raise ValueError(
f"Row count mismatch: predictions={len(pred_rows)}, references={len(ref_rows)}"
)
pred_by_audio: Dict[str, str] = {}
pred_order: List[str] = []
for audio, pred_text in pred_rows:
if audio in pred_by_audio:
raise ValueError(f"Duplicate audio_path in predictions: {audio}")
pred_by_audio[audio] = pred_text
pred_order.append(audio)
missing_in_pred = [audio for audio in ref_audios if audio not in pred_by_audio]
extra_in_pred = [audio for audio in pred_order if audio not in ref_map]
if missing_in_pred:
preview = ", ".join(missing_in_pred[:5])
raise ValueError(
f"Predictions missing {len(missing_in_pred)} reference audio_path(s): {preview}"
)
if extra_in_pred:
preview = ", ".join(extra_in_pred[:5])
raise ValueError(
f"Predictions contain {len(extra_in_pred)} unknown audio_path(s): {preview}"
)
if pred_order != ref_audios:
first_mismatch = next(
(
i
for i, (pred_audio, ref_audio) in enumerate(zip(pred_order, ref_audios))
if pred_audio != ref_audio
),
None,
)
if first_mismatch is not None:
raise ValueError(
"audio_path order mismatch at "
f"line {first_mismatch + 1}: "
f"pred={pred_order[first_mismatch]!r}, ref={ref_audios[first_mismatch]!r}"
)
audios = ref_audios
refs = [normalize_text(ref_map[audio]) for audio in audios]
preds = [normalize_text(pred_by_audio[audio]) for audio in audios]
return audios, refs, preds
def edit_distance(ref: str, pred: str) -> int:
m, n = len(ref), len(pred)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
dp[i][0] = i
for j in range(1, n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if ref[i - 1] == pred[j - 1] else 1
dp[i][j] = min(
dp[i - 1][j - 1] + cost,
dp[i - 1][j] + 1,
dp[i][j - 1] + 1,
)
return dp[m][n]
def is_match(ref: str, pred: str, tolerance: int = CHAR_TOLERANCE) -> bool:
return edit_distance(ref, pred) <= tolerance
def sentence_accuracy(preds: List[str], refs: List[str], tolerance: int = CHAR_TOLERANCE) -> float:
if not refs:
return 0.0
return sum(int(is_match(r, p, tolerance)) for p, r in zip(preds, refs)) / len(refs)
def main() -> None:
args = parse_args()
os.makedirs(args.report_dir, exist_ok=True)
ref_rows = load_verify_jsonl(args.verify_jsonl)
pred_rows = load_pred_jsonl(args.pred_jsonl)
ref_raw = {audio: ref for audio, ref in ref_rows}
pred_raw = {audio: pred for audio, pred in pred_rows}
audios, refs, preds = align_predictions(ref_rows, pred_rows)
sent_acc = sentence_accuracy(preds, refs)
score = sent_acc * 100.0
errors = []
for audio, ref_norm, pred_norm in zip(audios, refs, preds):
if not is_match(ref_norm, pred_norm):
errors.append({
"audio_path": audio,
"ref_text": ref_raw[audio],
"pred_text": pred_raw[audio],
"edit_distance": edit_distance(ref_norm, pred_norm),
})
score_path = os.path.join(args.report_dir, "score.txt")
with open(score_path, "w", encoding="utf-8") as f:
f.write(f"{score:g}\n")
error_path = os.path.join(args.report_dir, "error.jsonl")
with open(error_path, "w", encoding="utf-8") as f:
for row in errors:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
print(f"num_samples={len(refs)}")
print(f"sentence_accuracy={sent_acc:.4f}")
print(f"score={score:g}")
print(f"errors={len(errors)}")
print(f"saved -> {score_path}")
print(f"saved -> {error_path}")
if __name__ == "__main__":
try:
main()
except (ValueError, ImportError) as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
|