#!/usr/bin/env python3 """从公开数据集重新抽一遍语音题,并合成新功能题的音频。正常跑分不需要它:抽好的音频已经在 ime/voice/audio/ 里。 python3 -I ime/voice/fetch.py [--parts aishell,cv,ascend,features] [--cache DIR] - 抽样用固定种子(SEED),数据集钉在固定的提交(REV),重跑抽到的是同一批;题表里记了每条 PCM 的 sha256 前 16 位,可以对。 - 原始数据下到仓库外:默认 ~/.cache/luoke-bench/voice/raw/<数据集>/(环境变量 LUOKE_BENCH_CACHE 或 --cache 可改), 每个数据集一个新建的目录。下载的文件是不受信任的数据:只读、只解析,不在里面执行任何东西。 要的磁盘:AISHELL-1 测试集 parquet 约 1.14 GB + 官方转写 10 MB;Common Voice zh-CN 测试集 tar 约 0.51 GB + 3 MB; ASCEND 测试集 parquet 约 0.11 GB。合计约 1.8 GB(跑完可以删)。仓库里的 FLAC 合计约几十 MB。 - 抽中的音频转成 16 kHz 单声道 PCM16,存成 ime/voice/audio/<部分>/<编号>.flac;题表写到 ime/voice/sets/<部分>.tsv。 - features:照 sets/features.tsv 用 Qwen3-TTS(Apache-2.0,见 synth())合成,前后各垫 0.2 秒静音(和 luoke-ime 的 evals/transcribe 一样);静音、底噪用固定种子生成。 - 依赖:ffmpeg 或 afconvert;aishell、ascend 读 parquet 要 pyarrow(python3 -m venv ~/.cache/luoke-bench/venv && ~/.cache/luoke-bench/venv/bin/pip install pyarrow,再用那个 python 跑)。在国内可设 HF_ENDPOINT=https://hf-mirror.com。 """ import argparse import csv import os import random import subprocess import sys import tarfile import time import unicodedata import urllib.request sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import common # noqa: E402 SEED = 20261109 HF = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/") REV = { "TwinkStart/AISHELL-1": "2a509ef3a7a88d3234205eaeecba39fdd9d50518", # AISHELL-1 测试集(7176 条)的 parquet 镜像 "AISHELL/AISHELL-1": "bbe295d530192a4cd41644b711c9aecd087df653", # 官方组织:只用它的转写(答案以它为准) "fsicoli/common_voice_17_0": "8262c16bf297c87a9cd88c51997c4758ed7a8ba2", # Common Voice 17.0 的镜像(CC0) "CAiRE/ASCEND": "737e9800ae31be9932ba8464c80366559bd28424", # ASCEND(CC BY-SA 4.0),作者组织 } COUNTS = {"aishell": 150, "cv": 100, "ascend": 50} def url(repo, path): return f"{HF}/datasets/{repo}/resolve/{REV[repo]}/{path}" def download(repo, path, dest_dir): """下载到 dest_dir(已有同样大小的就不重下);断了从断点接着下。""" os.makedirs(dest_dir, exist_ok=True) dst = os.path.join(dest_dir, os.path.basename(path)) u = url(repo, path) for attempt in range(6): try: head = urllib.request.urlopen(urllib.request.Request(u, method="HEAD"), timeout=60) size = int(head.headers.get("Content-Length") or 0) if os.path.exists(dst) and (not size or os.path.getsize(dst) == size): return dst part = dst + ".part" have = os.path.getsize(part) if os.path.exists(part) else 0 req = urllib.request.Request(u, headers={"Range": f"bytes={have}-"} if have else {}) with urllib.request.urlopen(req, timeout=120) as r, open(part, "ab" if have and r.status == 206 else "wb") as f: done, t0 = (have if r.status == 206 else 0), time.time() while True: b = r.read(1 << 20) if not b: break f.write(b) done += len(b) if time.time() - t0 > 10: print(f" {os.path.basename(path)} {done / 1e6:.0f}/{size / 1e6:.0f} MB", file=sys.stderr, flush=True) t0 = time.time() if size and os.path.getsize(part) != size: raise IOError("大小不对") os.replace(part, dst) return dst except Exception as e: # noqa: BLE001 print(f" 下载 {path} 出错({type(e).__name__}: {e}),重试", file=sys.stderr, flush=True) time.sleep(3 * (attempt + 1)) raise SystemExit(f"下载失败:{u}") def need_pyarrow(): try: import pyarrow.parquet as pq # noqa: F401 return pq except ImportError: raise SystemExit("读 parquet 要 pyarrow:python3 -m venv ~/.cache/luoke-bench/venv && " "~/.cache/luoke-bench/venv/bin/pip install pyarrow,再用 ~/.cache/luoke-bench/venv/bin/python -I 跑") def is_cjk(c): return unicodedata.category(c) == "Lo" and ("㐀" <= c <= "鿿" or "豈" <= c <= "﫿") def convert_bytes(data, suffix, work): """parquet、tar 里取出来的音频字节 → PCM。写进 work(新建的临时目录)再转。""" p = os.path.join(work, "in" + suffix) with open(p, "wb") as f: f.write(data) try: return common.to_pcm(p) finally: os.remove(p) def save(part, rows, header, comment, audio=None): path = common.write_set(part, header, rows, comment) print(f"{part}: {len(rows)} 条 → {os.path.relpath(path, common.HERE)},音频 → audio/{audio or part}/", flush=True) # ---------------- AISHELL-1 测试集:按说话人分层 ---------------- def aishell(cache, work): pq = need_pyarrow() raw = os.path.join(cache, "raw", "aishell1") trans = download("AISHELL/AISHELL-1", "data_aishell/transcript/aishell_transcript_v0.8.txt", raw) files = [download("TwinkStart/AISHELL-1", f"data/test-0000{i}-of-00003.parquet", raw) for i in range(3)] official = {} with open(trans, encoding="utf-8") as f: for line in f: k, _, v = line.strip().partition(" ") official[k] = v.replace(" ", "") utts, mismatch = {}, 0 for p in files: t = pq.read_table(p, columns=["name", "text"]).to_pydict() for name, text in zip(t["name"], t["text"]): ref = official.get(name) if ref is None or ref != text.replace(" ", ""): mismatch += 1 continue utts.setdefault(name[6:11], []).append((name, ref)) print(f"aishell: 测试集 {sum(len(v) for v in utts.values())} 条(和官方转写对不上、去掉的 {mismatch} 条),说话人 {len(utts)} 个", flush=True) rng = random.Random(SEED) spk = sorted(utts) base, extra = divmod(COUNTS["aishell"], len(spk)) lucky = set(rng.sample(spk, extra)) chosen = {} for s in spk: for name, ref in rng.sample(sorted(utts[s]), base + (s in lucky)): chosen[name] = (s, ref) rows = [] order = sorted(chosen, key=lambda n: (chosen[n][0], n)) ids = {n: "a%03d" % (i + 1) for i, n in enumerate(order)} for p in files: t = pq.read_table(p, columns=["name", "audio"]).to_pydict() for name, a in zip(t["name"], t["audio"]): if name not in chosen: continue pcm = convert_bytes(a["bytes"], os.path.splitext(a.get("path") or "x.wav")[1] or ".wav", work) common.write_flac(pcm, common.audio_path("aishell", ids[name])) rows.append(dict(id=ids[name], cat="read", ref=chosen[name][1], source=name, secs=round(len(pcm) / 2 / common.SR, 2), pcm_sha256=common.sha(pcm), note="speaker " + chosen[name][0])) rows.sort(key=lambda r: r["id"]) assert len(rows) == COUNTS["aishell"], len(rows) save("aishell", rows, ["id", "cat", "ref", "source", "secs", "pcm_sha256", "note"], f""" 真人朗读普通话:AISHELL-1 测试集(Apache 2.0),{len(spk)} 个说话人按人分层抽 {COUNTS['aishell']} 条(每人 {base} 或 {base + 1} 条),种子 {SEED}。 答案是官方转写 aishell_transcript_v0.8.txt(去掉分词空格);音频取自 TwinkStart/AISHELL-1@{REV['TwinkStart/AISHELL-1'][:7]} 的测试集 parquet, 和官方转写对不上的不抽。source 是官方的句子编号。重抽:fetch.py --parts aishell。""") # ---------------- Common Voice 17.0 zh-CN 测试集 ---------------- def cv(cache, work): raw = os.path.join(cache, "raw", "commonvoice17-zhCN") tsv = download("fsicoli/common_voice_17_0", "transcript/zh-CN/test.tsv", raw) tar = download("fsicoli/common_voice_17_0", "audio/zh-CN/test/zh-CN_test_0.tar", raw) by_client = {} with open(tsv, encoding="utf-8", newline="") as f: for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): s = r["sentence"].strip() letters = [c for c in s if unicodedata.category(c)[0] in "LN"] if not letters or not all(is_cjk(c) for c in letters): # 只要纯汉字的句子:数字、英文的读法不统一 continue if not 6 <= len(letters) <= 30 or int(r.get("down_votes") or 0) > 0 or int(r.get("up_votes") or 0) < 2: continue by_client.setdefault(r["client_id"], []).append(r) rng = random.Random(SEED) clients = rng.sample(sorted(by_client), COUNTS["cv"]) # 每个说话人最多一条 chosen = {} for c in clients: r = rng.choice(sorted(by_client[c], key=lambda x: x["path"])) chosen[r["path"]] = r print(f"cv: 合格的句子来自 {len(by_client)} 个说话人,抽 {len(chosen)} 人各一条", flush=True) ids = {p: "c%03d" % (i + 1) for i, p in enumerate(sorted(chosen))} rows = [] with tarfile.open(tar, mode="r|") as tf: # 流式读:只取抽中的成员的字节,不解包到磁盘 for m in tf: base = os.path.basename(m.name) if not m.isfile() or base not in chosen: continue pcm = convert_bytes(tf.extractfile(m).read(), ".mp3", work) r = chosen[base] common.write_flac(pcm, common.audio_path("cv", ids[base])) note = " ".join(x for x in (r.get("gender"), r.get("age"), (r.get("accents") or "").replace(" ", "")) if x) rows.append(dict(id=ids[base], cat="cv", ref=r["sentence"].strip(), source=base, secs=round(len(pcm) / 2 / common.SR, 2), pcm_sha256=common.sha(pcm), note=note)) rows.sort(key=lambda r: r["id"]) assert len(rows) == COUNTS["cv"], len(rows) save("cv", rows, ["id", "cat", "ref", "source", "secs", "pcm_sha256", "note"], f""" 真人、众包录音(各人自己的设备和环境):Common Voice 17.0 zh-CN 测试集(CC0),取自 fsicoli/common_voice_17_0@{REV['fsicoli/common_voice_17_0'][:7]}。 只要纯汉字、6–30 字、赞成票不少于 2 且没有反对票的句子;每个说话人最多一条,抽 {COUNTS['cv']} 人,种子 {SEED}。原始音频是 48 kHz mp3。 注意:Common Voice 也是照稿念的,比 AISHELL 杂(口音、设备、底噪),但不是即兴说话。重抽:fetch.py --parts cv。""") # ---------------- ASCEND 测试集:中英混说 ---------------- def ascend(cache, work): pq = need_pyarrow() raw = os.path.join(cache, "raw", "ascend") p = download("CAiRE/ASCEND", "main/test-00000-of-00001.parquet", raw) t = pq.read_table(p, columns=["id", "transcription", "duration", "language", "original_speaker_id", "session_id", "topic"]).to_pylist() ok = [] for r in t: s = r["transcription"] if r["language"] != "mixed" or not 1.5 <= r["duration"] <= 12 or any(c in s for c in "[]<>{}()#*"): continue if not any(is_cjk(c) for c in s) or not any("a" <= c.lower() <= "z" for c in s): continue ok.append(r) by_spk = {} for r in ok: by_spk.setdefault(r["original_speaker_id"], []).append(r) rng = random.Random(SEED) for k in by_spk: by_spk[k] = sorted(by_spk[k], key=lambda r: r["id"]) rng.shuffle(by_spk[k]) spk = sorted(by_spk) rng.shuffle(spk) chosen, i = [], 0 while len(chosen) < COUNTS["ascend"]: # 轮流从每个说话人取,人人差不多 k = spk[i % len(spk)] if by_spk[k]: chosen.append(by_spk[k].pop()) i += 1 print(f"ascend: 混说、1.5–12 秒的 {len(ok)} 条,{len(spk)} 个说话人,轮流抽 {len(chosen)} 条", flush=True) ids = {r["id"]: "m%03d" % (n + 1) for n, r in enumerate(sorted(chosen, key=lambda r: r["id"]))} want = {r["id"]: r for r in chosen} rows = [] for r in pq.read_table(p, columns=["id", "audio"]).to_pylist(): if r["id"] not in want: continue a = r["audio"] pcm = convert_bytes(a["bytes"], os.path.splitext(a.get("path") or "x.wav")[1] or ".wav", work) m = want[r["id"]] common.write_flac(pcm, common.audio_path("ascend", ids[r["id"]])) rows.append(dict(id=ids[r["id"]], cat="mixed", ref=m["transcription"].strip(), source=r["id"], secs=round(len(pcm) / 2 / common.SR, 2), pcm_sha256=common.sha(pcm), note=f"speaker {m['original_speaker_id']} session {m['session_id']} {m['topic']}")) rows.sort(key=lambda r: r["id"]) assert len(rows) == COUNTS["ascend"], len(rows) save("ascend", rows, ["id", "cat", "ref", "source", "secs", "pcm_sha256", "note"], f""" 中英混说(即兴对话):ASCEND 测试集(CC BY-SA 4.0),取自 CAiRE/ASCEND@{REV['CAiRE/ASCEND'][:7]}。 只要 language=mixed、1.5–12 秒、转写里没有标记符号的;按说话人轮流抽 {COUNTS['ascend']} 条,种子 {SEED}。答案是数据集的转写原样(英文按词算)。 重抽:fetch.py --parts ascend。""") # ---------------- 新功能题:自己写的句子,开源 TTS 合成 ---------------- def tone(kind, db, secs, seed): """静音、白噪声、50 Hz 嗡声(加一点白噪声)。db 是相对满幅的 dBFS。""" import math rng = random.Random(seed) n = int(secs * common.SR) amp = 32767 * 10 ** (db / 20) if db else 0 out = bytearray() for i in range(n): if kind == "silence": v = 0 elif kind == "noise": v = rng.gauss(0, amp) else: # hum v = amp * math.sin(2 * math.pi * 50 * i / common.SR) + rng.gauss(0, amp / 10) out += int(max(-32768, min(32767, round(v)))).to_bytes(2, "little", signed=True) return bytes(out) # Qwen3-TTS 1.7B CustomVoice(Apache-2.0),MLX 版,钉在固定提交;声音 vivian(内置的中文女声)。 TTS_MODEL = ("mlx-community/Qwen3-TTS-12Hz-1.7B-CustomVoice-bf16", "52f4770fd9726457eae3d3b6aa92047a25a10776", "vivian") def synth_once(text, work, py, model_dir): voice = TTS_MODEL[2] subprocess.run([py, "-m", "mlx_audio.tts.generate", "--model", model_dir, "--text", text, "--voice", voice, "--lang_code", "chinese", "--temperature", "0.3", "--output_path", work, "--file_prefix", "tts", "--audio_format", "wav"], check=True, capture_output=True) src = os.path.join(work, "tts_000.wav") pcm = subprocess.run(["ffmpeg", "-v", "error", "-i", src, "-ac", "1", "-ar", str(common.SR), "-f", "s16le", "-"], check=True, capture_output=True).stdout os.remove(src) pad = bytes(int(0.2 * common.SR) * 2) return pad + pcm + pad def plain(t): return [c for c in unicodedata.normalize("NFKC", t).lower() if c.isalnum()] def cer(ref, hyp): r, h = plain(ref), plain(hyp) d = list(range(len(h) + 1)) for i, rc in enumerate(r, 1): prev, d[0] = d[0], i for j, hc in enumerate(h, 1): prev, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, prev + (rc != hc)) return d[-1] / max(1, len(r)) def transcribe(pcm, work, asr_py): p = os.path.join(work, "check.flac") common.write_flac(pcm, p) out = subprocess.run([asr_py, "-c", "import sys, mlx_whisper; print(mlx_whisper.transcribe(sys.argv[1], " "path_or_hf_repo='mlx-community/whisper-large-v3-turbo', language='zh', " "initial_prompt='以下是普通话的句子。')['text'])", p], check=True, capture_output=True, text=True).stdout.strip().splitlines() os.remove(p) return out[-1] if out else "" def synth(text, work, tries=4): """用 Qwen3-TTS 念一句:经 mlx-audio,在单独的 venv 里跑($LUOKE_TTS_PYTHON,默认 ~/.cache/luoke-bench/tts-venv/bin/python, 装法 pip install mlx-audio)。温度 0.3;输出 24 kHz,用 ffmpeg 转成 16 kHz 单声道,前后各垫 0.2 秒静音。 合成有随机性,偶尔念错字、单字念走样,所以给了 $LUOKE_ASR_PYTHON(装了 mlx-whisper 的 python)时,每句最多合成 tries 遍, 用 whisper-large-v3-turbo 转写,留字错率最低的一遍(念得一字不差就不再试)。生僻人名、虚构产品名几遍都会被认错, 不影响挑选。重合成的音频和仓库里的不会逐字节一样;跑分用仓库里的 FLAC。""" py = os.environ.get("LUOKE_TTS_PYTHON") or os.path.expanduser("~/.cache/luoke-bench/tts-venv/bin/python") asr_py = os.environ.get("LUOKE_ASR_PYTHON") repo, rev, _ = TTS_MODEL model_dir = subprocess.run([py, "-c", "from huggingface_hub import snapshot_download; " f"print(snapshot_download('{repo}', revision='{rev}'))"], check=True, capture_output=True, text=True).stdout.strip().splitlines()[-1] best = None for _ in range(tries if asr_py else 1): pcm = synth_once(text, work, py, model_dir) if not asr_py: return pcm heard = transcribe(pcm, work, asr_py) score = cer(text, heard) if best is None or score < best[0]: best = (score, pcm, heard) if score == 0: break print(f" {text} → {best[2]}(字错率 {best[0]:.2f})", flush=True) return best[1] def features(cache, work): rows = common.read_set("features") out = [] for n, r in enumerate(rows): spec = r["spec"].split(":") if r["spec"] else [] if spec: # silence:秒 / noise:dB:秒 / hum:dB:秒 kind = spec[0] db = float(spec[1]) if len(spec) == 3 else 0 pcm = tone(kind, db, float(spec[-1]), SEED + n) else: pcm = synth(r["say"] or r["ref"], work) common.write_flac(pcm, common.audio_path("features", r["id"])) out.append(dict(id=r["id"], secs=round(len(pcm) / 2 / common.SR, 2), pcm_sha256=common.sha(pcm))) save("features_audio", out, ["id", "secs", "pcm_sha256"], """ features.tsv 各题合成出来的音频(audio/features/<编号>.flac)的长度和 PCM 的 sha256 前 16 位。fetch.py --parts features 生成。 用 Qwen3-TTS 1.7B CustomVoice(Apache-2.0,声音 vivian)合成;仓库里的 FLAC 才是跑分用的那份。""", audio="features") PARTS = {"aishell": aishell, "cv": cv, "ascend": ascend, "features": features} def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--parts", default=",".join(PARTS)) ap.add_argument("--cache", default=common.CACHE) a = ap.parse_args() common.tool() import tempfile for part in [p for p in a.parts.split(",") if p]: if part not in PARTS: raise SystemExit("没有这个部分:" + part) with tempfile.TemporaryDirectory(prefix="luoke-voice-fetch-") as work: PARTS[part](os.path.expanduser(a.cache), work) if __name__ == "__main__": main()