""" 粤语 ASR 推理入口脚本。 本地开发(input.jsonl → output.jsonl): python predict.py --input_jsonl input.jsonl --output_jsonl output.jsonl 平台提交(与评测容器协议一致): python predict.py --audio_dir <音频根目录> --test_list <列表文件> --output_jsonl <输出路径> 选手需自行实现 transcribe() 中的 ASR 推理逻辑。 """ import argparse import csv import json import os import random from typing import Any AUDIO_PATH_KEYS = ("audio_path_1", "audio_path_2", "audio_path") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="ASR inference entry script") parser.add_argument("--input_jsonl", type=str, help="本地输入 JSONL(含 audio_path、pred_text)") parser.add_argument("--output_jsonl", type=str, required=True, help="预测结果输出 JSONL 路径") parser.add_argument( "--audio_dir", type=str, default="", help="音频根目录;平台评测时由容器传入;本地可与 input.jsonl 中的相对路径拼接", ) parser.add_argument( "--test_list", type=str, help="平台评测用音频列表(CSV 或 JSONL,须含 audio_path 字段)", ) return parser.parse_args() def _audio_names_from_row(row: dict) -> list[str]: """从 verify 行提取音频文件名。新格式为 audio_path_1 / audio_path_2,旧格式为 audio_path。""" names: list[str] = [] seen: set[str] = set() for key in AUDIO_PATH_KEYS: raw = row.get(key) if raw is None: continue name = os.path.basename(str(raw).strip()) if not name or name in seen: continue seen.add(name) names.append(name) return names def _load_verify_refs(script_dir: str) -> dict[str, str]: """从 verify.jsonl 或 verify.csv 加载 audio 文件名 -> ref_text 映射。""" refs: dict[str, str] = {} verify_jsonl = os.path.join(script_dir, "verify.jsonl") if os.path.isfile(verify_jsonl): for row in read_jsonl(verify_jsonl): ref_text = str(row["ref_text"]) for name in _audio_names_from_row(row): refs[name] = ref_text return refs verify_csv = os.path.join(script_dir, "verify.csv") if os.path.isfile(verify_csv): with open(verify_csv, "r", encoding="utf-8-sig") as f: reader = csv.DictReader(f) for row in reader: ref_text = str(row["ref_text"]) for name in _audio_names_from_row(row): refs[name] = ref_text return refs raise FileNotFoundError(f"未找到 verify.jsonl 或 verify.csv: {script_dir}") def _build_shuffled_pred_map(ref_by_audio: dict[str, str], rng: random.Random) -> dict[str, str]: """将 verify 中的 ref_text 随机打乱后映射到各音频。""" names = sorted(ref_by_audio.keys(), key=lambda n: int(os.path.splitext(n)[0])) ref_texts = [ref_by_audio[name] for name in names] shuffled = ref_texts[:] rng.shuffle(shuffled) return dict(zip(names, shuffled)) def load_model() -> dict[str, Any]: """ 示例实现:加载 verify 参考答案,并随机打乱后映射到各音频。 正式提交时请替换为真实 ASR 模型加载逻辑。 """ script_dir = os.path.dirname(os.path.abspath(__file__)) ref_by_audio = _load_verify_refs(script_dir) rng = random.Random() return { "pred_by_audio": _build_shuffled_pred_map(ref_by_audio, rng), } def transcribe(model: dict[str, Any], audio_path: str) -> str: """ 示例实现:返回打乱顺序后的 ref_text(非真实 ASR)。 正式提交时请替换为真实 ASR 推理逻辑。 """ name = os.path.basename(audio_path) return model["pred_by_audio"].get(name, "") def read_jsonl(path: str) -> list[dict]: records: list[dict] = [] with open(path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue records.append(json.loads(line)) return records def write_jsonl(path: str, records: list[dict]) -> None: out_dir = os.path.dirname(os.path.abspath(path)) if out_dir: os.makedirs(out_dir, exist_ok=True) with open(path, "w", encoding="utf-8") as f: for row in records: f.write(json.dumps(row, ensure_ascii=False) + "\n") def resolve_audio_path(audio_path: str, audio_dir: str) -> str: if audio_dir and not os.path.isabs(audio_path): return os.path.normpath(os.path.join(audio_dir, audio_path)) return os.path.normpath(audio_path) def read_test_list(path: str) -> list[str]: """从 CSV 或 JSONL 读取 audio_path 列表(保持原顺序)。""" ext = os.path.splitext(path)[1].lower() paths: list[str] = [] if ext == ".jsonl": for row in read_jsonl(path): paths.append(str(row["audio_path"]).strip()) return paths with open(path, "r", encoding="utf-8-sig") as f: reader = csv.DictReader(f) if not reader.fieldnames or "audio_path" not in reader.fieldnames: raise ValueError(f"test_list 须包含 audio_path 列,当前列: {reader.fieldnames}") for row in reader: paths.append(str(row["audio_path"]).strip()) return paths def run_from_input_jsonl(args: argparse.Namespace) -> None: records = read_jsonl(args.input_jsonl) model = load_model() output_records: list[dict] = [] total = len(records) for idx, row in enumerate(records, start=1): rel_path = str(row["audio_path"]).strip() abs_path = resolve_audio_path(rel_path, args.audio_dir) pred_text = "" if os.path.isfile(abs_path): try: pred_text = transcribe(model, abs_path) except Exception as exc: print(f"识别失败 {abs_path}: {exc}") else: print(f"[{idx}/{total}] 警告: 音频不存在 {abs_path}") output_records.append({"audio_path": rel_path, "pred_text": pred_text}) if idx % 100 == 0: print(f"已处理 {idx}/{total} 条...") write_jsonl(args.output_jsonl, output_records) print(f"预测结果已写入 {args.output_jsonl}") def run_from_test_list(args: argparse.Namespace) -> None: if not args.audio_dir: raise ValueError("使用 --test_list 时必须提供 --audio_dir") audio_paths = read_test_list(args.test_list) model = load_model() total = len(audio_paths) output_records: list[dict] = [] for idx, rel_path in enumerate(audio_paths, start=1): abs_path = os.path.join(args.audio_dir, rel_path) pred_text = "" if os.path.isfile(abs_path): try: pred_text = transcribe(model, abs_path) except Exception as exc: print(f"识别失败 {abs_path}: {exc}") else: print(f"[{idx}/{total}] 警告: 音频不存在 {abs_path}") output_records.append({"audio_path": rel_path, "pred_text": pred_text}) if idx % 100 == 0: print(f"已处理 {idx}/{total} 条...") write_jsonl(args.output_jsonl, output_records) print(f"预测结果已写入 {args.output_jsonl}") def main() -> None: args = parse_args() if args.input_jsonl: run_from_input_jsonl(args) elif args.test_list: run_from_test_list(args) else: raise SystemExit("请提供 --input_jsonl(本地开发)或 --test_list + --audio_dir(平台评测)") if __name__ == "__main__": main()