File size: 18,619 Bytes
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
04c8847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6b5e4f
 
 
 
 
 
 
 
 
912507a
 
 
 
 
 
 
c6b5e4f
 
 
 
 
 
 
 
 
912507a
 
 
 
 
c6b5e4f
912507a
c6b5e4f
912507a
c6b5e4f
912507a
 
 
c6b5e4f
 
 
912507a
c6b5e4f
61ade44
c6b5e4f
61ade44
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61ade44
c6b5e4f
912507a
 
c6b5e4f
912507a
61ade44
c6b5e4f
61ade44
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912507a
c6b5e4f
 
912507a
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912507a
c6b5e4f
 
 
 
 
912507a
c6b5e4f
 
912507a
c6b5e4f
 
 
 
 
 
 
 
 
 
912507a
c6b5e4f
 
 
 
 
 
 
 
 
 
61ade44
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912507a
c6b5e4f
 
912507a
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912507a
c6b5e4f
912507a
c6b5e4f
 
 
 
912507a
 
 
 
 
 
 
 
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912507a
 
 
c6b5e4f
 
 
 
912507a
 
 
 
 
 
 
 
 
 
 
c6b5e4f
912507a
 
 
 
 
 
 
 
 
 
 
c6b5e4f
 
 
 
 
 
 
 
912507a
c6b5e4f
 
61ade44
 
 
912507a
61ade44
 
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912507a
c6b5e4f
 
912507a
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912507a
c6b5e4f
912507a
 
 
 
c6b5e4f
 
 
 
912507a
 
 
 
c6b5e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441dcc1
 
 
 
 
 
 
 
 
912507a
 
61ade44
 
 
 
912507a
 
61ade44
 
 
 
441dcc1
 
 
c6b5e4f
 
 
441dcc1
 
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
"""Hugging Face Space for the description-accuracy and aspect MOS."""

from __future__ import annotations

import copy
import html
import os
from typing import Any, Dict, Optional

import gradio as gr

from mos_core import ROOT, Study

# ZeroGPU Spaces stop at startup unless at least one function uses this decorator.
# The MOS app does not call it, so no GPU time is used.
try:
    import spaces as _spaces
except ImportError:
    _spaces = None


def _zerogpu_stub() -> str:
    return "ok"


if _spaces is not None:
    _zerogpu_stub = _spaces.GPU(duration=1)(_zerogpu_stub)

STUDY = Study()

SCORE_CHOICES = [
    ("5 — 每一个具体说法都准确", "5"),
    ("4 — 整体准确,只有不影响含义的轻微不精确", "4"),
    ("3 — 准确和不准确的说法都有", "3"),
    ("2 — 大多数说法不准确,只有少量细节是对的", "2"),
    ("1 — 大体或完全不准确,或明显与音频矛盾", "1"),
]
RICH_CHOICES = [
    ("5 — 听到的主要内容都写到了,而且比较具体", "5"),
    ("4 — 主要内容都有,只漏了少量不影响整体的细节", "4"),
    ("3 — 写到了一部分主要内容,也漏掉了一部分", "3"),
    ("2 — 只写到少量内容,大部分听到的信息都没有", "2"),
    ("1 — 几乎没有写出音频里的内容", "1"),
]
ASPECT_CHOICES = [
    (
        f"{row['id']}. {row['en_name']}({row['zh_name']}):{row['zh_def']}",
        row["id"],
    )
    for row in STUDY.aspect["aspects"]
]

RUBRIC = """
### 准确性

只评价描述里**已经写出的说法**是否符合你听到的音频。不要评价完整性、覆盖面或细节多少。遗漏的事件、写得短、没提到的属性,都不能降低准确性。一段只说了真话的短描述,准确性应该得高分。只有某个说法是错的、与音频矛盾、或者你听不到能支持它的内容时,才降低准确性。

例如:音频里有说话、音乐和狗叫,描述只写了 “a dog is barking.” 如果这句是对的,准确性打 5 分。没写到的说话和音乐不影响准确性。

### 丰富度

评价这段描述覆盖了多少你听到的内容、写得有多具体。漏掉主要内容,或者只写了空泛的短句,都要降低丰富度。说法对不对在准确性里打,不在丰富度里重复扣分。

上面的例子里,描述只写了狗叫,丰富度要低,因为说话和音乐都没写到。

忽略文笔。两段描述分别打分,不要互相比较。
"""

ASPECT_GUIDE = """
### 六个语音角度

请选出回答这个问题所**必须**从语音中知道的信息。只选必要的,能少选就少选。

例如:问题只问说话人具体说了什么,通常只需要 1。问题如果问年龄和情绪,需要 6 和 3。
"""


def _catalog() -> str:
    lines = []
    for row in STUDY.aspect["aspects"]:
        lines.append(f"**{row['id']}. {row['en_name']}({row['zh_name']})**")
        lines.append(f"{row['en_def']}。{row['zh_def']}。")
        lines.append("")
    return "\n".join(lines)


def _choices_text(choices: list) -> str:
    letters = "ABCDEFGH"
    lines = []
    for index, choice in enumerate(choices):
        label = letters[index] if index < len(letters) else str(index + 1)
        lines.append(f"{label}. {choice}")
    return "\n".join(lines)


def _notice(text: str, kind: str) -> str:
    if not text:
        return ""
    color = "#9b1c1c" if kind == "error" else "#1e3a5f"
    return f"<p style='color:{color};font-weight:600;margin:0.4rem 0'>{html.escape(text)}</p>"


def _clean_name(name: Any) -> str:
    text = " ".join(str(name or "").split())
    if len(text) < 2:
        return ""
    return text[:40]


def _intro() -> str:
    minutes = STUDY.listen_seconds / 60
    return f"""
# 语音感知人工评测

评测包含两部分。

**第一部分:描述的准确性和丰富度**({STUDY.n_desc} 题)
每题听一段音频,并同时看到两段描述。请分别给每段描述的准确性和丰富度打分。

**第二部分:回答问题需要知道语音哪些角度的信息**({STUDY.n_aspect} 题)
只看文字问题和选项。请选择要回答该问题,必须知道语音哪些角度的信息。

开始前请填写姓名。用同一个姓名可以继续未完成的进度。
"""


def view(state: Optional[Dict[str, Any]], message: str = "", kind: str = "error") -> Dict[str, Any]:
    phase = None if not state else state.get("phase")
    payload: Dict[str, Any] = {
        "state": state,
        "notice": _notice(message, kind),
        "who": "",
        "intro": gr.update(visible=phase in {None, "resume_prompt"}),
        "resume": gr.update(visible=phase == "resume_prompt"),
        "desc_panel": gr.update(visible=phase == "desc"),
        "aspect_panel": gr.update(visible=phase == "aspect"),
        "done_panel": gr.update(visible=phase == "done"),
        "desc_progress": "",
        "desc_audio": None,
        "desc_text_1": "",
        "desc_score_1": None,
        "desc_rich_1": None,
        "desc_text_2": "",
        "desc_score_2": None,
        "desc_rich_2": None,
        "desc_prev": gr.update(interactive=False),
        "desc_next": gr.update(value="下一题"),
        "aspect_progress": "",
        "aspect_query": "",
        "aspect_choices": "",
        "aspect_select": [],
        "aspect_prev": gr.update(value="上一题"),
        "aspect_next": gr.update(value="下一题"),
        "done_text": "",
        "done_file": gr.update(visible=False, value=None),
    }
    if state and state.get("rater_id") and phase != None:
        payload["who"] = f"被试:{html.escape(str(state['rater_id']))}"

    if phase == "desc":
        trial = STUDY.current_trial(state)
        left, right = (STUDY.desc_by_uid[uid] for uid in trial["uids"])
        stored_left = STUDY.stored_desc(state, left["uid"])
        stored_right = STUDY.stored_desc(state, right["uid"])
        index = int(state["desc_idx"])
        total = len(state["desc_trials"])
        payload.update(
            {
                "desc_progress": (
                    f"第一部分 · 准确性和丰富度 · 第 {index + 1} / {total} 题"
                    f"(音频约 {float(left.get('duration_sec') or 0):.0f} 秒)"
                ),
                "desc_audio": str((ROOT / left["audio"]).resolve()),
                "desc_text_1": left["description"],
                "desc_score_1": None if stored_left["score"] is None else str(stored_left["score"]),
                "desc_rich_1": None if stored_left["richness"] is None else str(stored_left["richness"]),
                "desc_text_2": right["description"],
                "desc_score_2": None if stored_right["score"] is None else str(stored_right["score"]),
                "desc_rich_2": None if stored_right["richness"] is None else str(stored_right["richness"]),
                "desc_prev": gr.update(interactive=index > 0),
                "desc_next": gr.update(value="进入第二部分" if index + 1 == total else "下一题"),
            }
        )
    elif phase == "aspect":
        item = STUDY.current_aspect(state)
        index = int(state["aspect_idx"])
        total = len(state["aspect_order"])
        payload.update(
            {
                "aspect_progress": f"第二部分 · 角度选择 · 第 {index + 1} / {total} 题",
                "aspect_query": item["query"],
                "aspect_choices": _choices_text(item["choices"]),
                "aspect_select": STUDY.stored_aspects(state, item["uid"]),
                "aspect_prev": gr.update(value="返回第一部分" if index == 0 else "上一题"),
                "aspect_next": gr.update(value="提交" if index + 1 == total else "下一题"),
            }
        )
    elif phase == "done":
        payload["done_text"] = (
            f"感谢你完成评测。结果已经记在「{html.escape(str(state.get('rater_id') or ''))}」名下。"
            "可以下载自己的答卷。"
        )
        payload["done_file"] = gr.update(visible=True, value=state.get("download"))
    return payload


OUTPUT_KEYS = [
    "state",
    "notice",
    "who",
    "intro",
    "resume",
    "desc_panel",
    "aspect_panel",
    "done_panel",
    "desc_progress",
    "desc_audio",
    "desc_text_1",
    "desc_score_1",
    "desc_rich_1",
    "desc_text_2",
    "desc_score_2",
    "desc_rich_2",
    "desc_prev",
    "desc_next",
    "aspect_progress",
    "aspect_query",
    "aspect_choices",
    "aspect_select",
    "aspect_prev",
    "aspect_next",
    "done_text",
    "done_file",
]


def pack(payload: Dict[str, Any]) -> tuple:
    missing = [key for key in OUTPUT_KEYS if key not in payload]
    if missing:
        raise KeyError(missing)
    return tuple(payload[key] for key in OUTPUT_KEYS)


def enter(name: str, acknowledged: bool) -> tuple:
    cleaned = _clean_name(name)
    if not cleaned:
        return pack(view(None, "请填写至少 2 个字符的姓名。"))
    if not acknowledged:
        return pack(view(None, "请先勾选「我已阅读说明」。"))
    partial = STUDY.load_partial(cleaned)
    if partial:
        desc_done, aspect_done = STUDY.progress_counts(partial)
        message = (
            f"找到未完成的进度:描述题 {desc_done}/{STUDY.n_desc},"
            f"aspect 题 {aspect_done}/{STUDY.n_aspect}。可以继续,或重新开始。"
        )
        return pack(view({"phase": "resume_prompt", "rater_id": cleaned}, message, "info"))
    return pack(view(STUDY.new_session(cleaned)))


def resume(name: str) -> tuple:
    cleaned = _clean_name(name)
    partial = STUDY.load_partial(cleaned) if cleaned else None
    if partial is None:
        return pack(view(None, "没有找到这个名字的未完成进度。"))
    return pack(view(partial))


def restart(name: str, acknowledged: bool) -> tuple:
    cleaned = _clean_name(name)
    if not cleaned:
        return pack(view(None, "请填写至少 2 个字符的姓名。"))
    if not acknowledged:
        return pack(view(None, "请先勾选「我已阅读说明」。"))
    return pack(view(STUDY.new_session(cleaned)))


def on_desc(
    state: Optional[Dict[str, Any]],
    score_left: Any,
    rich_left: Any,
    score_right: Any,
    rich_right: Any,
    step: int,
) -> tuple:
    if not state or state.get("phase") != "desc":
        return pack(view(state, "当前不在描述评测。"))
    updated, message = STUDY.move_desc(
        copy.deepcopy(state),
        score_left,
        score_right,
        rich_left,
        rich_right,
        step,
    )
    return pack(view(updated, message))


def on_aspect(state: Optional[Dict[str, Any]], selected: Any, step: int) -> tuple:
    if not state or state.get("phase") != "aspect":
        return pack(view(state, "当前不在 aspect 评测。"))
    updated, message = STUDY.move_aspect(copy.deepcopy(state), selected, step)
    return pack(view(updated, message))


def export_all(password: str) -> str:
    token = os.environ.get("MOS_ADMIN_TOKEN", "")
    path = STUDY.results / "ratings.jsonl"
    if not token:
        raise gr.Error("服务器未设置 MOS_ADMIN_TOKEN。结果写在 results/ratings.jsonl。")
    if password != token:
        raise gr.Error("密码不正确。")
    if not path.is_file():
        raise gr.Error("还没有人提交。")
    return str(path)


def build_demo() -> gr.Blocks:
    with gr.Blocks(title="语音感知人工评测") as demo:
        notice = gr.HTML()
        who = gr.HTML()
        with gr.Column() as intro:
            gr.Markdown(_intro())
            name = gr.Textbox(
                label="你的姓名",
                placeholder="例如:张三",
                info="必填。每份答卷都会记下这个姓名,用来区分是谁做的测试。",
                max_lines=1,
            )
            acknowledged = gr.Checkbox(label="我已阅读说明,会独立完成两部分评测")
            start = gr.Button("开始评测", variant="primary")
        with gr.Row(visible=False) as resume_row:
            cont = gr.Button("继续上次的进度", variant="primary")
            restart_btn = gr.Button("重新开始")
        with gr.Column(visible=False) as desc_panel:
            desc_progress = gr.Markdown()
            gr.Markdown(
                "请听完音频。每段描述打两个分。"
                "**准确性**只看写出的说法对不对,不要因为短或有遗漏而扣分。"
                "**丰富度**看这段描述覆盖了多少听到的内容。"
            )
            desc_audio = gr.Audio(label="原始音频", interactive=False, type="filepath")
            with gr.Row():
                with gr.Column():
                    desc_text_1 = gr.Textbox(label="描述 1", lines=8, interactive=False)
                    desc_score_1 = gr.Radio(
                        choices=SCORE_CHOICES,
                        label="描述 1 的准确性",
                        elem_classes=["score-stack"],
                    )
                    desc_rich_1 = gr.Radio(
                        choices=RICH_CHOICES,
                        label="描述 1 的丰富度",
                        elem_classes=["score-stack"],
                    )
                with gr.Column():
                    desc_text_2 = gr.Textbox(label="描述 2", lines=8, interactive=False)
                    desc_score_2 = gr.Radio(
                        choices=SCORE_CHOICES,
                        label="描述 2 的准确性",
                        elem_classes=["score-stack"],
                    )
                    desc_rich_2 = gr.Radio(
                        choices=RICH_CHOICES,
                        label="描述 2 的丰富度",
                        elem_classes=["score-stack"],
                    )
            with gr.Accordion("评分规则", open=False):
                gr.Markdown(RUBRIC)
            with gr.Row():
                desc_prev = gr.Button("上一题")
                desc_next = gr.Button("下一题", variant="primary")
        with gr.Column(visible=False) as aspect_panel:
            aspect_progress = gr.Markdown()
            gr.Markdown(ASPECT_GUIDE)
            with gr.Accordion("每个角度是什么", open=True):
                gr.Markdown(_catalog())
            aspect_query = gr.Textbox(label="问题", lines=3, interactive=False)
            aspect_choices = gr.Textbox(label="选项", lines=6, interactive=False)
            aspect_select = gr.CheckboxGroup(
                choices=ASPECT_CHOICES,
                label="回答当前问题需要知道哪些角度的信息",
                elem_id="aspect-select",
            )
            with gr.Row():
                aspect_prev = gr.Button("上一题")
                aspect_next = gr.Button("下一题", variant="primary")
        with gr.Column(visible=False) as done_panel:
            done_text = gr.Markdown()
            done_file = gr.File(label="下载我的答卷")
        with gr.Accordion("研究者:导出全部结果", open=False):
            gr.Markdown("需要在 Space 的 Secrets 里设置 `MOS_ADMIN_TOKEN`。被试不使用这里。")
            admin_password = gr.Textbox(label="MOS_ADMIN_TOKEN", type="password")
            admin_button = gr.Button("下载全部结果")
            admin_file = gr.File(label="ratings.jsonl")

        state = gr.State(None)
        outputs = [
            state,
            notice,
            who,
            intro,
            resume_row,
            desc_panel,
            aspect_panel,
            done_panel,
            desc_progress,
            desc_audio,
            desc_text_1,
            desc_score_1,
            desc_rich_1,
            desc_text_2,
            desc_score_2,
            desc_rich_2,
            desc_prev,
            desc_next,
            aspect_progress,
            aspect_query,
            aspect_choices,
            aspect_select,
            aspect_prev,
            aspect_next,
            done_text,
            done_file,
        ]
        if len(outputs) != len(OUTPUT_KEYS):
            raise RuntimeError(f"{len(outputs)} outputs vs {len(OUTPUT_KEYS)} keys")

        start.click(enter, [name, acknowledged], outputs, api_name="start")
        cont.click(resume, [name], outputs, api_name="resume")
        restart_btn.click(restart, [name, acknowledged], outputs, api_name="restart")
        desc_inputs = [state, desc_score_1, desc_rich_1, desc_score_2, desc_rich_2]
        desc_next.click(
            lambda state, score_left, rich_left, score_right, rich_right: on_desc(
                state, score_left, rich_left, score_right, rich_right, 1
            ),
            desc_inputs,
            outputs,
            api_name="desc_next",
        )
        desc_prev.click(
            lambda state, score_left, rich_left, score_right, rich_right: on_desc(
                state, score_left, rich_left, score_right, rich_right, -1
            ),
            desc_inputs,
            outputs,
            api_name="desc_prev",
        )
        aspect_next.click(
            lambda state, selected: on_aspect(state, selected, 1),
            [state, aspect_select],
            outputs,
            api_name="aspect_next",
        )
        aspect_prev.click(
            lambda state, selected: on_aspect(state, selected, -1),
            [state, aspect_select],
            outputs,
            api_name="aspect_prev",
        )
        admin_button.click(export_all, [admin_password], [admin_file], api_name="export_all")
    return demo


demo = build_demo()


PAGE_CSS = """
.gradio-container {
  max-width: 1080px !important;
  margin-left: auto !important;
  margin-right: auto !important;
}
.gradio-container, .gradio-container * {
  font-family: "Times New Roman", Times, serif !important;
}
#aspect-select .wrap,
.score-stack .wrap {
  flex-direction: column !important;
  flex-wrap: nowrap !important;
  align-items: stretch !important;
}
#aspect-select .wrap > label,
.score-stack .wrap > label {
  width: 100% !important;
  box-sizing: border-box !important;
  white-space: normal !important;
}
"""


if __name__ == "__main__":
    launch_kwargs = {
        "allowed_paths": [str((ROOT / "audio").resolve())],
        "theme": gr.themes.Soft(font=["Times New Roman", "Times", "serif"]),
        "css": PAGE_CSS,
    }
    if os.environ.get("MOS_PORT"):
        launch_kwargs["server_name"] = os.environ.get("MOS_HOST", "127.0.0.1")
        launch_kwargs["server_port"] = int(os.environ["MOS_PORT"])
    demo.launch(**launch_kwargs)