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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2714b86
 
 
 
 
 
c6b5e4f
 
 
 
 
 
 
 
 
 
2714b86
 
 
 
 
c6b5e4f
 
 
 
 
 
 
 
 
 
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#!/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()