#!/usr/bin/env python3 """Summarize MOS submissions. Uses the latest submission from each rater.""" from __future__ import annotations import argparse import json from collections import defaultdict from pathlib import Path from typing import Any, Dict, Iterable, List, Optional ROOT = Path(__file__).resolve().parent def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Summarize MOS ratings.") parser.add_argument("--results", type=Path, default=ROOT / "results" / "ratings.jsonl") parser.add_argument("--keys", type=Path, default=ROOT / "data" / "PRIVATE_keys.json") parser.add_argument("--output", type=Path, default=ROOT / "results" / "summary.json") return parser.parse_args() def load_jsonl(path: Path) -> List[Dict[str, Any]]: rows = [] if not path.is_file(): return rows with path.open(encoding="utf-8") as handle: for line in handle: raw = line.strip() if not raw: continue rows.append(json.loads(raw)) return rows def latest_by_rater(rows: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]: chosen: Dict[str, Dict[str, Any]] = {} for row in rows: rater = str(row.get("rater_id") or "") previous = chosen.get(rater) if previous is None or str(row.get("submitted_at") or "") >= str(previous.get("submitted_at") or ""): chosen[rater] = row return list(chosen.values()) def mean(values: List[float]) -> Optional[float]: if not values: return None return sum(values) / len(values) def sample_std(values: List[float]) -> Optional[float]: if len(values) < 2: return 0.0 if values else None center = mean(values) or 0.0 return (sum((value - center) ** 2 for value in values) / (len(values) - 1)) ** 0.5 def histogram(values: List[int]) -> Dict[str, int]: counts = {str(score): 0 for score in range(1, 6)} for value in values: counts[str(value)] = counts.get(str(value), 0) + 1 return counts def jaccard(left: Iterable[str], right: Iterable[str]) -> float: a = set(left) b = set(right) if not a and not b: return 1.0 return len(a & b) / len(a | b) def summarize_scores( rows: List[Dict[str, Any]], field: str, role_of: Dict[str, str], ) -> Dict[str, Any]: by_system: Dict[str, List[int]] = defaultdict(list) paired: Dict[str, Dict[str, List[int]]] = defaultdict(lambda: defaultdict(list)) for row in rows: for rating in row.get("description_ratings") or []: if rating.get(field) is None: continue system = str(rating.get("system")) score = int(rating[field]) by_system[system].append(score) paired[str(rating.get("audio_id"))][system].append(score) system_stats = {} for system, scores in sorted(by_system.items()): system_stats[system] = { "role": role_of.get(system, system), "n": len(scores), "mean": mean([float(s) for s in scores]), "std": sample_std([float(s) for s in scores]), "histogram": histogram(scores), } differences = [] per_audio = [] for audio_id, groups in sorted(paired.items()): if "A" not in groups or "B" not in groups: continue mean_a = mean([float(s) for s in groups["A"]]) mean_b = mean([float(s) for s in groups["B"]]) if mean_a is None or mean_b is None: continue differences.append(mean_a - mean_b) per_audio.append( { "audio_id": audio_id, "mean_A": mean_a, "mean_B": mean_b, "A_minus_B": mean_a - mean_b, "n_A": len(groups["A"]), "n_B": len(groups["B"]), } ) return { "by_system": system_stats, "paired_A_minus_B": { "n_audios": len(differences), "mean": mean(differences), "n_A_higher": sum(1 for value in differences if value > 0), "n_tie": sum(1 for value in differences if value == 0), "n_B_higher": sum(1 for value in differences if value < 0), }, "per_audio": per_audio, } def summarize(rows: List[Dict[str, Any]], keys: Optional[Dict[str, Any]]) -> Dict[str, Any]: systems = (keys or {}).get("systems") or {} gold = (keys or {}).get("aspect_gold") or {} role_of = { system: meta.get("role_zh") or meta.get("role") or system for system, meta in systems.items() } aspect_rows = [] exact = 0 jaccard_scores: List[float] = [] gold_sets = 0 per_aspect = { aspect: {"tp": 0, "fp": 0, "fn": 0} for aspect in ["1", "2", "3", "4", "5", "6"] } for row in rows: rater = row.get("rater_id") for rating in row.get("aspect_ratings") or []: selected = [str(x) for x in rating.get("selected") or []] uid = str(rating.get("uid")) gold_row = gold.get(uid) or {} gold_aspects = [str(x) for x in gold_row.get("aspects") or []] item = { "rater_id": rater, "uid": uid, "selected": selected, "gold": gold_aspects or None, "query": gold_row.get("query"), } if gold_aspects: gold_sets += 1 same = set(selected) == set(gold_aspects) exact += int(same) jaccard_scores.append(jaccard(selected, gold_aspects)) item["exact"] = same item["jaccard"] = jaccard_scores[-1] for aspect in per_aspect: in_sel = aspect in selected in_gold = aspect in gold_aspects if in_sel and in_gold: per_aspect[aspect]["tp"] += 1 elif in_sel: per_aspect[aspect]["fp"] += 1 elif in_gold: per_aspect[aspect]["fn"] += 1 aspect_rows.append(item) aspect_stats = {} for aspect, counts in per_aspect.items(): tp, fp, fn = counts["tp"], counts["fp"], counts["fn"] precision = tp / (tp + fp) if tp + fp else None recall = tp / (tp + fn) if tp + fn else None f1 = None if precision is not None and recall is not None and precision + recall: f1 = 2 * precision * recall / (precision + recall) aspect_stats[aspect] = {**counts, "precision": precision, "recall": recall, "f1": f1} return { "n_submissions_used": len(rows), "systems": systems, "description_accuracy": summarize_scores(rows, "score", role_of), "description_richness": summarize_scores(rows, "richness", role_of), "aspects": { "n_scored_against_gold": gold_sets, "exact_match": (exact / gold_sets) if gold_sets else None, "mean_jaccard": mean(jaccard_scores), "per_aspect": aspect_stats, "items": aspect_rows, }, } def _fmt(value: Optional[float]) -> str: return "—" if value is None else f"{value:.3f}" def _render_scores(lines: List[str], title: str, block: Dict[str, Any]) -> None: lines.append(title) for system, stats in block["by_system"].items(): lines.append( f" {system} ({stats['role']}): n={stats['n']} mean={_fmt(stats['mean'])} " f"std={_fmt(stats['std'])} hist={stats['histogram']}" ) paired = block["paired_A_minus_B"] lines.append( " 配对 A−B: " f"mean={_fmt(paired['mean'])} " f"A更高={paired['n_A_higher']} 相同={paired['n_tie']} B更高={paired['n_B_higher']}" ) def render_text(summary: Dict[str, Any]) -> str: lines = [f"被试(每人取最新一次): {summary['n_submissions_used']}"] lines.append("") _render_scores(lines, "描述准确性(1–5,只评价说法是否正确,不评价完整性)", summary["description_accuracy"]) lines.append("") _render_scores(lines, "描述丰富度(1–5,评价覆盖了多少听到的内容)", summary["description_richness"]) aspects = summary["aspects"] lines.append("") lines.append("Aspect 选择 vs 训练集标签") lines.append( f" exact={_fmt(aspects['exact_match'])} " f"jaccard={_fmt(aspects['mean_jaccard'])} n={aspects['n_scored_against_gold']}" ) for aspect, stats in aspects["per_aspect"].items(): lines.append( f" aspect {aspect}: P={_fmt(stats['precision'])} R={_fmt(stats['recall'])} " f"F1={_fmt(stats['f1'])} tp={stats['tp']} fp={stats['fp']} fn={stats['fn']}" ) return "\n".join(lines) def main() -> None: args = parse_args() rows = latest_by_rater(load_jsonl(args.results)) keys = json.loads(args.keys.read_text(encoding="utf-8")) if args.keys.is_file() else None summary = summarize(rows, keys) text = render_text(summary) print(text) if rows: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"\nWrote {args.output}") else: print(f"\nNo submissions in {args.results}") if __name__ == "__main__": main()