Download script.py from leeduckgo/dim-sum-semi-round: direct link, hf CLI and curl.
- Browser
- Download file 8.82 kB
-
https://huggingface.co/datasets/leeduckgo/dim-sum-semi-round/resolve/main/script.py
- Command line
-
hf download hf://datasets/leeduckgo/dim-sum-semi-round/script.py
-
curl -L -o script.py https://huggingface.co/datasets/leeduckgo/dim-sum-semi-round/resolve/main/script.py
8.82 kB
| #!/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) | |