前言
本文章主要介绍如何快速使用MASR语音识别框架训练和推理,本文将致力于最简单的方式去介绍使用,如果使用更进阶功能,还需要从源码去看文档。仅需三行代码即可实现训练和推理。
源码地址:https://github.com/yeyupiaoling/MASR
安装环境
使用Anaconda,并创建了Python3.11的虚拟环境。
- 首先安装的是Pytorch 2.5.1 的GPU版本,如果已经安装过了,请跳过。
conda install pytorch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 pytorch-cuda=11.8 -c pytorch -c nvidia
- 使用pip安装MASR库,命令如下:
python -m pip install masr -U -i https://pypi.tuna.tsinghua.edu.cn/simple
准备数据集
执行下面代码即可自动完成下载数据,和制作数据列表。默认下载可能会比较慢,可以复制下载地址用迅雷等工具下载,并指定filepath
为下载好的文件路径,可以快速完成制作数据列表。
import argparse
import os
import functools
from utility import download, unpack
from utility import add_arguments, print_argumentsDATA_URL = 'https://openslr.trmal.net/resources/33/data_aishell.tgz'
MD5_DATA = '2f494334227864a8a8fec932999db9d8'parser = argparse.ArgumentParser(description=__doc__)
add_arg = functools.partial(add_arguments, argparser=parser)
add_arg("target_dir", default="dataset/audio/", type=str, help="存放音频文件的目录")
add_arg("annotation_text", default="dataset/annotation/", type=str, help="存放音频标注文件的目录")
add_arg("filepath", default=None, type=str, help="提前下载好的数据集压缩文件")
args = parser.parse_args()def create_annotation_text(data_dir, annotation_path):print('Create Aishell annotation text ...')if not os.path.exists(annotation_path):os.makedirs(annotation_path)f_train = open(os.path.join(annotation_path, 'aishell.txt'), 'w', encoding='utf-8')if not os.path.exists(os.path.join(annotation_path, 'test.txt')):f_test = open(os.path.join(annotation_path, 'test.txt'), 'w', encoding='utf-8')else:f_test = open(os.path.join(annotation_path, 'test.txt'), 'a', encoding='utf-8')transcript_path = os.path.join(data_dir, 'transcript', 'aishell_transcript_v0.8.txt')transcript_dict = {}for line in open(transcript_path, 'r', encoding='utf-8'):line = line.strip()if line == '': continueaudio_id, text = line.split(' ', 1)# remove spacetext = ''.join(text.split())transcript_dict[audio_id] = textdata_types = ['train', 'dev']for type in data_types:audio_dir = os.path.join(data_dir, 'wav', type)for subfolder, _, filelist in sorted(os.walk(audio_dir)):for fname in filelist:audio_path = os.path.join(subfolder, fname).replace('\\', '/')audio_id = fname[:-4]# if no transcription for audio then skippedif audio_id not in transcript_dict:continuetext = transcript_dict[audio_id]f_train.write(audio_path.replace('../', '') + '\t' + text + '\n')audio_dir = os.path.join(data_dir, 'wav', 'test')for subfolder, _, filelist in sorted(os.walk(audio_dir)):for fname in filelist:audio_path = os.path.join(subfolder, fname).replace('\\', '/')audio_id = fname[:-4]# if no transcription for audio then skippedif audio_id not in transcript_dict:continuetext = transcript_dict[audio_id]f_test.write(audio_path.replace('../', '') + '\t' + text + '\n')f_test.close()f_train.close()def prepare_dataset(url, md5sum, target_dir, annotation_path):"""Download, unpack and create manifest file."""data_dir = os.path.join(target_dir, 'data_aishell')if not os.path.exists(data_dir):if args.filepath is None:filepath = download(url, md5sum, target_dir)else:filepath = args.filepathunpack(filepath, target_dir)# unpack all audio tar filesaudio_dir = os.path.join(data_dir, 'wav')for subfolder, _, filelist in sorted(os.walk(audio_dir)):for ftar in filelist:unpack(os.path.join(subfolder, ftar), subfolder, True)os.remove(filepath)else:print("Skip downloading and unpacking. Aishell data already exists in %s." % target_dir)create_annotation_text(data_dir, annotation_path)def main():print_arguments(args)if args.target_dir.startswith('~'):args.target_dir = os.path.expanduser(args.target_dir)prepare_dataset(url=DATA_URL,md5sum=MD5_DATA,target_dir=args.target_dir,annotation_path=args.annotation_text)if __name__ == '__main__':main()
训练
使用MASR框架训练非常简单,核心代码就3行,如下,configs
参数可以指定使用的默认配置文件。
from masr.trainer import MASRTrainertrainer = MASRTrainer(configs="conformer", use_gpu=True)trainer.train(save_model_path="models/")
输出类似如下:
2025-03-08 11:04:57.884 | INFO | masr.optimizer:build_optimizer:16 - 成功创建优化方法:Adam,参数为:{'lr': 0.001, 'weight_decay': 1e-06}
2025-03-08 11:04:57.884 | INFO | masr.optimizer:build_lr_scheduler:31 - 成功创建学习率衰减:WarmupLR,参数为:{'warmup_steps': 25000, 'min_lr': 1e-05}
2025-03-08 11:04:57.885 | INFO | masr.trainer:train:541 - 词汇表大小:5561
2025-03-08 11:04:57.885 | INFO | masr.trainer:train:542 - 训练数据:13382
2025-03-08 11:04:57.885 | INFO | masr.trainer:train:543 - 评估数据:27
2025-03-08 11:04:58.642 | INFO | masr.trainer:__train_epoch:414 - Train epoch: [1/200], batch: [0/836], loss: 51.60880, learning_rate: 0.00000008, reader_cost: 0.1062, batch_cost: 0.6486, ips: 21.1991 speech/sec, eta: 1 day, 11:03:13
导出模型
训练完成之后还需要导出模型才能进行推理,导出模型也非常简单。需要三行代码,如下:
from masr.trainer import MASRTrainer# 获取训练器
trainer = MASRTrainer(configs="conformer", use_gpu=True)# 导出预测模型
trainer.export(save_model_path='models/',resume_model='models/ConformerModel_fbank/best_model/')
推理
推理也相当简单,只需要下面三行代码即可完成语音识别。
from masr.predict import MASRPredictorpredictor = MASRPredictor(model_dir="models/ConformerModel_fbank/inference_model/", use_gpu=True)audio_path = "dataset/test.wav"
result = predictor.predict(audio_data=audio_path)
print(f"识别结果: {result}")
输出如下:
2025-03-08 11:21:52.100 | INFO | masr.infer_utils.inference_predictor:__init__:38 - 已加载模型:models/ConformerModel_fbank/inference_model/inference.pth
2025-03-08 11:21:52.147 | INFO | masr.predict:__init__:117 - 流式VAD模型已加载完成
2025-03-08 11:21:52.147 | INFO | masr.predict:__init__:119 - 开始预热预测器...
2025-03-08 11:22:01.366 | INFO | masr.predict:reset_predictor:471 - 重置预测器
2025-03-08 11:22:01.366 | INFO | masr.predict:__init__:128 - 预测器已准备完成!
识别结果: {'text': '近几年不但我用书给女儿压岁也劝说亲朋不要给女儿压岁钱而改送压岁书', 'sentences': [{'text': '近几年不但我用书给女儿压岁也劝说亲朋不要给女儿压岁钱而改送压岁书', 'start': 0, 'end': 8.39}]}
结语
该框架支持多个语音识别模型,包含deepspeech2
、conformer
、squeezeformer
、efficient_conformer
等,每个模型都支持流式识别和非流式识别,以及多种解码器,包含ctc_greedy_search
、ctc_prefix_beam_search
、attention_rescoring
、ctc_beam_search
等。更多功能等你发现。