2023_マルチバンド生成と逆短時間フーリエ変換を備えた軽量で忠実度の高いエンドツーエンドのテキスト読み上げ
目次
【PS1】エラー: pyproject.toml ベースのプロジェクトのインストールに必要な pyopenjtalk のホイールをビルドできませんでした
【PS2】AttributeError: 'HParams' オブジェクトには属性 'seed' がありません
【PS4】データが対応するspec.ptファイルを生成しない
【PS5】 TypeError: __init__() は位置引数を 1 つとりますが、2 つが与えられました
1. 論文の詳細説明
1.1. はじめに
音声合成の前の 2 つの段階 (音響モデルとボコーダー) について説明しますが、VITS は高品質のエンドツーエンド モデルであるため、この論文で提案されるモデルは VITS の軽量エンドツーエンド モデルに基づいています。この論文では主に、モデル内でいくつかの復号化手法を使用しており、その一部、つまり潜在的な音響特徴を波形に変換し、周波数領域からの変換を効率的に完了するために、復号器の一部を単純な短時間逆フーリエ変換 (iSTFT) に置き換えています。推論を高速化する場合は、多段処理を使用します。提案手法では、各 iSTFTNet, サブセグメントが信号を送信します。推論中は、オリジナルの VITS よりも 4.1 倍高速です。
1.2.VITSアルゴリズム
1.2.1. VITS の原理を簡単に紹介しますが、ここでは多くは紹介しませんので、詳細については、[ VITS 論文の概要とプロジェクトの再現]を参照してください。
1.2.2. 各モデルの推論速度
ここでは、客観的な基準として、時間トークンを合成音声の長さで割るRTF 計算が使用されます。
1.3.提案手法
1.3.1. 出力層で、元のビットの HiFi-GAN をサンプル逆短時間フーリエ変換に置き換えます。
1.3.2. マルチバンド iSTFT VITS 自動エンコード
下の図はモデルの全体的な枠組みを示しています。
1.3.3. マルチストリーム iSTFT VITS (マルチストリーム iSTFT VITS) は
MB-iSTFT-VITS とは異なり、MS-iSTFT-VITS 波形は完全にトレーニング可能であり、固定サブバンド信号の影響を受けません。
1.4.実験
データセット: LJ 音声データセット
5 つの vits ベースのモデルを比較しました。
- VITS : 正式な VITS1。そのハイパーパラメータはオリジナルの VITS と同じです。
- Nix-TTS : Nix-TTS 2 の事前トレーニング済みモデル。使用されるモデルは、最適化された ONNX バージョンです [27]。実験で使用されたデータセットは、Nix-TTS で使用されたものとまったく同じであることに注意してください。
- iSTFT-VITS : VITSデコーダ部にiSTFTNetを組み込んだモデル。iSTFTNet のアーキテクチャは V1-C8C8I であり、[14] で説明されている最もバランスのとれたモデルです。このアーキテクチャには 2 つのアップサンプリング率 [8, 8] が含まれており、高速フーリエ変換 (FFT) のサイズ、ジャンプ長、ウィンドウ長はそれぞれ 16、4、16 に設定されています。
- MB-iSTFT-VITSのセクション 3.2 で導入された提案されたモデル。サブバンド数 N は 4 に設定されます。2 つの残差ブロックのアップサンプリング比は [4,4] で、各サブバンド信号の分解された解像度と一致します。擬似 QMF 分析フィルターは、各サブバンドの解像度に一致するように信号を分解します。iSTFT部のFFTサイズ、遷移長、窓長は、擬似QMF分析フィルタで分解された各サブバンド信号の分解能と同じである。
- MS-iSTFT-VITS : セクション 3.3 で紹介された別の提案モデル。[10] によれば、畳み込みベースのトレーニング可能な合成フィルターのカーネル サイズはバイアスなしで 63 に設定されます。トレーニング可能な合成フィルターのカーネル サイズは、バイアスなしで 63 に設定されます。その他の条件はMB-iSTFT-VITSと同様です。
下の図は比較結果を示しています
1.5.結論
本稿では、デバイス上で高速な音声合成を可能にするエンドツーエンドのTTSシステムを提案する。提案された方法は、VITS と呼ばれる成功したエンドツーエンド モデルに基づいて構築されていますが、iSTFT によるデコーダ計算の冗長性の削減やマルチバンド並列戦略の採用など、推論を高速化するためのいくつかの手法が採用されています。は完全にエンドツーエンドの方法で最適化されており、従来の 2 段階の方法と比較して、提案されたモデルはその強力な最適化プロセスを十分に楽しむことができます。実験結果は、この方法によって生成された音声が VITS によって合成された音声と同じくらい自然であると同時に、波形をより高速に生成することを示しています。今後の研究には、提案された方法をマルチスピーカーモデルに拡張することが含まれます。
2. プロジェクトの実施
2.1.データの準備
用意する音声データは22050Hz、シングルチャンネル(Mono)、PCM-16bitである必要があります。
個人
dataset/001.wav|您好
dataset/001.wav|안녕하세요
dataset/001.wav|こんにちは。
複数人
dataset/001.wav|0|こんにちは。
真ん中の数字は0から始まるキャラクターIDです。
# Cython-version Monotonoic Alignment Search
cd monotonic_align
mkdir monotonic_align
python setup.py build_ext --inplace
この論文ではいくつかのトレーニング構造を提供しています。論文では MB-iSTFT-VITS が最も効果的であるため、この論文ではこのモデルを使用しています。
training_files` と `validation_files` のパスを変更します。
独自のデータセットの新しい config.json ファイルを作成します
改訂:
"training_files":"./filelists/history_train_filelist.txt.cleaned",
"validation_files":"./filelists/history_train_filelist.txt.cleaned",
"text_cleaners":["cjke_cleaners2"], #多语言自定义函数
# "text_cleaners":["korean_cleaners"], #训练语言
2.2.データの前処理
# Single speaker
# python preprocess.py --text_index 1 --filelists path/to/filelist_train.txt path/to/filelist_val.txt --text_cleaners 'japanese_cleaners'
#本文实例
# 方法一:声学模型(暂时未运行)
python preprocess.py --text_index 1 --filelists ./filelists/history_train_filelist.txt ./filelists/history_val_filelist.txt --text_cleaners 'korean_cleaners'
# 方法二:G2p模型
python preprocess.py --text_index 1 --filelists ./filelists/history_train_filelist.txt ./filelists/history_val_filelist.txt --text_cleaners 'cjke_cleaners2'
# Mutiple speakers
python preprocess.py --text_index 2 --filelists path/to/filelist_train.txt path/to/filelist_val.txt --text_cleaners 'japanese_cleaners'
実行後に生成
2.3. テキスト処理
中国、英国、韓国、日本ではテキストの処理方法に若干の違いがあります。
テキスト処理、変換方法、テキストの正規化、シンボル処理を含む
2.4.トレーニング
# 单人
#python train_latest.py -c <config> -m <folder>
python train_latest.py -c configs/myvoice.json -m myvoice_model(文件夹名称,随便起)
# 多人
#python train_latest_ms.py -c <config> -m <folder>
トレーニング後、ログはログ フォルダーに保存されます。
2.5. 推論
import warnings
warnings.filterwarnings(action='ignore')
import os
import time
import torch
import utils
import argparse
import commons
import utils
from models import SynthesizerTrn
from text.symbols import symbols
from text import cleaned_text_to_sequence
#日语from g2p import pyopenjtalk_g2p_prosody
#韩语
from g2pk2 import G2p
import soundcard as sc
import soundfile as sf
def get_text(text, hps):
text_norm = cleaned_text_to_sequence(text)
if hps.data.add_blank:
text_norm = commons.intersperse(text_norm, 0)
text_norm = torch.LongTensor(text_norm)
return text_norm
def inference(args):
config_path = args.config
G_model_path = args.model_path
# check device
if torch.cuda.is_available() is True:
print("Enter the device number to use.")
key = input("GPU:0, CPU:1 ===> ")
if key == "0":
device="cuda:0"
elif key=="1":
device="cpu"
print(f"Device : {device}")
else:
print(f"CUDA is not available. Device : cpu")
device = "cpu"
# load config.json
hps = utils.get_hparams_from_file(config_path)
# load checkpoint
net_g = SynthesizerTrn(
len(symbols),
hps.data.filter_length // 2 + 1,
hps.train.segment_size // hps.data.hop_length,
**hps.model).cuda()
_ = net_g.eval()
_ = utils.load_checkpoint(G_model_path, net_g, None)
# play audio by system default
speaker = sc.get_speaker(sc.default_speaker().name)
# parameter settings
noise_scale = torch.tensor(0.66) # adjust z_p noise
noise_scale_w = torch.tensor(0.8) # adjust SDP noise
length_scale = torch.tensor(1.0) # adjust sound length scale (talk speed)
if args.is_save is True:
n_save = 0
save_dir = os.path.join("./infer_logs/")
os.makedirs(save_dir, exist_ok=True)
### Dummy Input ###
with torch.inference_mode():
#日语stn_phn = pyopenjtalk_g2p_prosody("速度計測のためのダミーインプットです。")
stn_phn = G2p("소프트웨어 교육의 중요성이 날로 더해가는데 학생들은 소프트웨어 관련 교육을 쉽게 지루해해요")
stn_tst = get_text(stn_phn, hps)
# generate audio
x_tst = stn_tst.cuda().unsqueeze(0)
x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).cuda()
audio = net_g.infer(x_tst,
x_tst_lengths,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale)[0][0,0].data.cpu().float().numpy()
while True:
# get text
text = input("Enter text. ==> ")
if text=="":
print("Empty input is detected... Exit...")
break
# measure the execution time
torch.cuda.synchronize()
start = time.time()
# required_grad is False
with torch.inference_mode():
#日语stn_phn = pyopenjtalk_g2p_prosody(text)
#韩语
stn_phn = G2p(text)
stn_tst = get_text(stn_phn, hps)
# generate audio
x_tst = stn_tst.cuda().unsqueeze(0)
x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).cuda()
audio = net_g.infer(x_tst,
x_tst_lengths,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale)[0][0,0].data.cpu().float().numpy()
# measure the execution time
torch.cuda.synchronize()
elapsed_time = time.time() - start
print(f"Gen Time : 0.0621")
# play audio
speaker.play(audio, hps.data.sampling_rate)
# save audio
if args.is_save is True:
n_save += 1
data = audio
try:
save_path = os.path.join(save_dir, str(n_save).zfill(3)+f"_{text}.wav")
sf.write(
file=save_path,
data=data,
samplerate=hps.data.sampling_rate,
format="WAV")
except:
save_path = os.path.join(save_dir, str(n_save).zfill(3)+f"_{text[:10]}〜.wav")
sf.write(
file=save_path,
data=data,
samplerate=hps.data.sampling_rate,
format="WAV")
print(f"Audio is saved at : {save_path}")
return 0
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--config',
type=str,
required=True,
#default="./logs/ITA_CORPUS/config.json" ,
help='Path to configuration file')
parser.add_argument('--model_path',
type=str,
required=True,
#default="./logs/ITA_CORPUS/G_1200.pth",
help='Path to checkpoint')
parser.add_argument('--is_save',
type=str,
default=True,
help='Whether to save output or not')
args = parser.parse_args()
inference(args)
何か問題が発生した場合は、[PS5] を確認してください。
【追記】
【PS1】エラー: pyproject.toml ベースのプロジェクトのインストールに必要な pyopenjtalk のホイールをビルドできませんでした
pip install -rrequirements.txt のインストール時に次のエラーが発生しました
参考1
試す
pip install pycocotools -i https://pypi.python.org/simple
まだエラー
【PS2】AttributeError: 'HParams' オブジェクトには属性 'seed' がありません
config 内の構成ファイルにシードがありません。
設定ファイルを再変更する
【PS3】EOFError:入力不足
著者のトレーニング用のデフォルトの GPU 数は 5 です
num_worker を 0 に変更します
その後再び現れた
/workspace/tts/MB-iSTFT-VITS-multilingual/text/__init__.py の 35 行目を次のように変更します。
sequence = [_symbol_to_id[symbol] for symbol in cleaned_text if symbol in _symbol_to_id.keys()]
【PS4】データが対応するspec.ptファイルを生成しない
【PS5】 TypeError: __init__() は位置引数を 1 つとりますが、2 つが与えられました
言語ごとに処理ライブラリが異なります。
【PS6】トレースバック (最新の呼び出しは最後):
ファイル "sc_test.py"、行 2、<module>
インポート サウンドカード
ファイル "/opt/miniconda3/envs/vits/lib/python3.8/site-packages/soundcard/ __init__.py"、4 行目、
soundcard.pulseaudio import の <module> 内 *
ファイル「/opt/miniconda3/envs/vits/lib/python3.8/site-packages/soundcard/pulseaudio.py」、265 行目、 <module>
_pulse = _PulseAudio()
ファイル「/opt/miniconda3/envs/vits/lib/python3.8/site-packages/soundcard/pulseaudio.py」、__init__ の 76 行目、
self._pa_context_get_state(self.context) をアサートします。 ==_pa.PA_CONTEXT_READY
アサーションエラー
参考
systemd サービスを通じて実行すると、「サウンドカードのインポート」でエラーがスローされる · 問題 #133 · bastibe/SoundCard (github.com)
拡大する
多言語処理方法の紹介
韓国語
- 韓国からIPAへ
Scarletcho/KoG2P: Python での韓国語の書記素から音への変換 (github.com)
方法 1: 韓国語から音素へ (G2p)
固定データ形式
/workspace/tts/MB-iSTFT-VITS-multilingual/text/__init__.py および Cleaners.py のテキストの処理を変更します。
構成ファイル/workspace/tts/MB-iSTFT-VITS-multilingual/configs/own data set name.json を変更します。
from text.korean import latin_to_hangul, number_to_hangul, divide_hangul, korean_to_lazy_ipa, korean_to_ipa
from g2pk2 import G2p
def cjke_cleaners2(text):
text = re.sub(r'(.*?)',
lambda x: korean_to_ipa(x.group(1))+' ', text)
text = re.sub(r'\s+$', '', text)
text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
for texts in text:
cleaned_text = korean_to_ipa(text[4:-4])
if re.match(r'[^\.,!\?\-…~]', text[-1]):
text += '.'
return text
方法 2: 音響モデル
テキスト処理用
韓国語では、著者が提供した方法に加えて、
まず、韓国語と句読点の処理メソッドを記述した korean.py を追加します。具体的なコードは以下のとおりです。
import re
from jamo import h2j, j2hcj
import ko_pron
# This is a list of Korean classifiers preceded by pure Korean numerals.
_korean_classifiers = '군데 권 개 그루 닢 대 두 마리 모 모금 뭇 발 발짝 방 번 벌 보루 살 수 술 시 쌈 움큼 정 짝 채 척 첩 축 켤레 톨 통'
# List of (hangul, hangul divided) pairs:
_hangul_divided = [(re.compile('%s' % x[0]), x[1]) for x in [
('ㄳ', 'ㄱㅅ'),
('ㄵ', 'ㄴㅈ'),
('ㄶ', 'ㄴㅎ'),
('ㄺ', 'ㄹㄱ'),
('ㄻ', 'ㄹㅁ'),
('ㄼ', 'ㄹㅂ'),
('ㄽ', 'ㄹㅅ'),
('ㄾ', 'ㄹㅌ'),
('ㄿ', 'ㄹㅍ'),
('ㅀ', 'ㄹㅎ'),
('ㅄ', 'ㅂㅅ'),
('ㅘ', 'ㅗㅏ'),
('ㅙ', 'ㅗㅐ'),
('ㅚ', 'ㅗㅣ'),
('ㅝ', 'ㅜㅓ'),
('ㅞ', 'ㅜㅔ'),
('ㅟ', 'ㅜㅣ'),
('ㅢ', 'ㅡㅣ'),
('ㅑ', 'ㅣㅏ'),
('ㅒ', 'ㅣㅐ'),
('ㅕ', 'ㅣㅓ'),
('ㅖ', 'ㅣㅔ'),
('ㅛ', 'ㅣㅗ'),
('ㅠ', 'ㅣㅜ')
]]
# List of (Latin alphabet, hangul) pairs:
_latin_to_hangul = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
('a', '에이'),
('b', '비'),
('c', '시'),
('d', '디'),
('e', '이'),
('f', '에프'),
('g', '지'),
('h', '에이치'),
('i', '아이'),
('j', '제이'),
('k', '케이'),
('l', '엘'),
('m', '엠'),
('n', '엔'),
('o', '오'),
('p', '피'),
('q', '큐'),
('r', '아르'),
('s', '에스'),
('t', '티'),
('u', '유'),
('v', '브이'),
('w', '더블유'),
('x', '엑스'),
('y', '와이'),
('z', '제트')
]]
# List of (ipa, lazy ipa) pairs:
_ipa_to_lazy_ipa = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
('t͡ɕ','ʧ'),
('d͡ʑ','ʥ'),
('ɲ','n^'),
('ɕ','ʃ'),
('ʷ','w'),
('ɭ','l`'),
('ʎ','ɾ'),
('ɣ','ŋ'),
('ɰ','ɯ'),
('ʝ','j'),
('ʌ','ə'),
('ɡ','g'),
('\u031a','#'),
('\u0348','='),
('\u031e',''),
('\u0320',''),
('\u0339','')
]]
def latin_to_hangul(text):
for regex, replacement in _latin_to_hangul:
text = re.sub(regex, replacement, text)
return text
def divide_hangul(text):
text = j2hcj(h2j(text))
for regex, replacement in _hangul_divided:
text = re.sub(regex, replacement, text)
return text
def hangul_number(num, sino=True):
'''Reference https://github.com/Kyubyong/g2pK'''
num = re.sub(',', '', num)
if num == '0':
return '영'
if not sino and num == '20':
return '스무'
digits = '123456789'
names = '일이삼사오육칠팔구'
digit2name = {d: n for d, n in zip(digits, names)}
modifiers = '한 두 세 네 다섯 여섯 일곱 여덟 아홉'
decimals = '열 스물 서른 마흔 쉰 예순 일흔 여든 아흔'
digit2mod = {d: mod for d, mod in zip(digits, modifiers.split())}
digit2dec = {d: dec for d, dec in zip(digits, decimals.split())}
spelledout = []
for i, digit in enumerate(num):
i = len(num) - i - 1
if sino:
if i == 0:
name = digit2name.get(digit, '')
elif i == 1:
name = digit2name.get(digit, '') + '십'
name = name.replace('일십', '십')
else:
if i == 0:
name = digit2mod.get(digit, '')
elif i == 1:
name = digit2dec.get(digit, '')
if digit == '0':
if i % 4 == 0:
last_three = spelledout[-min(3, len(spelledout)):]
if ''.join(last_three) == '':
spelledout.append('')
continue
else:
spelledout.append('')
continue
if i == 2:
name = digit2name.get(digit, '') + '백'
name = name.replace('일백', '백')
elif i == 3:
name = digit2name.get(digit, '') + '천'
name = name.replace('일천', '천')
elif i == 4:
name = digit2name.get(digit, '') + '만'
name = name.replace('일만', '만')
elif i == 5:
name = digit2name.get(digit, '') + '십'
name = name.replace('일십', '십')
elif i == 6:
name = digit2name.get(digit, '') + '백'
name = name.replace('일백', '백')
elif i == 7:
name = digit2name.get(digit, '') + '천'
name = name.replace('일천', '천')
elif i == 8:
name = digit2name.get(digit, '') + '억'
elif i == 9:
name = digit2name.get(digit, '') + '십'
elif i == 10:
name = digit2name.get(digit, '') + '백'
elif i == 11:
name = digit2name.get(digit, '') + '천'
elif i == 12:
name = digit2name.get(digit, '') + '조'
elif i == 13:
name = digit2name.get(digit, '') + '십'
elif i == 14:
name = digit2name.get(digit, '') + '백'
elif i == 15:
name = digit2name.get(digit, '') + '천'
spelledout.append(name)
return ''.join(elem for elem in spelledout)
def number_to_hangul(text):
'''Reference https://github.com/Kyubyong/g2pK'''
tokens = set(re.findall(r'(\d[\d,]*)([\uac00-\ud71f]+)', text))
for token in tokens:
num, classifier = token
if classifier[:2] in _korean_classifiers or classifier[0] in _korean_classifiers:
spelledout = hangul_number(num, sino=False)
else:
spelledout = hangul_number(num, sino=True)
text = text.replace(f'{num}{classifier}', f'{spelledout}{classifier}')
# digit by digit for remaining digits
digits = '0123456789'
names = '영일이삼사오육칠팔구'
for d, n in zip(digits, names):
text = text.replace(d, n)
return text
def korean_to_lazy_ipa(text):
text = latin_to_hangul(text)
text = number_to_hangul(text)
text=re.sub('[\uac00-\ud7af]+',lambda x:ko_pron.romanise(x.group(0),'ipa').split('] ~ [')[0],text)
for regex, replacement in _ipa_to_lazy_ipa:
text = re.sub(regex, replacement, text)
return text
def korean_to_ipa(text):
text = korean_to_lazy_ipa(text)
return text.replace('ʧ','tʃ').replace('ʥ','dʑ')
次に、/workspace/tts/MB-iSTFT-VITS-multilingual/text/cleaners.py で呼び出します。
from text.korean import latin_to_hangul, number_to_hangul, divide_hangul, korean_to_lazy_ipa, korean_to_ipa
def korean_cleaners(text):
#Pipeline for Korean text
text = latin_to_hangul(text)
text = number_to_hangul(text)
text = divide_hangul(text)
text = re.sub(r'([\u3131-\u3163])$', r'\1.', text)
return text
def korean_cleaners2(text):
#Pipeline for Korean text
text = latin_to_hangul(text)
g2p = G2p()
text = g2p(text)
text = divide_hangul(text)
text = re.sub(r'([\u3131-\u3163])$', r'\1.', text)
return text
VScodeのショートカットキー
Ctrl+F: キーワードを検索
左側の矢印をクリックして置き換えます
Ctrl+Alt+Enter すべて置換