欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 快速使用PPASR V3版不能语音识别框架

快速使用PPASR V3版不能语音识别框架

2025/3/12 12:01:46 来源:https://blog.csdn.net/qq_33200967/article/details/146113484  浏览:    关键词:快速使用PPASR V3版不能语音识别框架

前言

本文章主要介绍如何快速使用PPASR语音识别框架训练和推理,本文将致力于最简单的方式去介绍使用,如果使用更进阶功能,还需要从源码去看文档。仅需三行代码即可实现训练和推理。

源码地址:https://github.com/yeyupiaoling/PPASR

安装环境

使用Anaconda,并创建了Python3.11的虚拟环境。

  • 首先安装的是PaddlePaddle 2.6.2 的GPU版本,如果已经安装过了,请跳过。
conda install paddlepaddle-gpu==2.6.2 cudatoolkit=11.7 -c https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/Paddle/ -c conda-forge
  • 使用pip安装PPASR库,命令如下:
python -m pip install ppasr -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()

训练

使用PPASR框架训练非常简单,核心代码就3行,如下,configs参数可以指定使用的默认配置文件。

from ppasr.trainer import PPASRTrainertrainer = PPASRTrainer(configs="conformer", use_gpu=True)trainer.train(save_model_path="models/")

输出类似如下:

2025-03-08 11:04:57.884 | INFO     | ppasr.optimizer:build_optimizer:16 - 成功创建优化方法:Adam,参数为:{'lr': 0.001, 'weight_decay': 1e-06}
2025-03-08 11:04:57.884 | INFO     | ppasr.optimizer:build_lr_scheduler:31 - 成功创建学习率衰减:WarmupLR,参数为:{'warmup_steps': 25000, 'min_lr': 1e-05}
2025-03-08 11:04:57.885 | INFO     | ppasr.trainer:train:541 - 词汇表大小:5561
2025-03-08 11:04:57.885 | INFO     | ppasr.trainer:train:542 - 训练数据:13382
2025-03-08 11:04:57.885 | INFO     | ppasr.trainer:train:543 - 评估数据:27
2025-03-08 11:04:58.642 | INFO     | ppasr.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 ppasr.trainer import PPASRTrainer# 获取训练器
trainer = PPASRTrainer(configs="conformer", use_gpu=True)# 导出预测模型
trainer.export(save_model_path='models/',resume_model='models/ConformerModel_fbank/best_model/')

推理

推理也相当简单,只需要下面三行代码即可完成语音识别。

from ppasr.predict import PPASRPredictorpredictor = PPASRPredictor(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     | ppasr.infer_utils.inference_predictor:__init__:38 - 已加载模型:models/ConformerModel_fbank/inference_model/inference.pth
2025-03-08 11:21:52.147 | INFO     | ppasr.predict:__init__:117 - 流式VAD模型已加载完成
2025-03-08 11:21:52.147 | INFO     | ppasr.predict:__init__:119 - 开始预热预测器...
2025-03-08 11:22:01.366 | INFO     | ppasr.predict:reset_predictor:471 - 重置预测器
2025-03-08 11:22:01.366 | INFO     | ppasr.predict:__init__:128 - 预测器已准备完成!
识别结果: {'text': '近几年不但我用书给女儿压岁也劝说亲朋不要给女儿压岁钱而改送压岁书', 'sentences': [{'text': '近几年不但我用书给女儿压岁也劝说亲朋不要给女儿压岁钱而改送压岁书', 'start': 0, 'end': 8.39}]}

结语

该框架支持多个语音识别模型,包含deepspeech2conformersqueezeformerefficient_conformer等,每个模型都支持流式识别和非流式识别,以及多种解码器,包含ctc_greedy_searchctc_prefix_beam_searchattention_rescoringctc_beam_search等。更多功能等你发现。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词