ubuntu利用whisper和funASR-语者分离-二值化

打印 上一主题 下一主题

主题 2007|帖子 2007|积分 6021

一、选择体系



这个镜像可以

1.1 更新情况

python -m pip install --upgrade pip

二、安装利用whisper

我在另一篇博客也写道,互相交流学习
whisper-深入-语者分离
2.1 创建情况

  1. # ssh登录系统
  2. # 切换到root用户
  3. mkdir /opt/tools/
  4. cd /opt/tools/
  5. # 安装miniconda
  6. wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
  7. chmod +x Miniconda3-latest-Linux-x86_64.sh
  8. ./Miniconda3-latest-Linux-x86_64.sh
  9. #按提示操作,安装目录建议选择/opt/miniconda3
  10. #创建软链接
  11. ln -s /opt/miniconda3/bin/conda /usr/local/bin/conda
  12. #退出shell重新登陆,然后后续操作
  13. #创建环境
  14. conda create -n whisper python=3.9
  15. conda activate whisper
复制代码
2.1 安装

2.1.1安装底子包

  1. pip install -U openai-whisper
  2. 或者
  3. pip install git+https://github.com/openai/whisper.git
  4. 或者
  5. pip install -i https://pypi.tuna.tsinghua.edu.cn/simple openai-whisper
复制代码
2.1.2安装依靠

  1. pip install tiktoken
  2. pip install setuptools-rust
  3. #在conda whisper环境外执行,安装ffmpeg
  4. sudo apt update && sudo apt install ffmpeg
复制代码
3测试1

  1. whisper audio.mp3 --model medium --language Chinese
复制代码
代码调用
  1. import whisper
  2. import arrow
  3. # 定义模型、音频地址、录音开始时间
  4. def excute(model_name,file_path,start_time):
  5.     model = whisper.load_model(model_name)
  6.     result = model.transcribe(file_path)
  7.     for segment in result["segments"]:
  8.         now = arrow.get(start_time)
  9.         start = now.shift(seconds=segment["start"]).format("YYYY-MM-DD HH:mm:ss")
  10.         end = now.shift(seconds=segment["end"]).format("YYYY-MM-DD HH:mm:ss")
  11.         print("【"+start+"->" +end+"】:"+segment["text"])
  12. if __name__ == '__main__':
  13.     excute("base","1001.mp3","2022-10-24 16:23:00")
复制代码
3测试2 语着分离

创建key

https://huggingface.co/settings/tokens
创建代码



  • cache_dir:模型啥的下载后存放位置
  • use_auth_token :创建的key
  1. import os
  2. import whisper
  3. from pyannote.audio import Pipeline
  4. from pyannote_whisper.utils import diarize_text
  5. import concurrent.futures
  6. pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization", use_auth_token="你申请的key",cache_dir="/root/autodl-tmp/whisper/env")
  7. output_dir = '/root/autodl-tmp/pyannote-whisper'
  8. def process_audio(file_path):
  9.     model = whisper.load_model("large")
  10.     asr_result = model.transcribe(file_path, initial_prompt="语音转换")
  11.     diarization_result = pipeline(file_path)
  12.     final_result = diarize_text(asr_result, diarization_result)
  13.     output_file = os.path.join(output_dir, os.path.basename(file_path)[:-4] + '.txt')
  14.     with open(output_file, 'w') as f:
  15.         for seg, spk, sent in final_result:
  16.             line = f'{seg.start:.2f} {seg.end:.2f} {spk} {sent}\n'
  17.             f.write(line)
  18. if not os.path.exists(output_dir):
  19.     os.makedirs(output_dir)
  20. wave_dir = '/root/autodl-tmp/pyannote-whisper'
  21. # 获取当前目录下所有wav文件名
  22. wav_files = [os.path.join(wave_dir, file) for file in os.listdir(wave_dir) if file.endswith('.wav')]
  23. # 处理每个wav文件
  24. with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
  25.     executor.map(process_audio, wav_files)
  26. print('处理完成!')
复制代码
报错ModuleNotFoundError: No module named 'pyannote'


解决方案
  1. pip install  pyannote.audio
复制代码
报错No module named 'pyannote_whisper'

如果你利用利用AutoDL平台,你可以利用学术代理加速
  1. source /etc/network_turbo
复制代码
  1. git clone https://github.com/yinruiqing/pyannote-whisper.git
  2. cd pyannote-whisper
  3. pip install -r requirements.txt
复制代码

这个错误可能是由于缺少或不正确安装了所需的 sndfile 库。sndfile 是一个用于处理音频文件的库,它提供了多种格式的读写支持。
你可以尝试安装 sndfile 库,方法如下:
在 Ubuntu 上,利用以下命令安装:sudo apt-get install libsndfile1-dev
在 CentOS 上,利用以下命令安装:sudo yum install libsndfile-devel
在 macOS 上,利用 Homebrew 安装:brew install libsndfile
然后重新执行如上指令
在项目内里写代码就可以了,大概复制代码内里的pyannote_whisper.utils模块代码

三、安装利用funASR

1 安装

官网
1.1 安装 Conda(可选)

  1. wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
  2. sh Miniconda3-latest-Linux-x86_64.sh
  3. source ~/.bashrc
  4. conda create -n funasr python=3.8
  5. conda activate funasr
复制代码
1.2 安装 Pytorch(版本 >= 1.11.0)

  1. pip3 install torch torchaudio
复制代码
如果您的情况中存在CUDA,您应该安装与CUDA匹配的版本的pytorch。匹配列表可以在docs中找到。
1.3 安装funASR

从 pip 安装
  1. pip3 install -U funasr
  2. # 对于中国的用户,您可以使用以下命令进行安装:
  3. # pip3 install -U funasr -i https://mirror.sjtu.edu.cn/pypi/web/simple
复制代码
大概从源码安装funASR
  1. git clone https://github.com/alibaba/FunASR.git && cd FunASR
  2. pip3 install -e ./
复制代码
1.4 安装 modelscope(可选)

如果您想利用 ModelScope 中的预练习模型,您应该安装 modelscope:
  1. pip3 install -U modelscope
  2. # 对于中国的用户,您可以使用以下命令进行安装:
  3. # pip3 install -U modelscope -i https://mirror.sjtu.edu.cn/pypi/web/simple
复制代码
1.5 如何从当地模型路径推断(可选)

通过 modelscope-sdk 将模型下载到当地目录
  1. from modelscope.hub.snapshot_download import snapshot_download
  2. local_dir_root = "./models_from_modelscope"
  3. model_dir = snapshot_download('damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch', cache_dir=local_dir_root)
复制代码
大概通过 git lfs 将模型下载到当地目录
  1. git lfs install
  2. # git clone https://www.modelscope.cn/<namespace>/<model-name>.git
  3. git clone https://www.modelscope.cn/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch.git
复制代码
利用当地模型路径举行推断
  1. local_dir_root = "./models_from_modelscope/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch"
  2. inference_pipeline = pipeline(
  3.     task=Tasks.auto_speech_recognition,
  4.     model=local_dir_root,
  5. )
复制代码
2 利用funASR

2.1 利用funASR

  1. from modelscope.pipelines import pipeline
  2. from modelscope.utils.constant import Tasks
  3. inference_pipeline = pipeline(
  4.     task=Tasks.auto_speech_recognition,
  5.     model='damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
  6.     model_revision="v1.2.4")
  7. rec_result = inference_pipeline(audio_in='1001.wav')
  8. print(rec_result['sentences'])
  9. with open('result.txt', 'w', encoding='utf-8') as f:
  10.     print(rec_result, file=f)
  11. print(rec_result)
复制代码

2.2 利用 pyannote.audio 举行语者分离

第一步:安装依靠

  1. pip install pyannote.audio
复制代码
第二步:创建key

https://huggingface.co/settings/tokens

第三步:测试pyannote.audio

  1. from pyannote.audio import Pipeline
  2. pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization", use_auth_token="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")
  3. # send pipeline to GPU (when available)
  4. import torch
  5. pipeline.to(torch.device("cuda"))
  6. # apply pretrained pipeline
  7. diarization = pipeline("1002.wav")
  8. print(diarization)
  9. # print the result
  10. for turn, _, speaker in diarization.itertracks(yield_label=True):
  11.     print(f"start={turn.start:.1f}s stop={turn.end:.1f}s speaker_{speaker}")
  12. # start=0.2s stop=1.5s speaker_0
  13. # start=1.8s stop=3.9s speaker_1
  14. # start=4.2s stop=5.7s speaker_0
  15. # ...
复制代码

2.3 funAS整合pyannote.audio

1.1编写算法

  1. from pyannote.core import Segment, Annotation, Timeline
  2. def get_text_with_timestamp(transcribe_res):
  3.     timestamp_texts = []
  4.     for item in transcribe_res['segments']:
  5.         start = item['start']
  6.         end = item['end']
  7.         text = item['text']
  8.         timestamp_texts.append((Segment(start, end), text))
  9.         
  10.     print(timestamp_texts)
  11.     return timestamp_texts
  12. def get_text_with_timestampFun(transcribe_res):
  13.     print(transcribe_res['sentences'])
  14.     timestamp_texts = []
  15.     for item in transcribe_res['sentences']:
  16.         start = item['start']/1000.0
  17.         end = item['end']/1000.0
  18.         text = item['text']
  19.         timestamp_texts.append((Segment(start, end), text))
  20.     return timestamp_texts
  21. def add_speaker_info_to_text(timestamp_texts, ann):
  22.     spk_text = []
  23.     for seg, text in timestamp_texts:
  24.         #这行代码的作用是在给定的时间段 seg 中根据说话人分离结果 ann 获取出现次数最多的说话人。
  25.         spk = ann.crop(seg).argmax()
  26.         spk_text.append((seg, spk, text))
  27.     return spk_text
  28. def merge_cache(text_cache):
  29.     sentence = ''.join([item[-1] for item in text_cache])
  30.     spk = text_cache[0][1]
  31.     start = text_cache[0][0].start
  32.     end = text_cache[-1][0].end
  33.     return Segment(start, end), spk, sentence
  34. PUNC_SENT_END = ['.', '?', '!', '。', '?', '!']
  35. def merge_sentence(spk_text):
  36.     merged_spk_text = []
  37.     pre_spk = None
  38.     text_cache = []
  39.     for seg, spk, text in spk_text:
  40.         if spk != pre_spk and pre_spk is not None and len(text_cache) > 0:
  41.             merged_spk_text.append(merge_cache(text_cache))
  42.             text_cache = [(seg, spk, text)]
  43.             pre_spk = spk
  44.         elif text[-1] in PUNC_SENT_END:
  45.             text_cache.append((seg, spk, text))
  46.             merged_spk_text.append(merge_cache(text_cache))
  47.             text_cache = []
  48.             pre_spk = spk
  49.         else:
  50.             text_cache.append((seg, spk, text))
  51.             pre_spk = spk
  52.     if len(text_cache) > 0:
  53.         merged_spk_text.append(merge_cache(text_cache))
  54.     return merged_spk_text
  55. def diarize_text(transcribe_res, diarization_result):
  56.     timestamp_texts = get_text_with_timestampFun(transcribe_res)
  57.     spk_text = add_speaker_info_to_text(timestamp_texts, diarization_result)
  58.     res_processed = merge_sentence(spk_text)
  59.     return res_processed
  60. def write_to_txt(spk_sent, file):
  61.     with open(file, 'w') as fp:
  62.         for seg, spk, sentence in spk_sent:
  63.             line = f'{seg.start:.2f} {seg.end:.2f} {spk} {sentence}\n'
  64.             fp.write(line)
复制代码
1.2调用

  1. import os
  2. import whisper
  3. from pyannote.audio import Pipeline
  4. from pyannote_funasr.utils import diarize_text
  5. import concurrent.futures
  6. from modelscope.pipelines import pipeline
  7. from modelscope.utils.constant import Tasks
  8. # 输出位置
  9. output_dir = '/root/autodl-tmp/pyannote-whisper'
  10. from modelscope.pipelines import pipeline
  11. from modelscope.utils.constant import Tasks
  12. # 语音转文字的模型
  13. inference_pipeline = pipeline(
  14.     task=Tasks.auto_speech_recognition,
  15.     model='damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch',
  16.     model_revision="v1.2.4")
  17. # rec_result = inference_pipeline(audio_in='1002.wav')
  18. # with open('result.txt', 'w', encoding='utf-8') as f:
  19. #     print(rec_result, file=f)
  20. # # print(rec_result)
  21. def process_audio(file_path):
  22.     print("----------1")
  23.     asr_result = inference_pipeline(audio_in=file_path)  
  24.     print("-----------2.2")
  25.     # 语者分离pipeline
  26.     pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization", use_auth_token="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")
  27.     # 使用显卡加速
  28.     import torch
  29.     pipeline.to(torch.device("cuda"))
  30.     #num_speakers 几个说话者,可以不带
  31.     diarization_result = pipeline(file_path, num_speakers=2)
  32.     # 转文字结果
  33.     print(diarization_result)
  34.     # 进行语着分离
  35.     final_result = diarize_text(asr_result, diarization_result)
  36.     print("-----------5")
  37.     # 输出结果
  38.     output_file = os.path.join(output_dir, os.path.basename(file_path)[:-4] + '.txt')
  39.     with open(output_file, 'w') as f:
  40.         for seg, spk, sent in final_result:
  41.             line = f'{seg.start:.2f} {seg.end:.2f} {spk} {sent}\n'
  42.             f.write(line)
  43.             print(line)
  44. # 判断输出文件夹是否存在
  45. if not os.path.exists(output_dir):
  46.     os.makedirs(output_dir)
  47. wave_dir = '/root/autodl-tmp/pyannote-whisper'
  48. # 获取当前目录下所有wav文件名
  49. wav_files = [os.path.join(wave_dir, file) for file in os.listdir(wave_dir) if file.endswith('.wav')]
  50. # 处理每个wav文件
  51. with concurrent.futures.ThreadPoolExecutor() as executor:
  52.     executor.map(process_audio, wav_files)
  53. print('处理完成!')
复制代码

3.微调

微调.py
  1. import os
  2. from modelscope.metainfo import Trainers
  3. from modelscope.trainers import build_trainer
  4. from modelscope.msdatasets.audio.asr_dataset import ASRDataset
  5. def modelscope_finetune(params):
  6.     if not os.path.exists(params.output_dir):
  7.         os.makedirs(params.output_dir, exist_ok=True)
  8.     # dataset split ["train", "validation"]
  9.     ds_dict = ASRDataset.load(params.data_path, namespace='speech_asr')
  10.     kwargs = dict(
  11.         model=params.model,
  12.         data_dir=ds_dict,
  13.         dataset_type=params.dataset_type,
  14.         work_dir=params.output_dir,
  15.         batch_bins=params.batch_bins,
  16.         max_epoch=params.max_epoch,
  17.         lr=params.lr)
  18.     trainer = build_trainer(Trainers.speech_asr_trainer, default_args=kwargs)
  19.     trainer.train()
  20. if __name__ == '__main__':
  21.     from funasr.utils.modelscope_param import modelscope_args
  22.     params = modelscope_args(model="damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch")
  23.     params.output_dir = "./checkpoint"                      # 模型保存路径
  24.     params.data_path = "speech_asr_aishell1_trainsets"      # 数据路径,可以为modelscope中已上传数据,也可以是本地数据
  25.     params.dataset_type = "small"                           # 小数据量设置small,若数据量大于1000小时,请使用large
  26.     params.batch_bins = 2000                                # batch size,如果dataset_type="small",batch_bins单位为fbank特征帧数,如果dataset_type="large",batch_bins单位为毫秒,
  27.     params.max_epoch = 50                                   # 最大训练轮数
  28.     params.lr = 0.00005                                     # 设置学习率
  29.    
  30.     modelscope_finetune(params)
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

尚未崩坏

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表