#!/usr/bin/env python3 """Build the blind stimuli used by the MOS Space. Description task: 10 paired MMAU speech clips. Each clip has one description from each system. The page shows both at once, in a random order. Aspect task: 10 queries drawn from the AudioMCQ strong training set. Gold aspect labels stay in PRIVATE_keys.json and are not shown by the app. """ from __future__ import annotations import argparse import hashlib import json import random import re from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, List, Optional MOS_DIR = Path(__file__).resolve().parent REPO_ROOT = MOS_DIR.parents[2] BASELINE_JSON = ( REPO_ROOT / "exp/qwen25omni_original_model_for_evaluation" / "eval_0_Qwen_Qwen3-30B-A3B-Instruct-2507" / "mmau_predictions_two_stage.json" ) OURS_JSON = ( REPO_ROOT / "exp/qwen25omni_sft_full_grpo_full_audiomcq_strong_duplicate_listed" / "eval_5127_Qwen_Qwen3-30B-A3B-Instruct-2507" / "mmau_predictions_two_stage.json" ) TRAIN_JSONL = REPO_ROOT / "data/qa/AudioMCQ/AudioMCQ_SpeechCraft_with_aspect_strong_train.jsonl" AUDIO_ROOTS = [ Path("/mnt/users_home/cpii.local/wdchen/dataset/MMAU"), REPO_ROOT / "data/MMAU", ] # Internal ids only. A is the original model (baseline). B is the trained model. SYSTEMS = { "A": { "role": "baseline", "role_zh": "baseline", "exp": "qwen25omni_original_model_for_evaluation", "predictions": str(BASELINE_JSON.relative_to(REPO_ROOT)), }, "B": { "role": "ours", "role_zh": "我们的模型", "exp": "qwen25omni_sft_full_grpo_full_audiomcq_strong_duplicate_listed", "predictions": str(OURS_JSON.relative_to(REPO_ROOT)), }, } ASPECTS = [ { "id": "1", "en_name": "Lexical & Semantic Content", "zh_name": "词汇与语义内容", "en_def": "key words, entities, literal meaning", "zh_def": "关键词、实体、字面含义", }, { "id": "2", "en_name": "Intent & Pragmatics", "zh_name": "意图与语用", "en_def": "communicative goal, implied meaning grounded in speech", "zh_def": "交际目的,以及必须结合语音才能确定的隐含意义", }, { "id": "3", "en_name": "Emotion & Affect", "zh_name": "情感与情绪", "en_def": "emotion type and intensity", "zh_def": "情绪的类型和强度", }, { "id": "4", "en_name": "Prosody & Delivery", "zh_name": "韵律与表达方式", "en_def": "pitch, rhythm, stress, speaking rate", "zh_def": "音高、节奏、重音、语速", }, { "id": "5", "en_name": "Fluency & Articulation", "zh_name": "流利度与发音", "en_def": "pauses, disfluencies, clarity", "zh_def": "停顿、不流利、清晰度", }, { "id": "6", "en_name": "Speaker Traits", "zh_name": "说话人特征", "en_def": "age, gender, accent, speaking style", "zh_def": "年龄、性别、口音、说话风格", }, ] def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Prepare blind MOS stimuli.") parser.add_argument("--seed", type=int, default=42) parser.add_argument("--n-desc", type=int, default=10, help="Paired audios per system.") parser.add_argument("--n-aspect", type=int, default=10) parser.add_argument("--bitrate", type=int, default=192_000, help="MP3 bitrate for web playback.") parser.add_argument("--max-duration", type=float, default=10.0, help="Keep speech clips no longer than this many seconds.") parser.add_argument("--min-words", type=int, default=4, help="Drop a pair if either description has fewer words than this.") parser.add_argument( "--n-contrastive", type=int, default=5, help="How many items must be baseline-wrong and ours-correct. The rest are drawn from the other eligible clips.", ) return parser.parse_args() def load_json(path: Path) -> List[Dict[str, Any]]: with path.open(encoding="utf-8") as handle: data = json.load(handle) if not isinstance(data, list): raise ValueError(f"Expected a list in {path}") return [row for row in data if isinstance(row, dict)] def resolve_audio(audio_id: str) -> Optional[Path]: raw = str(audio_id or "").strip() if not raw: return None path = Path(raw) if path.is_file(): return path.resolve() for root in AUDIO_ROOTS: candidate = (root / raw).resolve() if candidate.is_file(): return candidate return None def parse_aspects(text: str) -> List[str]: found: List[str] = [] for piece in str(text or "").replace(",", ",").split(","): part = piece.strip() if part in {"1", "2", "3", "4", "5", "6"} and part not in found: found.append(part) return found _WORD = re.compile(r"[A-Za-z0-9]+(?:'[A-Za-z]+)?") def word_count(text: str) -> int: return len(_WORD.findall(text)) def answered_correctly(row: Dict[str, Any]) -> bool: try: return int(row.get("match")) == 1 except (TypeError, ValueError): return False def audio_duration(path: Path) -> float: import av with av.open(str(path)) as container: if container.duration: return float(container.duration) / 1_000_000 stream = container.streams.audio[0] if stream.duration: return float(stream.duration * stream.time_base) return 0.0 def transcode_mp3(src: Path, dst: Path, bit_rate: int) -> float: import av dst.parent.mkdir(parents=True, exist_ok=True) source = av.open(str(src)) target = av.open(str(dst), mode="w") try: stream = source.streams.audio[0] context = stream.codec_context channels = context.channels or 1 layout_name = "mono" if channels == 1 else "stereo" output = target.add_stream("mp3", rate=context.sample_rate) output.bit_rate = bit_rate output.layout = layout_name resampler = av.audio.resampler.AudioResampler( format="s16p", layout=layout_name, rate=context.sample_rate, ) duration = (source.duration or 0) / 1_000_000 for frame in source.decode(stream): for resampled in resampler.resample(frame): resampled.pts = None for packet in output.encode(resampled): target.mux(packet) for resampled in resampler.resample(None): resampled.pts = None for packet in output.encode(resampled): target.mux(packet) for packet in output.encode(None): target.mux(packet) return float(duration) finally: target.close() source.close() def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def select_description_pairs( n: int, seed: int, bit_rate: int, max_duration: float, min_words: int, n_contrastive: int, ) -> Dict[str, Any]: baseline_rows = {row["id"]: row for row in load_json(BASELINE_JSON) if row.get("task") == "speech"} ours_rows = {row["id"]: row for row in load_json(OURS_JSON) if row.get("task") == "speech"} candidates = [] too_long = 0 too_short = 0 for sample_id in sorted(set(baseline_rows) & set(ours_rows)): baseline_desc = str(baseline_rows[sample_id].get("perceiver_description") or "").strip() ours_desc = str(ours_rows[sample_id].get("perceiver_description") or "").strip() if not baseline_desc or not ours_desc: continue if word_count(baseline_desc) < min_words or word_count(ours_desc) < min_words: too_short += 1 continue audio_path = resolve_audio(str(baseline_rows[sample_id].get("audio_id") or "")) if audio_path is None: continue duration = audio_duration(audio_path) if duration <= 0 or duration > max_duration: too_long += 1 continue candidates.append(sample_id) preferred = [ sample_id for sample_id in candidates if not answered_correctly(baseline_rows[sample_id]) and answered_correctly(ours_rows[sample_id]) ] others = [sample_id for sample_id in candidates if sample_id not in set(preferred)] print( f"Speech pairs at most {max_duration:.0f}s with at least {min_words} words: " f"{len(candidates)} (excluded {too_short} short descriptions, {too_long} longer clips)" ) print(f"Baseline wrong and ours correct: {len(preferred)}; other eligible: {len(others)}") n_from_preferred = min(max(n_contrastive, 0), n) if len(candidates) < n: raise RuntimeError(f"Only {len(candidates)} usable speech pairs; need {n}.") if len(preferred) < n_from_preferred: raise RuntimeError( f"Only {len(preferred)} baseline-wrong/ours-correct pairs; need {n_from_preferred}." ) if len(others) < n - n_from_preferred: raise RuntimeError( f"Only {len(others)} other eligible pairs; need {n - n_from_preferred}." ) rng = random.Random(seed) picked = rng.sample(preferred, n_from_preferred) picked.extend(rng.sample(others, n - n_from_preferred)) rng.shuffle(picked) audio_dir = MOS_DIR / "audio" audio_dir.mkdir(parents=True, exist_ok=True) public_items: List[Dict[str, Any]] = [] private_items: List[Dict[str, Any]] = [] for sample_id in picked: source = resolve_audio(str(baseline_rows[sample_id].get("audio_id") or "")) assert source is not None mp3_rel = f"audio/{sample_id}.mp3" duration = transcode_mp3(source, MOS_DIR / mp3_rel, bit_rate) descriptions = { "A": str(baseline_rows[sample_id].get("perceiver_description") or "").strip(), "B": str(ours_rows[sample_id].get("perceiver_description") or "").strip(), } source_rows = {"A": baseline_rows[sample_id], "B": ours_rows[sample_id]} for system, description in descriptions.items(): uid = f"{sample_id}::{system}" row = source_rows[system] public_items.append( { "uid": uid, "audio_id": sample_id, "audio": mp3_rel, "duration_sec": round(duration, 2), "system": system, "description": description, } ) private_items.append( { "uid": uid, "audio_id": sample_id, "system": system, "question": row.get("question"), "choices": row.get("choices"), "answer": row.get("answer"), "task": row.get("task"), "category": row.get("category"), "sub_category": row.get("sub-category"), "match": row.get("match"), "model_output": row.get("model_output"), "description": description, "description_sha256": hashlib.sha256(description.encode("utf-8")).hexdigest(), "source_audio": str(source), } ) preferred_picked = sum( 1 for sample_id in picked if not answered_correctly(baseline_rows[sample_id]) and answered_correctly(ours_rows[sample_id]) ) return { "n_preferred_available": len(preferred), "n_preferred_picked": preferred_picked, "public": { "task": "description_accuracy", "subset": "speech", "max_duration_sec": max_duration, "min_words": min_words, "seed": seed, "n_audios": n, "playback": f"{bit_rate // 1000} kbps MP3 transcoded from the original wav", "items": public_items, }, "private": private_items, } def select_aspect_items(n: int, seed: int) -> Dict[str, Any]: pool: List[Dict[str, Any]] = [] with TRAIN_JSONL.open(encoding="utf-8") as handle: for lineno, line in enumerate(handle, 1): raw = line.strip() if not raw: continue row = json.loads(raw) pairs = row.get("pairs") if isinstance(row.get("pairs"), list) else [] for pair_index, pair in enumerate(pairs): if not isinstance(pair, dict): continue query = str(pair.get("query") or "").strip() choices = pair.get("choices") if isinstance(pair.get("choices"), list) else [] choices = [str(choice).strip() for choice in choices if str(choice).strip()] aspects = parse_aspects(str(pair.get("aspects") or "")) if not query or len(choices) < 2 or not aspects: continue pool.append( { "uid": f"L{lineno}P{pair_index}", "query": query, "choices": choices, "aspects": aspects, "answer": pair.get("answer"), "source_line": lineno, "pair_index": pair_index, } ) if len(pool) < n: raise RuntimeError(f"Only {len(pool)} usable training queries; need {n}.") picked = random.Random(seed).sample(pool, n) public = [ {"uid": item["uid"], "query": item["query"], "choices": item["choices"]} for item in picked ] gold = { item["uid"]: { "aspects": item["aspects"], "answer": item["answer"], "source_line": item["source_line"], "pair_index": item["pair_index"], "query": item["query"], } for item in picked } return {"public": public, "gold": gold, "pool_size": len(pool)} def main() -> None: args = parse_args() ratings = MOS_DIR / "results" / "ratings.jsonl" if ratings.is_file() and ratings.stat().st_size: print( "Note: results/ratings.jsonl already has submissions. " "Old ratings stay aligned only while these stimulus ids are unchanged." ) desc = select_description_pairs( args.n_desc, args.seed, args.bitrate, args.max_duration, args.min_words, args.n_contrastive, ) keep = {item["audio"] for item in desc["public"]["items"]} audio_dir = MOS_DIR / "audio" if audio_dir.is_dir(): for old in audio_dir.glob("*.mp3"): if f"audio/{old.name}" not in keep: old.unlink() aspect = select_aspect_items(args.n_aspect, args.seed) created = datetime.now(timezone.utc).isoformat() write_json(MOS_DIR / "data" / "desc_items.json", desc["public"]) write_json( MOS_DIR / "data" / "aspect_items.json", { "task": "aspect_necessity", "seed": args.seed, "source": str(TRAIN_JSONL.relative_to(REPO_ROOT)), "aspects": ASPECTS, "items": aspect["public"], }, ) write_json( MOS_DIR / "data" / "PRIVATE_keys.json", { "created_at": created, "seed": args.seed, "warning": "Do not upload this file to a public Space. It reveals system identity and gold aspect labels.", "systems": SYSTEMS, "description_sampling": { "contrastive": "baseline match 0 and ours match 1", "available_contrastive": desc["n_preferred_available"], "picked_contrastive": desc["n_preferred_picked"], "picked_other": args.n_desc - desc["n_preferred_picked"], }, "description_items": desc["private"], "aspect_gold": aspect["gold"], "aspect_pool_size": aspect["pool_size"], }, ) durations = {} for item in desc["public"]["items"]: durations[item["audio_id"]] = item["duration_sec"] total = sum(durations.values()) print(f"Description audios: {len(durations)} total {total:.1f}s mean {total / len(durations):.1f}s") print( "Baseline wrong and ours correct in the sample: " f"{desc['n_preferred_picked']}/{len(durations)} " f"(available {desc['n_preferred_available']})" ) print(f"Aspect pool: {aspect['pool_size']} sampled: {len(aspect['public'])}") print(f"Wrote {MOS_DIR / 'data'}") for item in desc["private"]: if item["system"] != "A": continue print(f" {item['audio_id']} {item['question']}") if __name__ == "__main__": main()