음성 복제, 나만의 음성 맞춤화, 클라우드 교육 + 추론 녹음을 위해 최신 버전의 Bert-VITS2 사용

설명하다

  • 이 훈련 서버는 Google Colab T4 GPU를 사용합니다.
  • Bert-VITS2 라이브러리는 https://github.com/fishaudio/Bert-VITS2입니다. 더 자주 업데이트됩니다. 2023.10.12 커밋 버전을 사용하세요.여기에 이미지 설명을 삽입하세요.
  • 주요 참조: 스테이션 B의 많은 거물들의 동영상, CSDN: https://blog.csdn.net/qq_51506262/article/details/133359555,
    코드 클라우드: https :/ /gitee.com/Sake809/Bert-VITS2-Integration-package
  • 배포 과정에서 많은 문제가 발생하여 원본 Bert-VITS2의 개별 코드도 조정되었으며 조정된 코드는 클라우드에 게시되었습니다: https://gitee.com/ajianoscgit/bert-vits2.git
  • 본 프로젝트는 실행 가능한 것으로 확인되었으며, Bert-VITS2는 지속적으로 업데이트됨에 따라 현재 안정적으로 실행되는 코드에 향후 문제가 발생할 수 있습니다.

환경 준비

코드 다운로드, 모델 다운로드 등의 단계가 포함됩니다.

프로젝트 다운로드

%cd /content/drive/MyDrive
# 这里是下载原仓库代码
#!git clone https://github.com/fishaudio/Bert-VITS2.git
# 这是下载码云调整后的代码
!git clone https://gitee.com/ajianoscgit/bert-vits2.git

모델 다운로드

여기서는 중국어 음성 모델만 다운로드되며, https://huggingface.co/hfl/chinese-roberta-wwm-ext-large/tree/main에서 다운로드하실 수 있습니다. /bert /chinese-roberta-wwm-ext-large 디렉토리에 누락된 파일을 다운로드하고 완료합니다.

%cd /content/drive/MyDrive/Bert-VITS2/bert/chinese-roberta-wwm-ext-large
!wget https://huggingface.co/hfl/chinese-roberta-wwm-ext-large/resolve/main/flax_model.msgpack
!wget https://huggingface.co/hfl/chinese-roberta-wwm-ext-large/resolve/main/pytorch_model.bin
!wget https://huggingface.co/hfl/chinese-roberta-wwm-ext-large/resolve/main/tf_model.h5

하단 템플릿 파일 다운로드:

하단 템플릿 파일은 B 스테이션 상사가 잘라낸 하단 템플릿을 사용하므로 효과가 더 좋습니다. https://www.bilibili.com /video/ BV1hp4y1K78E

cloab에서는 모델 파일을 직접 다운로드할 수 없기 때문에 사이트 다운로드가 완료된 후 Google Cloud Disk에 업로드하고, log/base/ 디렉터리에 넣어야 합니다.

# 这是原版底模,使用1.1版b站大佬的底模替代!
%cd /content/drive/MyDrive/Bert-VITS2

#!wget -P logs/base/ https://huggingface.co/Erythrocyte/bert-vits2_base_model/resolve/main/DUR_0.pth
#!wget -P logs/base/ https://huggingface.co/Erythrocyte/bert-vits2_base_model/resolve/main/D_0.pth
#!wget -P logs/base/ https://huggingface.co/Erythrocyte/bert-vits2_base_model/resolve/main/G_0.pth

데이터 전처리 스크립트 작성

특정 음색의 모델을 학습할 때는 먼저 준비된 드라이 오디오 파일을 분할하고 나중에 사용할 수 있도록 분할된 파일의 텍스트를 추출해야 합니다.

이러한 파일을 로컬에서 준비하거나 서버에서 만들 수 있습니다. 서버에서 만들려면 다음 스크립트를 사용하세요.

다음 스크립트는 이 기능을 구현하는 관련 스크립트입니다(스크립트는 런타임 매개변수 및 오디오를 읽을 때 중국어 번체 문자를 중국어 간체로 변환하기 위해 csdn 보스의 코드에 따라 조정됩니다). 트랜스코딩 텍스트): < /span>

import os
from pathlib import Path
import librosa
from scipy.io import wavfile
import numpy as np
import whisper
import argparse
from langconv import *

def split_long_audio(model, filepath, save_dir="short_dir", out_sr=44100)->str:
    '''将长音源wav文件分割为短音源文件,返回短音源文件存储路径path'''
    # 短音频文件存储路径
    save_dir=os.path.join(os.path.dirname(filepath),save_dir)
    if not os.path.exists(save_dir):
      os.makedirs(save_dir)

    #分割文件
    print(f'分割文件{filepath}...')
    result = model.transcribe(filepath, word_timestamps=True, task="transcribe", beam_size=5, best_of=5)
    segments = result['segments']
    wav, sr = librosa.load(filepath, sr=None, offset=0, duration=None, mono=True)
    wav, _ = librosa.effects.trim(wav, top_db=20)
    peak = np.abs(wav).max()
    if peak > 1.0:
      wav = 0.98 * wav / peak
    wav2 = librosa.resample(wav, orig_sr=sr, target_sr=out_sr)
    wav2 /= max(wav2.max(), -wav2.min())
    for i, seg in enumerate(segments):
        start_time = seg['start']
        end_time = seg['end']
        wav_seg = wav2[int(start_time * out_sr):int(end_time * out_sr)]
        wav_seg_name = f"{i}.wav" # 修改名字
        i+=1
        out_fpath = os.path.join(save_dir,wav_seg_name)
        wavfile.write(out_fpath, rate=out_sr, data=(wav_seg * np.iinfo(np.int16).max).astype(np.int16))
    return save_dir


def transcribe_one(audio_path): # 使用whisper语音识别
    # load audio and pad/trim it to fit 30 seconds
    audio = whisper.load_audio(audio_path)
    audio = whisper.pad_or_trim(audio)
    # make log-Mel spectrogram and move to the same device as the model
    mel = whisper.log_mel_spectrogram(audio).to(model.device)
    # detect the spoken language
    _, probs = model.detect_language(mel)
    lang = max(probs, key=probs.get)
    # decode the audio
    options = whisper.DecodingOptions(beam_size=5)
    result = whisper.decode(model, mel, options)
    #繁体转简体
    txt = result.text
    txt = Converter('zh-hans').convert(txt)

    fileName = os.path.basename(audio_path)
    print(f'{fileName}:{lang}——>{txt}')
    return txt

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('inputFilePath', type=str,help="干声源音频wav文件的全路径")
    parser.add_argument('listFileSavePath', type=str,help=".list文件存储全路径")
    parser.add_argument('--shortFilesPath', type=str, help="已经分割好了的短音频的存储目录全路径,用于当分割好之后再次运行时配置")
    opt = parser.parse_args()
    print(f'参数:{opt}')

    model = whisper.load_model("medium")
    #将长音源分割成短音源文件
    if not opt.shortFilesPath:
      save_dir = split_long_audio(model, opt.inputFilePath)
    else:
      save_dir = opt.shortFilesPath

    #为每个短音频文件提取文字内容,生成.lab文件和filelists目录下的.list文件
    if not os.path.exists(opt.listFileSavePath):
      file = open(opt.listFileSavePath, "w")
      file.close()
    print('提取文字内容...')
    files=os.listdir(save_dir)
    spk = os.path.basename(os.path.dirname(opt.inputFilePath))
    for file in files:
      if not file.endswith('.wav'):
        continue
      text = transcribe_one(os.path.join(save_dir,file))
      with open(os.path.join(save_dir,f"{file}.lab"),'w') as f:
          f.write(text)
      with open(opt.listFileSavePath,'a', encoding="utf-8") as wf:
          wf.write(f"{os.path.join(save_dir,file)}|{spk}|ZH|{text}\n")


    print('音频预处理完成!')

종속성 설치

#检查CUDA版本
import torch
print(torch.version.cuda)
print(torch.cuda.is_available())
#安装依赖
%cd /content/drive/MyDrive/Bert-VITS2

!pip install wavfile
!pip install git+https://github.com/openai/whisper.git
!pip install -r requirements.txt
!pip install zhconv==1.4.3
!pip install zhtools==0.3.1

기차

오디오 전처리

  • 오디오의 경우 소리를 직접 녹음해야 하며, 길이는 1분 이상 10분 미만일 수 있습니다.
  • Ultimate Vocal Remover 도구를 사용하여 오디오에서 배경 소음을 제거하여 순수하고 건조한 사운드를 만듭니다. Ultimate Vocal Remover 도구를 사용하려면 https://github.com/Anjok07/ultimatevocalremovergui를 참조하세요. 작성자가 GUI를 캡슐화했으므로 다운로드하여 설치하기만 하면 됩니다.
  • 추출된 마른 소리는 프로젝트의 데이터 디렉터리에 업로드됩니다. zhangsan과 같은 데이터 아래에 새 이름 디렉터리를 생성해야 합니다. 파일 구조는 다음과 같습니다.
    Bert-VITS2 ——————ganshen. 웨이브 ——————zhangsan
    ————데이터

  • 다음 스크립트를 실행하여 오디오를 전처리합니다.
%cd /content/drive/MyDrive/Bert-VITS2
!python 音频预处理脚本.py /content/drive/MyDrive/Bert-VITS2/data/zhangsan/ganshen.wav /content/drive/MyDrive/Bert-VITS2/filelists/zhangsan.list --shortFilesPath '/content/drive/MyDrive/Bert-VITS2/data/zhangsan/short_dir'

참고: 오디오 전처리가 완료된 후 datalists 디렉터리에서 해당 목록 파일을 열어 처리 결과를 확인하고 너무 이상하고 명백한 오류가 있는 줄을 직접 삭제하세요!

오디오 리샘플링

리샘플링된 오디오는 데이터 세트 아래에 생성됩니다. 소스 오디오가 보조 교육을 위해 수정된 경우 원본 데이터 세트 아래의 파일을 삭제해야 합니다.

%cd /content/drive/MyDrive/Bert-VITS2
!python resample.py --in_dir /content/drive/MyDrive/Bert-VITS2/data/zhangsan/short_dir

.list 파일 전처리 중

전처리가 완료되면 파일 목록 아래에 .cleaned, train.list 및 val.list 파일이 생성됩니다!

%cd /content/drive/MyDrive/Bert-VITS2
!python preprocess_text.py --transcription-path /content/drive/MyDrive/Bert-VITS2/filelists/zhangsan.list

pt 파일 생성

비디오 파일에 해당하는 .bert.pt 파일이 data/username/short_dir 디렉터리에 생성됩니다.

%cd /content/drive/MyDrive/Bert-VITS2
!python bert_gen.py --num_processes 4

훈련 시작

참고 1: 훈련을 시작하기 전에 먼저 데이터 디렉터리의 훈련 폴더 이름을 configs/config.json 파일의 spk2id에 추가하고 ID를 추가해야 합니다! ! ! 이 경우 "biaibei"에 "zhangsan"이 추가됩니다: 247, after!

참고 2: train_ms.py 및 data_utils.py는 다중 스레드 병렬 교육을 지원하도록 광범위하게 수정되었습니다. 하지만 T4 서버는 메모리가 12G밖에 없어 소모되기 때문에 멀티스레딩 효과는 없습니다.

  • 여기에서 총 훈련 단계 수는 config.json의 epoch에 의해 제어되며 일반적으로 약 500으로 설정됩니다.
  • 학습을 통해 생성된 모델은 로그 디렉터리에 있으며 DUR_x, D_x, G_x 뒤의 숫자는 모두 1:1 대응이며 프로그램이 중단된 후 다음 학습은 이전 단계로 계속됩니다.
%cd /content/drive/MyDrive/Bert-VITS2

# -m:base,表示的logs/base/底模文件目录的base
!python train_ms.py -m base -c configs/config.json --cont

추리

  • 브라우저 환경이 있는 경우 webui.py를 직접 실행하여 인터페이스 동작 추론을 활성화합니다.
  • 시각적 인터페이스 환경이 없는 경우 명령줄 추론을 위해 다음 스크립트를 사용합니다.
%cd /content/drive/MyDrive/Bert-VITS2
# -m:就是推理之后的模型路径
!python 命令行推理.py -m ./logs/base/G_8000.pth --text='你好啊你是谁呀' --speaker='zhangsan'

생성된 오디오 파일은 자체적으로 다운로드하여 재생할 수 있습니다.

Guess you like

Origin blog.csdn.net/AJian759447583/article/details/133807519