From 797c354b1bc4699c1b7c58807180704945079d68 Mon Sep 17 00:00:00 2001 From: tsukumi Date: Fri, 19 Apr 2024 04:09:21 +0000 Subject: [PATCH 1/9] =?UTF-8?q?Add:=20the=20ability=20to=20specify=20a=20p?= =?UTF-8?q?honeme=20sequence=20representing=20the=20reading=20of=20the=20t?= =?UTF-8?q?ext=20to=20be=20read=20during=20speech=20synthesis=20With=20thi?= =?UTF-8?q?s=20feature,=20it=20is=20possible=20to=20specify=20individual?= =?UTF-8?q?=20readings=20for=20homonyms=20such=20as=20"=E6=98=8E=E6=97=A5?= =?UTF-8?q?=20(ashita/asu)"=20while=20maintaining=20the=20Kanji=20represen?= =?UTF-8?q?tation=20of=20the=20read=20text.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- style_bert_vits2/models/infer.py | 45 +++++- style_bert_vits2/nlp/japanese/g2p.py | 208 +++++++++++++++++++++++++-- style_bert_vits2/tts_model.py | 6 +- 3 files changed, 246 insertions(+), 13 deletions(-) diff --git a/style_bert_vits2/models/infer.py b/style_bert_vits2/models/infer.py index a9bcbf6..da416b8 100644 --- a/style_bert_vits2/models/infer.py +++ b/style_bert_vits2/models/infer.py @@ -102,6 +102,7 @@ def get_text( device: str, assist_text: Optional[str] = None, assist_text_weight: float = 0.7, + given_phone: Optional[list[str]] = None, given_tone: Optional[list[int]] = None, ): use_jp_extra = hps.version.endswith("JP-Extra") @@ -112,10 +113,43 @@ def get_text( use_jp_extra=use_jp_extra, raise_yomi_error=False, ) - if given_tone is not None: - if len(given_tone) != len(phone): + # phone と tone の両方が与えられた場合はそれを使う + if given_phone is not None and given_tone is not None: + # 指定された phone と指定された tone 両方の長さが一致していなければならない + if len(given_phone) != len(given_tone): + raise InvalidPhoneError( + f"Length of given_phone ({len(given_phone)}) != length of given_tone ({len(given_tone)})" + ) + # 与えられた音素数と pyopenjtalk で生成した読みの音素数が一致しない + if len(given_phone) != sum(word2ph): + # 日本語の場合、len(given_phone) と sum(word2ph) が一致するように word2ph を適切に調整する + # 他の言語は word2ph の調整方法が思いつかないのでエラー + if language_str == Languages.JP: + from style_bert_vits2.nlp.japanese.g2p import adjust_word2ph + word2ph = adjust_word2ph(word2ph, phone, given_phone) + # 上記処理により word2ph の合計が given_phone の長さと一致するはず + # それでも一致しない場合、大半は読み上げテキストと given_phone が著しく乖離していて調整し切れなかったことを意味する + if len(given_phone) != sum(word2ph): + raise InvalidPhoneError( + f"Length of given_phone ({len(given_phone)}) != sum of word2ph ({sum(word2ph)})" + ) + else: + raise InvalidPhoneError( + f"Length of given_phone ({len(given_phone)}) != sum of word2ph ({sum(word2ph)})" + ) + phone = given_phone + # 生成あるいは指定された phone と指定された tone 両方の長さが一致していなければならない + if len(phone) != len(given_tone): raise InvalidToneError( - f"Length of given_tone ({len(given_tone)}) != length of phone ({len(phone)})" + f"Length of phone ({len(phone)}) != length of given_tone ({len(given_tone)})" + ) + tone = given_tone + # tone だけが与えられた場合は clean_text() で生成した phone と合わせて使う + elif given_tone is not None: + # 生成した phone と指定された tone 両方の長さが一致していなければならない + if len(phone) != len(given_tone): + raise InvalidToneError( + f"Length of phone ({len(phone)}) != length of given_tone ({len(given_tone)})" ) tone = given_tone phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str) @@ -179,6 +213,7 @@ def infer( skip_end: bool = False, assist_text: Optional[str] = None, assist_text_weight: float = 0.7, + given_phone: Optional[list[str]] = None, given_tone: Optional[list[int]] = None, ): is_jp_extra = hps.version.endswith("JP-Extra") @@ -189,6 +224,7 @@ def infer( device, assist_text=assist_text, assist_text_weight=assist_text_weight, + given_phone=given_phone, given_tone=given_tone, ) if skip_start: @@ -263,5 +299,8 @@ def infer( return audio +class InvalidPhoneError(ValueError): + pass + class InvalidToneError(ValueError): pass diff --git a/style_bert_vits2/nlp/japanese/g2p.py b/style_bert_vits2/nlp/japanese/g2p.py index 1f6b450..8038573 100644 --- a/style_bert_vits2/nlp/japanese/g2p.py +++ b/style_bert_vits2/nlp/japanese/g2p.py @@ -1,4 +1,5 @@ import re +from typing import TypedDict from style_bert_vits2.constants import Languages from style_bert_vits2.logging import logger @@ -23,7 +24,7 @@ def g2p( Args: norm_text (str): 正規化されたテキスト use_jp_extra (bool, optional): False の場合、「ん」の音素を「N」ではなく「n」とする。Defaults to True. - raise_yomi_error (bool, optional): False の場合、読めない文字が消えたような扱いとして処理される。Defaults to False. + raise_yomi_error (bool, optional): False の場合、読めない文字が「ん」として発音される。Defaults to False. Returns: tuple[list[str], list[int], list[int]]: 音素のリスト、アクセントのリスト、word2ph のリスト @@ -38,8 +39,8 @@ def g2p( # punctuation がすべて消えた、音素とアクセントのタプルのリスト(「ん」は「N」) phone_tone_list_wo_punct = __g2phone_tone_wo_punct(norm_text) - # sep_text: 単語単位の単語のリスト、読めない文字があったら raise_yomi_error なら例外、そうでないなら読めない文字が消えて返ってくる - # sep_kata: 単語単位の単語のカタカナ読みのリスト + # sep_text: 単語単位の単語のリスト + # sep_kata: 単語単位の単語のカタカナ読みのリスト、読めない文字は raise_yomi_error=True なら例外、False なら読めない文字を「ン」として返ってくる sep_text, sep_kata = text_to_sep_kata(norm_text, raise_yomi_error=raise_yomi_error) # sep_phonemes: 各単語ごとの音素のリストのリスト @@ -103,7 +104,7 @@ def text_to_sep_kata( Args: norm_text (str): 正規化されたテキスト - raise_yomi_error (bool, optional): False の場合、読めない文字が消えたような扱いとして処理される。Defaults to False. + raise_yomi_error (bool, optional): False の場合、読めない文字が「ん」として発音される。Defaults to False. Returns: tuple[list[str], list[str]]: 分割された単語リストと、その読み(カタカナ or 記号1文字)のリスト @@ -137,12 +138,17 @@ def text_to_sep_kata( # word は正規化されているので、`.`, `,`, `!`, `'`, `-`, `--` のいずれか if not set(word).issubset(set(PUNCTUATIONS)): # 記号繰り返しか判定 # ここは pyopenjtalk が読めない文字等のときに起こる + ## 例外を送出する場合 if raise_yomi_error: raise YomiError(f"Cannot read: {word} in:\n{norm_text}") - logger.warning(f"Ignoring unknown: {word} in:\n{norm_text}") - continue - # yomi は元の記号のままに変更 - yomi = word + ## 例外を送出しない場合 + ## 読めない文字は「ん」として扱う + logger.warning(f"Cannot read: {word} in:\n{norm_text}, replaced with 'ん'") + # word の文字数分「ん」を追加 + yomi = "ン" * len(word) + else: + # yomi は元の記号のままに変更 + yomi = word elif yomi == "?": assert word == "?", f"yomi `?` comes from: {word}" yomi = "?" @@ -152,6 +158,188 @@ def text_to_sep_kata( return sep_text, sep_kata +def adjust_word2ph( + word2ph: list[int], generated_phone: list[str], given_phone: list[str], +) -> list[int]: + """ + `g2p()` で得られた `word2ph` を、generated_phone と given_phone の差分情報を使っていい感じに調整する。 + generated_phone は正規化された読み上げテキストから生成された読みの情報だが、 + given_phone で 同じ読み上げテキストに異なる読みが与えられた場合、正規化された読み上げテキストの各文字に + 音素が何文字割り当てられるかを示す word2ph の合計値が given_phone の長さ (音素数) と一致しなくなりうる + そこで generated_phone と given_phone の差分を取り変更箇所に対応する word2ph の要素の値だけを増減させ、 + アクセントへの影響を最低限に抑えつつ word2ph の合計値を given_phone の長さ (音素数) に一致させる。 + + Args: + word2ph (list[int]): 単語ごとの音素の数のリスト + generated_phone (list[str]): 生成された音素のリスト + given_phone (list[str]): 与えられた音素のリスト + + Returns: + list[int]: 修正された word2ph のリスト + """ + + # word2ph・generated_phone・given_phone 全ての先頭と末尾にダミー要素が入っているので、処理の都合上それらを削除 + # word2ph は先頭と末尾に 1 が入っている (返す際に再度追加する) + word2ph = word2ph[1:-1] + generated_phone = generated_phone[1:-1] + given_phone = given_phone[1:-1] + + class DiffDetail(TypedDict): + begin_index: int + end_index: int + value: list[str] + class Diff(TypedDict): + generated: DiffDetail + given: DiffDetail + + def extract_differences(generated_phone: list[str], given_phone: list[str]) -> list[Diff]: + """ + 最長共通部分列を基にして、二つのリストの異なる部分を抽出する。 + """ + + def longest_common_subsequence(X: list[str], Y: list[str]) -> list[tuple[int, int]]: + """ + 二つのリストの最長共通部分列のインデックスのペアを返す。 + """ + m, n = len(X), len(Y) + L = [[0] * (n + 1) for _ in range(m + 1)] + # LCSの長さを構築 + for i in range(1, m + 1): + for j in range(1, n + 1): + if X[i - 1] == Y[j - 1]: + L[i][j] = L[i - 1][j - 1] + 1 + else: + L[i][j] = max(L[i - 1][j], L[i][j - 1]) + # LCSを逆方向にトレースしてインデックスのペアを取得 + index_pairs = [] + i, j = m, n + while i > 0 and j > 0: + if X[i - 1] == Y[j - 1]: + index_pairs.append((i - 1, j - 1)) + i -= 1 + j -= 1 + elif L[i - 1][j] >= L[i][j - 1]: + i -= 1 + else: + j -= 1 + index_pairs.reverse() + return index_pairs + + differences = [] + common_indices = longest_common_subsequence(generated_phone, given_phone) + prev_x, prev_y = -1, -1 + + # 共通部分のインデックスを基にして差分を抽出 + for (x, y) in common_indices: + diff_X = {"begin_index": prev_x + 1, "end_index": x, "value": generated_phone[prev_x + 1:x]} + diff_Y = {"begin_index": prev_y + 1, "end_index": y, "value": given_phone[prev_y + 1:y]} + if diff_X or diff_Y: + differences.append({"generated": diff_X, "given": diff_Y}) + prev_x, prev_y = x, y + # 最後の非共通部分を追加 + if prev_x < len(generated_phone) - 1 or prev_y < len(given_phone) - 1: + differences.append({ + "generated": {"begin_index": prev_x + 1, "end_index": len(generated_phone) - 1, "value": generated_phone[prev_x + 1:len(generated_phone) - 1]}, + "given": {"begin_index": prev_y + 1, "end_index": len(given_phone) - 1, "value": given_phone[prev_y + 1:len(given_phone) - 1]} + }) + # generated.value と given.value の両方が空の要素を diffrences から削除 + for diff in differences[:]: + if len(diff["generated"]["value"]) == 0 and len(diff["given"]["value"]) == 0: + differences.remove(diff) + + return differences + + # 二つのリストの差分を抽出 + differences = extract_differences(generated_phone, given_phone) + + # word2ph をもとにして新しく作る word2ph のリスト + ## 長さは word2ph と同じだが、中身は 0 で初期化されている + adjusted_word2ph: list[int] = [0] * len(word2ph) + # 現在処理中の generated_phone のインデックス + current_generated_index = 0 + + # word2ph の要素数 (=正規化された読み上げテキストの文字数) を維持しながら、差分情報を使って word2ph を修正 + ## 音素数が generated_phone と given_phone で異なる場合にこの align_word2ph() が呼び出される + ## word2ph は正規化された読み上げテキストの文字数に対応しているので、要素数はそのまま given_phone で増減した音素数に合わせて各要素の値を増減する + for word2ph_element_index, word2ph_element in enumerate(word2ph): + # ここの word2ph_element は、正規化された読み上げテキストの各文字に割り当てられる音素の数を示す + # 例えば word2ph_element が 2 ならば、その文字には 2 つの音素 (例: "k", "a") が割り当てられる + # 音素の数だけループを回す + for _ in range(word2ph_element): + # difference の中に 処理中の generated_phone から始まる差分があるかどうかを確認 + current_diff: Diff | None = None + for diff in differences: + if diff["generated"]["begin_index"] == current_generated_index: + current_diff = diff + break + # current_diff が None でない場合、generated_phone から始まる差分がある + if current_diff is not None: + # generated から given で変わった音素数の差分を取得 (2増えた場合は +2 だし、2減った場合は -2) + diff_in_phonemes = len(current_diff["given"]["value"]) - len(current_diff["generated"]["value"]) + # adjusted_word2ph[(読み上げテキストの各文字のインデックス)] に上記差分を反映 + adjusted_word2ph[word2ph_element_index] += diff_in_phonemes + # adjusted_word2ph[(読み上げテキストの各文字のインデックス)] に処理が完了した分の音素として 1 を加える + adjusted_word2ph[word2ph_element_index] += 1 + # 処理中の generated_phone のインデックスを進める + current_generated_index += 1 + + # この時点で given_phone の長さと adjusted_word2ph に記録されている音素数の合計が一致しているはず + assert len(given_phone) == sum(adjusted_word2ph), f"{len(given_phone)} != {sum(adjusted_word2ph)}" + + # generated_phone から given_phone の間で音素が減った場合 (例: a, sh, i, t, a -> a, s, u) 、 + # adjusted_word2ph の要素の値が 1 未満になることがあるので、1 になるように値を増やす + ## この時、adjusted_word2ph に記録されている音素数の合計を変えないために、 + ## 値を 1 にした分だけ右隣の要素から増やした分の差分を差し引く + for adjusted_word2ph_element_index, adjusted_word2ph_element in enumerate(adjusted_word2ph): + # もし現在の要素が 1 未満ならば + if adjusted_word2ph_element < 1: + # 値を 1 にするためにどれだけ足せばいいかを計算 + diff = 1 - adjusted_word2ph_element + # adjusted_word2ph[(読み上げテキストの各文字のインデックス)] を 1 にする + # これにより、当該文字に最低ラインとして 1 つの音素が割り当てられる + adjusted_word2ph[adjusted_word2ph_element_index] = 1 + # 次の要素のうち、一番近くてかつ 1 以上の要素から diff を引く + # この時、diff を引いた結果引いた要素が 1 未満になる場合は、その要素の次の要素の中から一番近くてかつ 1 以上の要素から引く + # 上記を繰り返していって、diff が 0 になるまで続ける + for i in range(1, len(adjusted_word2ph)): + if adjusted_word2ph_element_index + i >= len(adjusted_word2ph): + break # adjusted_word2ph の最後に達した場合は諦める + if adjusted_word2ph[adjusted_word2ph_element_index + i] - diff >= 1: + adjusted_word2ph[adjusted_word2ph_element_index + i] -= diff + break + else: + diff -= adjusted_word2ph[adjusted_word2ph_element_index + i] - 1 + adjusted_word2ph[adjusted_word2ph_element_index + i] = 1 + if diff == 0: + break + + # 逆に、generated_phone から given_phone の間で音素が増えた場合 (例: a, s, u -> a, sh, i, t, a) 、 + # 1文字あたり7音素以上も割り当てられてしまう場合があるので、最大6音素にした上で削った分の差分を次の要素に加える + # 次の要素に差分を加えた結果7音素以上になってしまう場合は、その差分をさらに次の要素に加える + for adjusted_word2ph_element_index, adjusted_word2ph_element in enumerate(adjusted_word2ph): + if adjusted_word2ph_element > 6: + diff = adjusted_word2ph_element - 6 + adjusted_word2ph[adjusted_word2ph_element_index] = 6 + for i in range(1, len(adjusted_word2ph)): + if adjusted_word2ph_element_index + i >= len(adjusted_word2ph): + break # adjusted_word2ph の最後に達した場合は諦める + if adjusted_word2ph[adjusted_word2ph_element_index + i] + diff <= 6: + adjusted_word2ph[adjusted_word2ph_element_index + i] += diff + break + else: + diff -= 6 - adjusted_word2ph[adjusted_word2ph_element_index + i] + adjusted_word2ph[adjusted_word2ph_element_index + i] = 6 + if diff == 0: + break + + # この時点で given_phone の長さと adjusted_word2ph に記録されている音素数の合計が一致していない場合、 + # 正規化された読み上げテキストと given_phone が著しく乖離していることを示す + # このとき、この関数の呼び出し元の get_text() にて InvalidPhoneError が送出される + + # 最初に削除した前後のダミー要素を追加して返す + return [1] + adjusted_word2ph + [1] + + def __g2phone_tone_wo_punct(text: str) -> list[tuple[str, int]]: """ テキストに対して、音素とアクセント(0か1)のペアのリストを返す。 @@ -446,6 +634,10 @@ def __align_tones( elif phone in PUNCTUATIONS: # phone が punctuation の場合 → (phone, 0) を追加 result.append((phone, 0)) + elif phone == 'N' or phone == 'n': + # ここに到達するのは raise_yomi_error=False 時に読めない文字を「ん」に代替した場合のみ + # この際、phone_tone_list には「ん」の音素は含まれていないので、(phone, 0) を追加 + result.append((phone, 0)) else: logger.debug(f"phones: {phones_with_punct}") logger.debug(f"phone_tone_list: {phone_tone_list}") diff --git a/style_bert_vits2/tts_model.py b/style_bert_vits2/tts_model.py index 1280308..dbead9e 100644 --- a/style_bert_vits2/tts_model.py +++ b/style_bert_vits2/tts_model.py @@ -29,7 +29,6 @@ from style_bert_vits2.models.models import SynthesizerTrn from style_bert_vits2.models.models_jp_extra import ( SynthesizerTrn as SynthesizerTrnJPExtra, ) -from style_bert_vits2.nlp import bert_models from style_bert_vits2.voice import adjust_voice @@ -155,6 +154,7 @@ class TTSModel: use_assist_text: bool = False, style: str = DEFAULT_STYLE, style_weight: float = DEFAULT_STYLE_WEIGHT, + given_phone: Optional[list[str]] = None, given_tone: Optional[list[int]] = None, pitch_scale: float = 1.0, intonation_scale: float = 1.0, @@ -171,13 +171,14 @@ class TTSModel: noise (float, optional): DP に与えられるノイズ. Defaults to DEFAULT_NOISE. noise_w (float, optional): SDP に与えられるノイズ. Defaults to DEFAULT_NOISEW. length (float, optional): 生成音声の長さ(話速)のパラメータ。大きいほど生成音声が長くゆっくり、小さいほど短く早くなる。 Defaults to DEFAULT_LENGTH. - line_split (bool, optional): テキストを改行ごとに分割して生成するかどうか. Defaults to DEFAULT_LINE_SPLIT. + line_split (bool, optional): テキストを改行ごとに分割して生成するかどうか (True の場合 given_phone/given_tone は無視される). Defaults to DEFAULT_LINE_SPLIT. split_interval (float, optional): 改行ごとに分割する場合の無音 (秒). Defaults to DEFAULT_SPLIT_INTERVAL. assist_text (Optional[str], optional): 感情表現の参照元の補助テキスト. Defaults to None. assist_text_weight (float, optional): 感情表現の補助テキストを適用する強さ. Defaults to DEFAULT_ASSIST_TEXT_WEIGHT. use_assist_text (bool, optional): 音声合成時に感情表現の補助テキストを使用するかどうか. Defaults to False. style (str, optional): 音声スタイル (Neutral, Happy など). Defaults to DEFAULT_STYLE. style_weight (float, optional): 音声スタイルを適用する強さ. Defaults to DEFAULT_STYLE_WEIGHT. + given_phone (Optional[list[int]], optional): 読み上げテキストの読みを表す音素列。指定する場合は given_tone も別途指定が必要. Defaults to None. given_tone (Optional[list[int]], optional): アクセントのトーンのリスト. Defaults to None. pitch_scale (float, optional): ピッチの高さ (1.0 から変更すると若干音質が低下する). Defaults to 1.0. intonation_scale (float, optional): 抑揚の平均からの変化幅 (1.0 から変更すると若干音質が低下する). Defaults to 1.0. @@ -222,6 +223,7 @@ class TTSModel: assist_text=assist_text, assist_text_weight=assist_text_weight, style_vec=style_vector, + given_phone=given_phone, given_tone=given_tone, ) else: From 9d15d5763de90b6f6f7675a5e2e45c7064bfe60d Mon Sep 17 00:00:00 2001 From: tsukumi Date: Fri, 19 Apr 2024 04:17:27 +0000 Subject: [PATCH 2/9] Refactor: run "hatch run style:fmt" --- style_bert_vits2/models/infer.py | 2 + style_bert_vits2/nlp/japanese/g2p.py | 65 ++++++++++++++++++++-------- 2 files changed, 50 insertions(+), 17 deletions(-) diff --git a/style_bert_vits2/models/infer.py b/style_bert_vits2/models/infer.py index da416b8..a9a4869 100644 --- a/style_bert_vits2/models/infer.py +++ b/style_bert_vits2/models/infer.py @@ -126,6 +126,7 @@ def get_text( # 他の言語は word2ph の調整方法が思いつかないのでエラー if language_str == Languages.JP: from style_bert_vits2.nlp.japanese.g2p import adjust_word2ph + word2ph = adjust_word2ph(word2ph, phone, given_phone) # 上記処理により word2ph の合計が given_phone の長さと一致するはず # それでも一致しない場合、大半は読み上げテキストと given_phone が著しく乖離していて調整し切れなかったことを意味する @@ -302,5 +303,6 @@ def infer( class InvalidPhoneError(ValueError): pass + class InvalidToneError(ValueError): pass diff --git a/style_bert_vits2/nlp/japanese/g2p.py b/style_bert_vits2/nlp/japanese/g2p.py index 8038573..2443305 100644 --- a/style_bert_vits2/nlp/japanese/g2p.py +++ b/style_bert_vits2/nlp/japanese/g2p.py @@ -143,7 +143,9 @@ def text_to_sep_kata( raise YomiError(f"Cannot read: {word} in:\n{norm_text}") ## 例外を送出しない場合 ## 読めない文字は「ん」として扱う - logger.warning(f"Cannot read: {word} in:\n{norm_text}, replaced with 'ん'") + logger.warning( + f"Cannot read: {word} in:\n{norm_text}, replaced with 'ん'" + ) # word の文字数分「ん」を追加 yomi = "ン" * len(word) else: @@ -159,7 +161,9 @@ def text_to_sep_kata( def adjust_word2ph( - word2ph: list[int], generated_phone: list[str], given_phone: list[str], + word2ph: list[int], + generated_phone: list[str], + given_phone: list[str], ) -> list[int]: """ `g2p()` で得られた `word2ph` を、generated_phone と given_phone の差分情報を使っていい感じに調整する。 @@ -188,16 +192,21 @@ def adjust_word2ph( begin_index: int end_index: int value: list[str] + class Diff(TypedDict): generated: DiffDetail given: DiffDetail - def extract_differences(generated_phone: list[str], given_phone: list[str]) -> list[Diff]: + def extract_differences( + generated_phone: list[str], given_phone: list[str] + ) -> list[Diff]: """ 最長共通部分列を基にして、二つのリストの異なる部分を抽出する。 """ - def longest_common_subsequence(X: list[str], Y: list[str]) -> list[tuple[int, int]]: + def longest_common_subsequence( + X: list[str], Y: list[str] + ) -> list[tuple[int, int]]: """ 二つのリストの最長共通部分列のインデックスのペアを返す。 """ @@ -230,21 +239,42 @@ def adjust_word2ph( prev_x, prev_y = -1, -1 # 共通部分のインデックスを基にして差分を抽出 - for (x, y) in common_indices: - diff_X = {"begin_index": prev_x + 1, "end_index": x, "value": generated_phone[prev_x + 1:x]} - diff_Y = {"begin_index": prev_y + 1, "end_index": y, "value": given_phone[prev_y + 1:y]} + for x, y in common_indices: + diff_X = { + "begin_index": prev_x + 1, + "end_index": x, + "value": generated_phone[prev_x + 1 : x], + } + diff_Y = { + "begin_index": prev_y + 1, + "end_index": y, + "value": given_phone[prev_y + 1 : y], + } if diff_X or diff_Y: differences.append({"generated": diff_X, "given": diff_Y}) prev_x, prev_y = x, y # 最後の非共通部分を追加 if prev_x < len(generated_phone) - 1 or prev_y < len(given_phone) - 1: - differences.append({ - "generated": {"begin_index": prev_x + 1, "end_index": len(generated_phone) - 1, "value": generated_phone[prev_x + 1:len(generated_phone) - 1]}, - "given": {"begin_index": prev_y + 1, "end_index": len(given_phone) - 1, "value": given_phone[prev_y + 1:len(given_phone) - 1]} - }) + differences.append( + { + "generated": { + "begin_index": prev_x + 1, + "end_index": len(generated_phone) - 1, + "value": generated_phone[prev_x + 1 : len(generated_phone) - 1], + }, + "given": { + "begin_index": prev_y + 1, + "end_index": len(given_phone) - 1, + "value": given_phone[prev_y + 1 : len(given_phone) - 1], + }, + } + ) # generated.value と given.value の両方が空の要素を diffrences から削除 for diff in differences[:]: - if len(diff["generated"]["value"]) == 0 and len(diff["given"]["value"]) == 0: + if ( + len(diff["generated"]["value"]) == 0 + and len(diff["given"]["value"]) == 0 + ): differences.remove(diff) return differences @@ -275,7 +305,8 @@ def adjust_word2ph( # current_diff が None でない場合、generated_phone から始まる差分がある if current_diff is not None: # generated から given で変わった音素数の差分を取得 (2増えた場合は +2 だし、2減った場合は -2) - diff_in_phonemes = len(current_diff["given"]["value"]) - len(current_diff["generated"]["value"]) + diff_in_phonemes = \ + len(current_diff["given"]["value"]) - len(current_diff["generated"]["value"]) # fmt: skip # adjusted_word2ph[(読み上げテキストの各文字のインデックス)] に上記差分を反映 adjusted_word2ph[word2ph_element_index] += diff_in_phonemes # adjusted_word2ph[(読み上げテキストの各文字のインデックス)] に処理が完了した分の音素として 1 を加える @@ -284,13 +315,13 @@ def adjust_word2ph( current_generated_index += 1 # この時点で given_phone の長さと adjusted_word2ph に記録されている音素数の合計が一致しているはず - assert len(given_phone) == sum(adjusted_word2ph), f"{len(given_phone)} != {sum(adjusted_word2ph)}" + assert len(given_phone) == sum(adjusted_word2ph), f"{len(given_phone)} != {sum(adjusted_word2ph)}" # fmt: skip # generated_phone から given_phone の間で音素が減った場合 (例: a, sh, i, t, a -> a, s, u) 、 # adjusted_word2ph の要素の値が 1 未満になることがあるので、1 になるように値を増やす ## この時、adjusted_word2ph に記録されている音素数の合計を変えないために、 ## 値を 1 にした分だけ右隣の要素から増やした分の差分を差し引く - for adjusted_word2ph_element_index, adjusted_word2ph_element in enumerate(adjusted_word2ph): + for adjusted_word2ph_element_index, adjusted_word2ph_element in enumerate(adjusted_word2ph): # fmt: skip # もし現在の要素が 1 未満ならば if adjusted_word2ph_element < 1: # 値を 1 にするためにどれだけ足せばいいかを計算 @@ -316,7 +347,7 @@ def adjust_word2ph( # 逆に、generated_phone から given_phone の間で音素が増えた場合 (例: a, s, u -> a, sh, i, t, a) 、 # 1文字あたり7音素以上も割り当てられてしまう場合があるので、最大6音素にした上で削った分の差分を次の要素に加える # 次の要素に差分を加えた結果7音素以上になってしまう場合は、その差分をさらに次の要素に加える - for adjusted_word2ph_element_index, adjusted_word2ph_element in enumerate(adjusted_word2ph): + for adjusted_word2ph_element_index, adjusted_word2ph_element in enumerate(adjusted_word2ph): # fmt: skip if adjusted_word2ph_element > 6: diff = adjusted_word2ph_element - 6 adjusted_word2ph[adjusted_word2ph_element_index] = 6 @@ -634,7 +665,7 @@ def __align_tones( elif phone in PUNCTUATIONS: # phone が punctuation の場合 → (phone, 0) を追加 result.append((phone, 0)) - elif phone == 'N' or phone == 'n': + elif phone == "N" or phone == "n": # ここに到達するのは raise_yomi_error=False 時に読めない文字を「ん」に代替した場合のみ # この際、phone_tone_list には「ん」の音素は含まれていないので、(phone, 0) を追加 result.append((phone, 0)) From 28f254f44927c4f6bd989b5f71031ad1db51425f Mon Sep 17 00:00:00 2001 From: tsukumi Date: Tue, 23 Apr 2024 05:45:11 +0000 Subject: [PATCH 3/9] Improve: remove Gradio dependency from style_bert_vits2 as a library --- pyproject.toml | 1 - style_bert_vits2/tts_model.py | 65 +++++++++++++++++++++++++++++------ 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 2d26680..c0493a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,6 @@ dependencies = [ 'cmudict', 'cn2an', 'g2p_en', - 'gradio', 'jieba', 'librosa==0.9.2', 'loguru', diff --git a/style_bert_vits2/tts_model.py b/style_bert_vits2/tts_model.py index dbead9e..99a9901 100644 --- a/style_bert_vits2/tts_model.py +++ b/style_bert_vits2/tts_model.py @@ -1,12 +1,9 @@ -import warnings from pathlib import Path -from typing import Any, Optional, Union +from typing import TYPE_CHECKING, Any, Optional, Union -import gradio as gr import numpy as np import pyannote.audio import torch -from gradio.processing_utils import convert_to_16_bit_wav from numpy.typing import NDArray from pydantic import BaseModel @@ -32,6 +29,13 @@ from style_bert_vits2.models.models_jp_extra import ( from style_bert_vits2.voice import adjust_voice +# Gradio の import は重いため、ここでは型チェック時のみ import する +# ライブラリとしての利用を考慮し、TTSModelHolder の _for_gradio() 系メソッド以外では Gradio に依存しないようにする +# _for_gradio() 系メソッドの戻り値の型アノテーションを文字列としているのは、Gradio なしで実行できるようにするため +if TYPE_CHECKING: + import gradio as gr + + class TTSModel: """ Style-Bert-Vits2 の音声合成モデルを操作するクラス。 @@ -137,6 +141,43 @@ class TTSModel: xvec = mean + (xvec - mean) * weight return xvec + def __convert_to_16_bit_wav(self, data: NDArray[Any]) -> NDArray[Any]: + """ + 音声データを 16-bit int 形式に変換する。 + gradio.processing_utils.convert_to_16_bit_wav() を移植したもの。 + + Args: + data (NDArray[Any]): 音声データ + + Returns: + NDArray[Any]: 16-bit int 形式の音声データ + """ + # Based on: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.write.html + if data.dtype in [np.float64, np.float32, np.float16]: # type: ignore + data = data / np.abs(data).max() + data = data * 32767 + data = data.astype(np.int16) + elif data.dtype == np.int32: + data = data / 65536 + data = data.astype(np.int16) + elif data.dtype == np.int16: + pass + elif data.dtype == np.uint16: + data = data - 32768 + data = data.astype(np.int16) + elif data.dtype == np.uint8: + data = data * 257 - 32768 + data = data.astype(np.int16) + elif data.dtype == np.int8: + data = data * 256 + data = data.astype(np.int16) + else: + raise ValueError( + "Audio data cannot be converted automatically from " + f"{data.dtype} to 16-bit int format." + ) + return data + def infer( self, text: str, @@ -260,9 +301,7 @@ class TTSModel: pitch_scale=pitch_scale, intonation_scale=intonation_scale, ) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - audio = convert_to_16_bit_wav(audio) + audio = self.__convert_to_16_bit_wav(audio) return (self.hyper_parameters.data.sampling_rate, audio) @@ -381,7 +420,9 @@ class TTSModelHolder: def get_model_for_gradio( self, model_name: str, model_path_str: str - ) -> tuple[gr.Dropdown, gr.Button, gr.Dropdown]: + ) -> tuple["gr.Dropdown", "gr.Button", "gr.Dropdown"]: + import gradio as gr + model_path = Path(model_path_str) if model_name not in self.model_files_dict: raise ValueError(f"Model `{model_name}` is not found") @@ -413,13 +454,17 @@ class TTSModelHolder: gr.Dropdown(choices=speakers, value=speakers[0]), # type: ignore ) - def update_model_files_for_gradio(self, model_name: str) -> gr.Dropdown: + def update_model_files_for_gradio(self, model_name: str) -> "gr.Dropdown": + import gradio as gr + model_files = self.model_files_dict[model_name] return gr.Dropdown(choices=model_files, value=model_files[0]) # type: ignore def update_model_names_for_gradio( self, - ) -> tuple[gr.Dropdown, gr.Dropdown, gr.Button]: + ) -> tuple["gr.Dropdown", "gr.Dropdown", "gr.Button"]: + import gradio as gr + self.refresh() initial_model_name = self.model_names[0] initial_model_files = self.model_files_dict[initial_model_name] From aa0f9308b111a0c386f78f93565570d9072961c7 Mon Sep 17 00:00:00 2001 From: tsukumi Date: Thu, 25 Apr 2024 00:31:14 +0000 Subject: [PATCH 4/9] Refactor: remove dependencies on libraries not required for style_bert_vits2 as a library librosa: Originally not used under style_bert_vits2/. pyannote.audio: Required only when using the "infer style vector from audio" function during inference, but it is currently almost unused. scipy: Because it was used in only one utility function that was not needed outside of training. --- pyproject.toml | 3 --- style_bert_vits2/models/utils/__init__.py | 8 +++++++- style_bert_vits2/tts_model.py | 15 ++++++++++++--- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c0493a3..77306ad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,18 +26,15 @@ dependencies = [ 'cn2an', 'g2p_en', 'jieba', - 'librosa==0.9.2', 'loguru', 'num2words', 'numba', 'numpy', - 'pyannote.audio>=3.1.0', 'pydantic>=2.0', 'pyopenjtalk-dict', 'pypinyin', 'pyworld-prebuilt', 'safetensors', - 'scipy', 'torch>=2.1', 'transformers', ] diff --git a/style_bert_vits2/models/utils/__init__.py b/style_bert_vits2/models/utils/__init__.py index edd51cc..2e750c8 100644 --- a/style_bert_vits2/models/utils/__init__.py +++ b/style_bert_vits2/models/utils/__init__.py @@ -9,7 +9,6 @@ from typing import TYPE_CHECKING, Any, Optional, Union import numpy as np import torch from numpy.typing import NDArray -from scipy.io.wavfile import read from style_bert_vits2.logging import logger from style_bert_vits2.models.utils import checkpoints # type: ignore @@ -162,6 +161,13 @@ def load_wav_to_torch(full_path: Union[str, Path]) -> tuple[torch.FloatTensor, i tuple[torch.FloatTensor, int]: 音声データのテンソルとサンプリングレート """ + # この関数は学習時以外使われないため、ライブラリとしての style_bert_vits2 が + # 重たい scipy に依存しないように遅延 import する + try: + from scipy.io.wavfile import read + except ImportError: + raise ImportError("scipy is required to load wav file") + sampling_rate, data = read(full_path) return torch.FloatTensor(data.astype(np.float32)), sampling_rate diff --git a/style_bert_vits2/tts_model.py b/style_bert_vits2/tts_model.py index 99a9901..83ebcad 100644 --- a/style_bert_vits2/tts_model.py +++ b/style_bert_vits2/tts_model.py @@ -2,7 +2,6 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Optional, Union import numpy as np -import pyannote.audio import torch from numpy.typing import NDArray from pydantic import BaseModel @@ -76,7 +75,7 @@ class TTSModel: f"Number of styles ({num_styles}) does not match the number of style2id ({len(self.style2id)})" ) - self.__style_vector_inference: Optional[pyannote.audio.Inference] = None + self.__style_vector_inference: Optional[Any] = None self.__style_vectors: NDArray[Any] = np.load(self.style_vec_path) if self.__style_vectors.shape[0] != num_styles: raise ValueError( @@ -125,8 +124,18 @@ class TTSModel: NDArray[Any]: スタイルベクトル """ - # スタイルベクトルを取得するための推論モデルを初期化 if self.__style_vector_inference is None: + + # pyannote.audio は scikit-learn などの大量の重量級ライブラリに依存しているため、 + # TTSModel.infer() に reference_audio_path を指定し音声からスタイルベクトルを推論する場合のみ遅延 import する + try: + import pyannote.audio + except ImportError: + raise ImportError( + "pyannote.audio is required to infer style vector from audio" + ) + + # スタイルベクトルを取得するための推論モデルを初期化 self.__style_vector_inference = pyannote.audio.Inference( model=pyannote.audio.Model.from_pretrained( "pyannote/wespeaker-voxceleb-resnet34-LM" From 0d9034b8bda8992f3e2c623e3beb43242f0d4cdb Mon Sep 17 00:00:00 2001 From: tsukumi Date: Wed, 1 May 2024 11:21:01 +0900 Subject: [PATCH 5/9] Fix text encoding in Server.bat --- Server.bat | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Server.bat b/Server.bat index 816cc45..cec9b1d 100644 --- a/Server.bat +++ b/Server.bat @@ -1,11 +1,11 @@ -chcp 65001 > NUL -@echo off - -pushd %~dp0 -echo Running server_fastapi.py -venv\Scripts\python server_fastapi.py - -if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% ) - -popd +chcp 65001 > NUL +@echo off + +pushd %~dp0 +echo Running server_fastapi.py +venv\Scripts\python server_fastapi.py + +if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% ) + +popd pause \ No newline at end of file From b23083252815094bd653a406d96fa930f643b75d Mon Sep 17 00:00:00 2001 From: tsukumi Date: Mon, 6 May 2024 20:43:22 +0900 Subject: [PATCH 6/9] Add: allow hyper-parameters and style vectors to be specified directly --- style_bert_vits2/tts_model.py | 38 ++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/style_bert_vits2/tts_model.py b/style_bert_vits2/tts_model.py index 83ebcad..c60a632 100644 --- a/style_bert_vits2/tts_model.py +++ b/style_bert_vits2/tts_model.py @@ -42,7 +42,11 @@ class TTSModel: """ def __init__( - self, model_path: Path, config_path: Path, style_vec_path: Path, device: str + self, + model_path: Path, + config_path: Union[Path, HyperParameters], + style_vec_path: Union[Path, NDArray[Any]], + device: str, ) -> None: """ Style-Bert-Vits2 の音声合成モデルを初期化する。 @@ -50,18 +54,33 @@ class TTSModel: Args: model_path (Path): モデル (.safetensors) のパス - config_path (Path): ハイパーパラメータ (config.json) のパス - style_vec_path (Path): スタイルベクトル (style_vectors.npy) のパス + config_path (Union[Path, HyperParameters]): ハイパーパラメータ (config.json) のパス (直接 HyperParameters を指定することも可能) + style_vec_path (Union[Path, NDArray[Any]]): スタイルベクトル (style_vectors.npy) のパス (直接 NDArray を指定することも可能) device (str): 音声合成時に利用するデバイス (cpu, cuda, mps など) """ self.model_path: Path = model_path - self.config_path: Path = config_path - self.style_vec_path: Path = style_vec_path self.device: str = device - self.hyper_parameters: HyperParameters = HyperParameters.load_from_json( - self.config_path - ) + + # ハイパーパラメータの Pydantic モデルが直接指定された + if isinstance(config_path, HyperParameters): + self.config_path: Path = Path("") # 互換性のため空の Path を設定 + self.hyper_parameters: HyperParameters = config_path + # ハイパーパラメータのパスが指定された + else: + self.config_path: Path = config_path + self.hyper_parameters: HyperParameters = \ + HyperParameters.load_from_json(self.config_path) + + # スタイルベクトルの NDArray が直接指定された + if isinstance(style_vec_path, np.ndarray): + self.style_vec_path: Path = Path("") # 互換性のため空の Path を設定 + self.__style_vectors: NDArray[Any] = style_vec_path + # スタイルベクトルのパスが指定された + else: + self.style_vec_path: Path = style_vec_path + self.__style_vectors: NDArray[Any] = np.load(self.style_vec_path) + self.spk2id: dict[str, int] = self.hyper_parameters.data.spk2id self.id2spk: dict[int, str] = {v: k for k, v in self.spk2id.items()} @@ -75,12 +94,11 @@ class TTSModel: f"Number of styles ({num_styles}) does not match the number of style2id ({len(self.style2id)})" ) - self.__style_vector_inference: Optional[Any] = None - self.__style_vectors: NDArray[Any] = np.load(self.style_vec_path) if self.__style_vectors.shape[0] != num_styles: raise ValueError( f"The number of styles ({num_styles}) does not match the number of style vectors ({self.__style_vectors.shape[0]})" ) + self.__style_vector_inference: Optional[Any] = None self.__net_g: Union[SynthesizerTrn, SynthesizerTrnJPExtra, None] = None From 87144dd321ea6cc3c65d76772ca0d01e0699c0cf Mon Sep 17 00:00:00 2001 From: tsukumi Date: Mon, 6 May 2024 20:56:07 +0900 Subject: [PATCH 7/9] Improve: automatically generate configs/paths.yml by copying it from configs/default_paths.yml when running initialize.py If configs/paths.yml itself is included in version control, differences will occur when it is changed in each environment, which is troublesome. --- .gitignore | 2 ++ configs/{paths.yml => default_paths.yml} | 0 gradio_tabs/style_vectors.py | 1 + initialize.py | 8 +++++++- style_bert_vits2/tts_model.py | 5 +++-- 5 files changed, 13 insertions(+), 3 deletions(-) rename configs/{paths.yml => default_paths.yml} (100%) diff --git a/.gitignore b/.gitignore index aa114e3..cc5fed4 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,8 @@ dist/ /bert/*/*.safetensors /bert/*/*.msgpack +/configs/paths.yml + /pretrained/*.safetensors /pretrained/*.pth diff --git a/configs/paths.yml b/configs/default_paths.yml similarity index 100% rename from configs/paths.yml rename to configs/default_paths.yml diff --git a/gradio_tabs/style_vectors.py b/gradio_tabs/style_vectors.py index 9234cff..af43258 100644 --- a/gradio_tabs/style_vectors.py +++ b/gradio_tabs/style_vectors.py @@ -16,6 +16,7 @@ from config import config from style_bert_vits2.constants import DEFAULT_STYLE, GRADIO_THEME from style_bert_vits2.logging import logger + # Get path settings with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f: path_config: dict[str, str] = yaml.safe_load(f.read()) diff --git a/initialize.py b/initialize.py index bfe59e4..664d570 100644 --- a/initialize.py +++ b/initialize.py @@ -1,5 +1,6 @@ import argparse import json +import shutil from pathlib import Path import yaml @@ -102,11 +103,16 @@ def main(): download_pretrained_models() download_jp_extra_pretrained_models() + # If configs/paths.yml not exists, create it + default_paths_yml = Path("configs/default_paths.yml") + paths_yml = Path("configs/paths.yml") + if not paths_yml.exists(): + shutil.copy(default_paths_yml, paths_yml) + if args.dataset_root is None and args.assets_root is None: return # Change default paths if necessary - paths_yml = Path("configs/paths.yml") with open(paths_yml, "r", encoding="utf-8") as f: yml_data = yaml.safe_load(f) if args.assets_root is not None: diff --git a/style_bert_vits2/tts_model.py b/style_bert_vits2/tts_model.py index c60a632..092957c 100644 --- a/style_bert_vits2/tts_model.py +++ b/style_bert_vits2/tts_model.py @@ -69,8 +69,9 @@ class TTSModel: # ハイパーパラメータのパスが指定された else: self.config_path: Path = config_path - self.hyper_parameters: HyperParameters = \ - HyperParameters.load_from_json(self.config_path) + self.hyper_parameters: HyperParameters = HyperParameters.load_from_json( + self.config_path + ) # スタイルベクトルの NDArray が直接指定された if isinstance(style_vec_path, np.ndarray): From 2d6baa3928d0cf225d4b21abf6d316c89dd3527b Mon Sep 17 00:00:00 2001 From: tsukumi Date: Mon, 6 May 2024 22:17:34 +0900 Subject: [PATCH 8/9] =?UTF-8?q?Fix:=20changed=20the=20substitute=20phoneme?= =?UTF-8?q?=20from=E3=80=8C=E3=82=93=E3=80=8Dto=20=E3=80=8C'=E3=80=8D=20wh?= =?UTF-8?q?en=20the=20pronunciation=20can't=20be=20obtained?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- style_bert_vits2/nlp/japanese/g2p.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/style_bert_vits2/nlp/japanese/g2p.py b/style_bert_vits2/nlp/japanese/g2p.py index 2443305..6b7b74a 100644 --- a/style_bert_vits2/nlp/japanese/g2p.py +++ b/style_bert_vits2/nlp/japanese/g2p.py @@ -24,7 +24,7 @@ def g2p( Args: norm_text (str): 正規化されたテキスト use_jp_extra (bool, optional): False の場合、「ん」の音素を「N」ではなく「n」とする。Defaults to True. - raise_yomi_error (bool, optional): False の場合、読めない文字が「ん」として発音される。Defaults to False. + raise_yomi_error (bool, optional): False の場合、読めない文字が「'」として発音される。Defaults to False. Returns: tuple[list[str], list[int], list[int]]: 音素のリスト、アクセントのリスト、word2ph のリスト @@ -40,7 +40,7 @@ def g2p( phone_tone_list_wo_punct = __g2phone_tone_wo_punct(norm_text) # sep_text: 単語単位の単語のリスト - # sep_kata: 単語単位の単語のカタカナ読みのリスト、読めない文字は raise_yomi_error=True なら例外、False なら読めない文字を「ン」として返ってくる + # sep_kata: 単語単位の単語のカタカナ読みのリスト、読めない文字は raise_yomi_error=True なら例外、False なら読めない文字を「'」として返ってくる sep_text, sep_kata = text_to_sep_kata(norm_text, raise_yomi_error=raise_yomi_error) # sep_phonemes: 各単語ごとの音素のリストのリスト @@ -104,7 +104,7 @@ def text_to_sep_kata( Args: norm_text (str): 正規化されたテキスト - raise_yomi_error (bool, optional): False の場合、読めない文字が「ん」として発音される。Defaults to False. + raise_yomi_error (bool, optional): False の場合、読めない文字が「'」として発音される。Defaults to False. Returns: tuple[list[str], list[str]]: 分割された単語リストと、その読み(カタカナ or 記号1文字)のリスト @@ -142,12 +142,12 @@ def text_to_sep_kata( if raise_yomi_error: raise YomiError(f"Cannot read: {word} in:\n{norm_text}") ## 例外を送出しない場合 - ## 読めない文字は「ん」として扱う + ## 読めない文字は「'」として扱う logger.warning( - f"Cannot read: {word} in:\n{norm_text}, replaced with 'ん'" + f"Cannot read: {word} in:\n{norm_text}, replaced with \"'\"" ) - # word の文字数分「ん」を追加 - yomi = "ン" * len(word) + # word の文字数分「'」を追加 + yomi = "'" * len(word) else: # yomi は元の記号のままに変更 yomi = word @@ -665,10 +665,6 @@ def __align_tones( elif phone in PUNCTUATIONS: # phone が punctuation の場合 → (phone, 0) を追加 result.append((phone, 0)) - elif phone == "N" or phone == "n": - # ここに到達するのは raise_yomi_error=False 時に読めない文字を「ん」に代替した場合のみ - # この際、phone_tone_list には「ん」の音素は含まれていないので、(phone, 0) を追加 - result.append((phone, 0)) else: logger.debug(f"phones: {phones_with_punct}") logger.debug(f"phone_tone_list: {phone_tone_list}") From 44693e7d6b153ee9d9b00a157c41b5749fc50535 Mon Sep 17 00:00:00 2001 From: tsukumi Date: Sun, 12 May 2024 00:26:46 +0900 Subject: [PATCH 9/9] Refactor: improve regular expression performance during NLP Improve performance by pre-compiling regular expressions that are executed many times. --- style_bert_vits2/nlp/chinese/normalizer.py | 73 ++++----- style_bert_vits2/nlp/japanese/g2p.py | 65 +++++--- style_bert_vits2/nlp/japanese/g2p_utils.py | 10 +- style_bert_vits2/nlp/japanese/mora_list.py | 12 ++ style_bert_vits2/nlp/japanese/normalizer.py | 161 ++++++++++---------- 5 files changed, 171 insertions(+), 150 deletions(-) diff --git a/style_bert_vits2/nlp/chinese/normalizer.py b/style_bert_vits2/nlp/chinese/normalizer.py index c56c636..8239bc7 100644 --- a/style_bert_vits2/nlp/chinese/normalizer.py +++ b/style_bert_vits2/nlp/chinese/normalizer.py @@ -5,6 +5,41 @@ import cn2an from style_bert_vits2.nlp.symbols import PUNCTUATIONS +__REPLACE_MAP = { + ":": ",", + ";": ",", + ",": ",", + "。": ".", + "!": "!", + "?": "?", + "\n": ".", + "·": ",", + "、": ",", + "...": "…", + "$": ".", + "“": "'", + "”": "'", + '"': "'", + "‘": "'", + "’": "'", + "(": "'", + ")": "'", + "(": "'", + ")": "'", + "《": "'", + "》": "'", + "【": "'", + "】": "'", + "[": "'", + "]": "'", + "—": "-", + "~": "-", + "~": "-", + "「": "'", + "」": "'", +} + + def normalize_text(text: str) -> str: numbers = re.findall(r"\d+(?:\.?\d+)?", text) for number in numbers: @@ -15,44 +50,10 @@ def normalize_text(text: str) -> str: def replace_punctuation(text: str) -> str: - REPLACE_MAP = { - ":": ",", - ";": ",", - ",": ",", - "。": ".", - "!": "!", - "?": "?", - "\n": ".", - "·": ",", - "、": ",", - "...": "…", - "$": ".", - "“": "'", - "”": "'", - '"': "'", - "‘": "'", - "’": "'", - "(": "'", - ")": "'", - "(": "'", - ")": "'", - "《": "'", - "》": "'", - "【": "'", - "】": "'", - "[": "'", - "]": "'", - "—": "-", - "~": "-", - "~": "-", - "「": "'", - "」": "'", - } - text = text.replace("嗯", "恩").replace("呣", "母") - pattern = re.compile("|".join(re.escape(p) for p in REPLACE_MAP.keys())) + pattern = re.compile("|".join(re.escape(p) for p in __REPLACE_MAP.keys())) - replaced_text = pattern.sub(lambda x: REPLACE_MAP[x.group()], text) + replaced_text = pattern.sub(lambda x: __REPLACE_MAP[x.group()], text) replaced_text = re.sub( r"[^\u4e00-\u9fa5" + "".join(PUNCTUATIONS) + r"]+", "", replaced_text diff --git a/style_bert_vits2/nlp/japanese/g2p.py b/style_bert_vits2/nlp/japanese/g2p.py index 6b7b74a..54270ba 100644 --- a/style_bert_vits2/nlp/japanese/g2p.py +++ b/style_bert_vits2/nlp/japanese/g2p.py @@ -5,7 +5,7 @@ from style_bert_vits2.constants import Languages from style_bert_vits2.logging import logger from style_bert_vits2.nlp import bert_models from style_bert_vits2.nlp.japanese import pyopenjtalk_worker as pyopenjtalk -from style_bert_vits2.nlp.japanese.mora_list import MORA_KATA_TO_MORA_PHONEMES +from style_bert_vits2.nlp.japanese.mora_list import MORA_KATA_TO_MORA_PHONEMES, VOWELS from style_bert_vits2.nlp.japanese.normalizer import replace_punctuation from style_bert_vits2.nlp.symbols import PUNCTUATIONS @@ -144,7 +144,7 @@ def text_to_sep_kata( ## 例外を送出しない場合 ## 読めない文字は「'」として扱う logger.warning( - f"Cannot read: {word} in:\n{norm_text}, replaced with \"'\"" + f'Cannot read: {word} in:\n{norm_text}, replaced with "\'"' ) # word の文字数分「'」を追加 yomi = "'" * len(word) @@ -428,15 +428,23 @@ def __g2phone_tone_wo_punct(text: str) -> list[tuple[str, int]]: return result +__PYOPENJTALK_G2P_PROSODY_A1_PATTERN = re.compile(r"/A:([0-9\-]+)\+") +__PYOPENJTALK_G2P_PROSODY_A2_PATTERN = re.compile(r"\+(\d+)\+") +__PYOPENJTALK_G2P_PROSODY_A3_PATTERN = re.compile(r"\+(\d+)/") +__PYOPENJTALK_G2P_PROSODY_E3_PATTERN = re.compile(r"!(\d+)_") +__PYOPENJTALK_G2P_PROSODY_F1_PATTERN = re.compile(r"/F:(\d+)_") +__PYOPENJTALK_G2P_PROSODY_P3_PATTERN = re.compile(r"\-(.*?)\+") + + def __pyopenjtalk_g2p_prosody( text: str, drop_unvoiced_vowels: bool = True ) -> list[str]: """ - ESPnet の実装から引用、変更点無し。「ん」は「N」なことに注意。 + ESPnet の実装から引用、概ね変更点無し。「ん」は「N」なことに注意。 ref: https://github.com/espnet/espnet/blob/master/espnet2/text/phoneme_tokenizer.py ------------------------------------------------------------------------------------------ - Extract phoneme + prosoody symbol sequence from input full-context labels. + Extract phoneme + prosody symbol sequence from input full-context labels. The algorithm is based on `Prosodic features control by symbols as input of sequence-to-sequence acoustic modeling for neural TTS`_ with some r9y9's tweaks. @@ -457,8 +465,8 @@ def __pyopenjtalk_g2p_prosody( modeling for neural TTS`: https://doi.org/10.1587/transinf.2020EDP7104 """ - def _numeric_feature_by_regex(regex: str, s: str) -> int: - match = re.search(regex, s) + def _numeric_feature_by_regex(pattern: re.Pattern[str], s: str) -> int: + match = pattern.search(s) if match is None: return -50 return int(match.group(1)) @@ -471,7 +479,7 @@ def __pyopenjtalk_g2p_prosody( lab_curr = labels[n] # current phoneme - p3 = re.search(r"\-(.*?)\+", lab_curr).group(1) # type: ignore + p3 = __PYOPENJTALK_G2P_PROSODY_P3_PATTERN.search(lab_curr).group(1) # type: ignore # deal unvoiced vowels as normal vowels if drop_unvoiced_vowels and p3 in "AEIOU": p3 = p3.lower() @@ -483,7 +491,9 @@ def __pyopenjtalk_g2p_prosody( phones.append("^") elif n == N - 1: # check question form or not - e3 = _numeric_feature_by_regex(r"!(\d+)_", lab_curr) + e3 = _numeric_feature_by_regex( + __PYOPENJTALK_G2P_PROSODY_E3_PATTERN, lab_curr + ) if e3 == 0: phones.append("$") elif e3 == 1: @@ -496,14 +506,16 @@ def __pyopenjtalk_g2p_prosody( phones.append(p3) # accent type and position info (forward or backward) - a1 = _numeric_feature_by_regex(r"/A:([0-9\-]+)\+", lab_curr) - a2 = _numeric_feature_by_regex(r"\+(\d+)\+", lab_curr) - a3 = _numeric_feature_by_regex(r"\+(\d+)/", lab_curr) + a1 = _numeric_feature_by_regex(__PYOPENJTALK_G2P_PROSODY_A1_PATTERN, lab_curr) + a2 = _numeric_feature_by_regex(__PYOPENJTALK_G2P_PROSODY_A2_PATTERN, lab_curr) + a3 = _numeric_feature_by_regex(__PYOPENJTALK_G2P_PROSODY_A3_PATTERN, lab_curr) # number of mora in accent phrase - f1 = _numeric_feature_by_regex(r"/F:(\d+)_", lab_curr) + f1 = _numeric_feature_by_regex(__PYOPENJTALK_G2P_PROSODY_F1_PATTERN, lab_curr) - a2_next = _numeric_feature_by_regex(r"\+(\d+)\+", labels[n + 1]) + a2_next = _numeric_feature_by_regex( + __PYOPENJTALK_G2P_PROSODY_A2_PATTERN, labels[n + 1] + ) # accent phrase border if a3 == 1 and a2_next == 1 and p3 in "aeiouAEIOUNcl": phones.append("#") @@ -560,9 +572,6 @@ def __handle_long(sep_phonemes: list[list[str]]) -> list[list[str]]: list[list[str]]: 長音記号を処理した音素のリストのリスト """ - # 母音の集合 (便宜上「ん」を含める) - VOWELS = {"a", "i", "u", "e", "o", "N"} - for i in range(len(sep_phonemes)): if len(sep_phonemes[i]) == 0: # 空白文字等でリストが空の場合 @@ -588,6 +597,15 @@ def __handle_long(sep_phonemes: list[list[str]]) -> list[list[str]]: return sep_phonemes +__KATAKANA_PATTERN = re.compile(r"[\u30A0-\u30FF]+") +__MORA_PATTERN = re.compile( + "|".join( + map(re.escape, sorted(MORA_KATA_TO_MORA_PHONEMES.keys(), key=len, reverse=True)) + ) +) +__LONG_PATTERN = re.compile(r"(\w)(ー*)") + + def __kata_to_phoneme_list(text: str) -> list[str]: """ 原則カタカナの `text` を受け取り、それをそのままいじらずに音素記号のリストに変換。 @@ -610,23 +628,20 @@ def __kata_to_phoneme_list(text: str) -> list[str]: if set(text).issubset(set(PUNCTUATIONS)): return list(text) # `text` がカタカナ(`ー`含む)のみからなるかどうかをチェック - if re.fullmatch(r"[\u30A0-\u30FF]+", text) is None: + if __KATAKANA_PATTERN.fullmatch(text) is None: raise ValueError(f"Input must be katakana only: {text}") - sorted_keys = sorted(MORA_KATA_TO_MORA_PHONEMES.keys(), key=len, reverse=True) - pattern = "|".join(map(re.escape, sorted_keys)) def mora2phonemes(mora: str) -> str: - cosonant, vowel = MORA_KATA_TO_MORA_PHONEMES[mora] - if cosonant is None: + consonant, vowel = MORA_KATA_TO_MORA_PHONEMES[mora] + if consonant is None: return f" {vowel}" - return f" {cosonant} {vowel}" + return f" {consonant} {vowel}" - spaced_phonemes = re.sub(pattern, lambda m: mora2phonemes(m.group()), text) + spaced_phonemes = __MORA_PATTERN.sub(lambda m: mora2phonemes(m.group()), text) # 長音記号「ー」の処理 - long_pattern = r"(\w)(ー*)" long_replacement = lambda m: m.group(1) + (" " + m.group(1)) * len(m.group(2)) # type: ignore - spaced_phonemes = re.sub(long_pattern, long_replacement, spaced_phonemes) + spaced_phonemes = __LONG_PATTERN.sub(long_replacement, spaced_phonemes) return spaced_phonemes.strip().split(" ") diff --git a/style_bert_vits2/nlp/japanese/g2p_utils.py b/style_bert_vits2/nlp/japanese/g2p_utils.py index 511793f..ce0b049 100644 --- a/style_bert_vits2/nlp/japanese/g2p_utils.py +++ b/style_bert_vits2/nlp/japanese/g2p_utils.py @@ -1,5 +1,6 @@ from style_bert_vits2.nlp.japanese.g2p import g2p from style_bert_vits2.nlp.japanese.mora_list import ( + CONSONANTS, MORA_KATA_TO_MORA_PHONEMES, MORA_PHONEMES_TO_MORA_KATA, ) @@ -33,15 +34,6 @@ def phone_tone2kata_tone(phone_tone: list[tuple[str, int]]) -> list[tuple[str, i カタカナと音高のリスト。 """ - # 子音の集合 - CONSONANTS = set( - [ - consonant - for consonant, _ in MORA_KATA_TO_MORA_PHONEMES.values() - if consonant is not None - ] - ) - phone_tone = phone_tone[1:] # 最初の("_", 0)を無視 phones = [phone for phone, _ in phone_tone] tones = [tone for _, tone in phone_tone] diff --git a/style_bert_vits2/nlp/japanese/mora_list.py b/style_bert_vits2/nlp/japanese/mora_list.py index a0dab2f..db69c34 100644 --- a/style_bert_vits2/nlp/japanese/mora_list.py +++ b/style_bert_vits2/nlp/japanese/mora_list.py @@ -234,3 +234,15 @@ MORA_KATA_TO_MORA_PHONEMES: dict[str, tuple[Optional[str], str]] = { kana: (consonant, vowel) for [kana, consonant, vowel] in __MORA_LIST_MINIMUM + __MORA_LIST_ADDITIONAL } + +# 子音の集合 +CONSONANTS = set( + [ + consonant + for consonant, _ in MORA_KATA_TO_MORA_PHONEMES.values() + if consonant is not None + ] +) + +# 母音の集合 (便宜上「ん」を含める) +VOWELS = {"a", "i", "u", "e", "o", "N"} diff --git a/style_bert_vits2/nlp/japanese/normalizer.py b/style_bert_vits2/nlp/japanese/normalizer.py index 5ceb2f8..edb394e 100644 --- a/style_bert_vits2/nlp/japanese/normalizer.py +++ b/style_bert_vits2/nlp/japanese/normalizer.py @@ -6,6 +6,81 @@ from num2words import num2words from style_bert_vits2.nlp.symbols import PUNCTUATIONS +# 記号類の正規化マップ +__REPLACE_MAP = { + ":": ",", + ";": ",", + ",": ",", + "。": ".", + "!": "!", + "?": "?", + "\n": ".", + ".": ".", + "…": "...", + "···": "...", + "・・・": "...", + "·": ",", + "・": ",", + "、": ",", + "$": ".", + "“": "'", + "”": "'", + '"': "'", + "‘": "'", + "’": "'", + "(": "'", + ")": "'", + "(": "'", + ")": "'", + "《": "'", + "》": "'", + "【": "'", + "】": "'", + "[": "'", + "]": "'", + # NFKC 正規化後のハイフン・ダッシュの変種を全て通常半角ハイフン - \u002d に変換 + "\u02d7": "\u002d", # ˗, Modifier Letter Minus Sign + "\u2010": "\u002d", # ‐, Hyphen, + # "\u2011": "\u002d", # ‑, Non-Breaking Hyphen, NFKC により \u2010 に変換される + "\u2012": "\u002d", # ‒, Figure Dash + "\u2013": "\u002d", # –, En Dash + "\u2014": "\u002d", # —, Em Dash + "\u2015": "\u002d", # ―, Horizontal Bar + "\u2043": "\u002d", # ⁃, Hyphen Bullet + "\u2212": "\u002d", # −, Minus Sign + "\u23af": "\u002d", # ⎯, Horizontal Line Extension + "\u23e4": "\u002d", # ⏤, Straightness + "\u2500": "\u002d", # ─, Box Drawings Light Horizontal + "\u2501": "\u002d", # ━, Box Drawings Heavy Horizontal + "\u2e3a": "\u002d", # ⸺, Two-Em Dash + "\u2e3b": "\u002d", # ⸻, Three-Em Dash + # "~": "-", # これは長音記号「ー」として扱うよう変更 + # "~": "-", # これも長音記号「ー」として扱うよう変更 + "「": "'", + "」": "'", +} +# 記号類の正規化パターン +__REPLACE_PATTERN = re.compile("|".join(re.escape(p) for p in __REPLACE_MAP.keys())) +# 句読点等の正規化パターン +__PUNCTUATION_CLEANUP_PATTERN = re.compile( + # ↓ ひらがな、カタカナ、漢字 + r"[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u3400-\u4DBF\u3005" + # ↓ 半角アルファベット(大文字と小文字) + + r"\u0041-\u005A\u0061-\u007A" + # ↓ 全角アルファベット(大文字と小文字) + + r"\uFF21-\uFF3A\uFF41-\uFF5A" + # ↓ ギリシャ文字 + + r"\u0370-\u03FF\u1F00-\u1FFF" + # ↓ "!", "?", "…", ",", ".", "'", "-", 但し`…`はすでに`...`に変換されている + + "".join(PUNCTUATIONS) + r"]+", # fmt: skip +) +# 数字・通貨記号の正規化パターン +__CURRENCY_MAP = {"$": "ドル", "¥": "円", "£": "ポンド", "€": "ユーロ"} +__CURRENCY_PATTERN = re.compile(r"([$¥£€])([0-9.]*[0-9])") +__NUMBER_PATTERN = re.compile(r"[0-9]+(\.[0-9]+)?") +__NUMBER_WITH_SEPARATOR_PATTERN = re.compile("[0-9]{1,3}(,[0-9]{3})+") + + def normalize_text(text: str) -> str: """ 日本語のテキストを正規化する。 @@ -62,80 +137,11 @@ def replace_punctuation(text: str) -> str: str: 正規化されたテキスト """ - # 記号類の正規化変換マップ - REPLACE_MAP = { - ":": ",", - ";": ",", - ",": ",", - "。": ".", - "!": "!", - "?": "?", - "\n": ".", - ".": ".", - "…": "...", - "···": "...", - "・・・": "...", - "·": ",", - "・": ",", - "、": ",", - "$": ".", - "“": "'", - "”": "'", - '"': "'", - "‘": "'", - "’": "'", - "(": "'", - ")": "'", - "(": "'", - ")": "'", - "《": "'", - "》": "'", - "【": "'", - "】": "'", - "[": "'", - "]": "'", - # NFKC 正規化後のハイフン・ダッシュの変種を全て通常半角ハイフン - \u002d に変換 - "\u02d7": "\u002d", # ˗, Modifier Letter Minus Sign - "\u2010": "\u002d", # ‐, Hyphen, - # "\u2011": "\u002d", # ‑, Non-Breaking Hyphen, NFKC により \u2010 に変換される - "\u2012": "\u002d", # ‒, Figure Dash - "\u2013": "\u002d", # –, En Dash - "\u2014": "\u002d", # —, Em Dash - "\u2015": "\u002d", # ―, Horizontal Bar - "\u2043": "\u002d", # ⁃, Hyphen Bullet - "\u2212": "\u002d", # −, Minus Sign - "\u23af": "\u002d", # ⎯, Horizontal Line Extension - "\u23e4": "\u002d", # ⏤, Straightness - "\u2500": "\u002d", # ─, Box Drawings Light Horizontal - "\u2501": "\u002d", # ━, Box Drawings Heavy Horizontal - "\u2e3a": "\u002d", # ⸺, Two-Em Dash - "\u2e3b": "\u002d", # ⸻, Three-Em Dash - # "~": "-", # これは長音記号「ー」として扱うよう変更 - # "~": "-", # これも長音記号「ー」として扱うよう変更 - "「": "'", - "」": "'", - } - - pattern = re.compile("|".join(re.escape(p) for p in REPLACE_MAP.keys())) - # 句読点を辞書で置換 - replaced_text = pattern.sub(lambda x: REPLACE_MAP[x.group()], text) + replaced_text = __REPLACE_PATTERN.sub(lambda x: __REPLACE_MAP[x.group()], text) - replaced_text = re.sub( - # ↓ ひらがな、カタカナ、漢字 - r"[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u3400-\u4DBF\u3005" - # ↓ 半角アルファベット(大文字と小文字) - + r"\u0041-\u005A\u0061-\u007A" - # ↓ 全角アルファベット(大文字と小文字) - + r"\uFF21-\uFF3A\uFF41-\uFF5A" - # ↓ ギリシャ文字 - + r"\u0370-\u03FF\u1F00-\u1FFF" - # ↓ "!", "?", "…", ",", ".", "'", "-", 但し`…`はすでに`...`に変換されている - + "".join(PUNCTUATIONS) + r"]+", - # 上述以外の文字を削除 - "", - replaced_text, - ) + # 上述以外の文字を削除 + replaced_text = __PUNCTUATION_CLEANUP_PATTERN.sub("", replaced_text) return replaced_text @@ -151,13 +157,8 @@ def __convert_numbers_to_words(text: str) -> str: str: 変換されたテキスト """ - NUMBER_WITH_SEPARATOR_PATTERN = re.compile("[0-9]{1,3}(,[0-9]{3})+") - CURRENCY_MAP = {"$": "ドル", "¥": "円", "£": "ポンド", "€": "ユーロ"} - CURRENCY_PATTERN = re.compile(r"([$¥£€])([0-9.]*[0-9])") - NUMBER_PATTERN = re.compile(r"[0-9]+(\.[0-9]+)?") - - res = NUMBER_WITH_SEPARATOR_PATTERN.sub(lambda m: m[0].replace(",", ""), text) - res = CURRENCY_PATTERN.sub(lambda m: m[2] + CURRENCY_MAP.get(m[1], m[1]), res) - res = NUMBER_PATTERN.sub(lambda m: num2words(m[0], lang="ja"), res) + res = __NUMBER_WITH_SEPARATOR_PATTERN.sub(lambda m: m[0].replace(",", ""), text) + res = __CURRENCY_PATTERN.sub(lambda m: m[2] + __CURRENCY_MAP.get(m[1], m[1]), res) + res = __NUMBER_PATTERN.sub(lambda m: num2words(m[0], lang="ja"), res) return res