Migrated content from Space: Plana-Archive/NSW-CHUPA
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- Mutsumi-Chan/NSW-CHUPA/Plana-Archive.PNG +3 -0
- Mutsumi-Chan/NSW-CHUPA/README.md +15 -0
- Mutsumi-Chan/NSW-CHUPA/app.py +1022 -0
- Mutsumi-Chan/NSW-CHUPA/chupa_examples.txt +0 -0
- Mutsumi-Chan/NSW-CHUPA/model_assets/chupa_1/chupa_1spk_e1000_s194312.safetensors +3 -0
- Mutsumi-Chan/NSW-CHUPA/model_assets/chupa_1/config.json +87 -0
- Mutsumi-Chan/NSW-CHUPA/model_assets/chupa_1/style_vectors.npy +3 -0
- Mutsumi-Chan/NSW-CHUPA/requirements.txt +47 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/.editorconfig +15 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/__init__.py +0 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/constants.py +48 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/logging.py +15 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/__init__.py +0 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/attentions.py +491 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/commons.py +223 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/hyper_parameters.py +129 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/infer.py +308 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/models.py +1102 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/models_jp_extra.py +1157 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/modules.py +642 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/monotonic_alignment.py +89 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/transforms.py +215 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/utils/__init__.py +264 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/utils/checkpoints.py +202 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/utils/safetensors.py +91 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/__init__.py +120 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/bert_models.py +210 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/__init__.py +0 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/bert_feature.py +125 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/g2p.py +139 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/normalizer.py +62 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/opencpop-strict.txt +429 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/tone_sandhi.py +771 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/__init__.py +0 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/bert_feature.py +66 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/cmudict.py +46 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/cmudict.rep +0 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/cmudict_cache.pickle +3 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/g2p.py +230 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/normalizer.py +132 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/__init__.py +0 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/bert_feature.py +73 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/g2p.py +721 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/g2p_utils.py +84 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/mora_list.py +248 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/normalizer.py +164 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/pyopenjtalk_worker/__init__.py +160 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/pyopenjtalk_worker/__main__.py +16 -0
- Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/pyopenjtalk_worker/worker_client.py +60 -0
.gitattributes
CHANGED
|
@@ -174,3 +174,4 @@ Mutsumi-Chan/VITS-Umamusume-Voice/haru-urara-concert.gif filter=lfs diff=lfs mer
|
|
| 174 |
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/lib.win-amd64-cpython-37/monotonic_align/core.cp37-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
| 175 |
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/temp.win-amd64-cpython-37/Release/core.obj filter=lfs diff=lfs merge=lfs -text
|
| 176 |
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/monotonic_align/core.cp37-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 174 |
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/lib.win-amd64-cpython-37/monotonic_align/core.cp37-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
| 175 |
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/temp.win-amd64-cpython-37/Release/core.obj filter=lfs diff=lfs merge=lfs -text
|
| 176 |
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/monotonic_align/core.cp37-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
| 177 |
+
Mutsumi-Chan/NSW-CHUPA/Plana-Archive.PNG filter=lfs diff=lfs merge=lfs -text
|
Mutsumi-Chan/NSW-CHUPA/Plana-Archive.PNG
ADDED
|
|
Git LFS Details
|
Mutsumi-Chan/NSW-CHUPA/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: NSW - Chupa Anime Ecchi
|
| 3 |
+
emoji: 👅
|
| 4 |
+
colorFrom: pink
|
| 5 |
+
colorTo: pink
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
python_version: '3.10'
|
| 11 |
+
short_description: Generate Voice Hent4i
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# SBV2 Chupa Demo Space
|
| 15 |
+
Aplikasi ini berjalan menggunakan Python 3.10 dan Gradio 4.44.1 untuk stabilitas model Bert-VITS2.
|
Mutsumi-Chan/NSW-CHUPA/app.py
ADDED
|
@@ -0,0 +1,1022 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import datetime
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import random
|
| 6 |
+
import time
|
| 7 |
+
import torch
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from huggingface_hub import snapshot_download, login
|
| 10 |
+
|
| 11 |
+
# --- BAGIAN 1: LOGIKA MODEL ---
|
| 12 |
+
from style_bert_vits2.constants import (
|
| 13 |
+
DEFAULT_LENGTH, DEFAULT_LINE_SPLIT, DEFAULT_NOISE,
|
| 14 |
+
DEFAULT_NOISEW, DEFAULT_SPLIT_INTERVAL, Languages
|
| 15 |
+
)
|
| 16 |
+
from style_bert_vits2.logging import logger
|
| 17 |
+
from style_bert_vits2.tts_model import TTSModelHolder
|
| 18 |
+
from style_bert_vits2.nlp import bert_models
|
| 19 |
+
|
| 20 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 21 |
+
|
| 22 |
+
# Login dengan token Hugging Face
|
| 23 |
+
def hf_login():
|
| 24 |
+
"""Login ke Hugging Face Hub dengan token"""
|
| 25 |
+
token = os.environ.get("HF_TOKEN")
|
| 26 |
+
if token:
|
| 27 |
+
try:
|
| 28 |
+
login(token=token, add_to_git_credential=True)
|
| 29 |
+
logger.info("✅ Berhasil login ke Hugging Face Hub dengan token")
|
| 30 |
+
return True
|
| 31 |
+
except Exception as e:
|
| 32 |
+
logger.warning(f"⚠️ Gagal login dengan token: {e}")
|
| 33 |
+
return False
|
| 34 |
+
else:
|
| 35 |
+
logger.warning("⚠️ HF_TOKEN tidak ditemukan, mencoba akses tanpa token")
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
# Login saat aplikasi dimulai
|
| 39 |
+
hf_login()
|
| 40 |
+
|
| 41 |
+
def setup_bert_structure():
|
| 42 |
+
"""Setup struktur folder BERT sesuai yang diharapkan style_bert_vits2"""
|
| 43 |
+
try:
|
| 44 |
+
# Path yang diharapkan oleh style_bert_vits2 untuk model JP
|
| 45 |
+
bert_jp_path = Path("./bert/bert-base-japanese-v3")
|
| 46 |
+
|
| 47 |
+
# Cek apakah sudah ada struktur yang benar
|
| 48 |
+
required_files = ["config.json", "pytorch_model.bin", "vocab.txt"]
|
| 49 |
+
has_all_files = all((bert_jp_path / file).exists() for file in required_files)
|
| 50 |
+
|
| 51 |
+
if has_all_files:
|
| 52 |
+
logger.info(f"✅ Model BERT JP sudah ada di {bert_jp_path}")
|
| 53 |
+
return True
|
| 54 |
+
|
| 55 |
+
logger.info("📥 Mengunduh atau mengatur ulang struktur BERT...")
|
| 56 |
+
|
| 57 |
+
# Coba unduh dari repo premium
|
| 58 |
+
REPO_ID = "Plana-Archive/Premium-Model"
|
| 59 |
+
SOURCE_SUBFOLDER = "SBV2-Chupa-Demo/bert"
|
| 60 |
+
|
| 61 |
+
token = os.environ.get("HF_TOKEN")
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
if token:
|
| 65 |
+
temp_dir = snapshot_download(
|
| 66 |
+
repo_id=REPO_ID,
|
| 67 |
+
allow_patterns=[f"{SOURCE_SUBFOLDER}/**/*"],
|
| 68 |
+
token=token,
|
| 69 |
+
local_dir_use_symlinks=False
|
| 70 |
+
)
|
| 71 |
+
logger.info("✅ BERT assets berhasil diunduh dari repo premium")
|
| 72 |
+
else:
|
| 73 |
+
temp_dir = snapshot_download(
|
| 74 |
+
repo_id=REPO_ID,
|
| 75 |
+
allow_patterns=[f"{SOURCE_SUBFOLDER}/**/*"],
|
| 76 |
+
local_dir_use_symlinks=False
|
| 77 |
+
)
|
| 78 |
+
logger.info("✅ BERT assets berhasil diunduh tanpa token")
|
| 79 |
+
|
| 80 |
+
# Cari file BERT dalam struktur yang diunduh
|
| 81 |
+
src_path = Path(temp_dir) / SOURCE_SUBFOLDER
|
| 82 |
+
|
| 83 |
+
# Jika tidak ditemukan, coba cari di lokasi lain
|
| 84 |
+
if not src_path.exists():
|
| 85 |
+
# Coba cari folder bert di berbagai lokasi
|
| 86 |
+
possible_locations = [
|
| 87 |
+
Path(temp_dir) / "bert",
|
| 88 |
+
Path(temp_dir) / "BERT",
|
| 89 |
+
Path(temp_dir) / "SBV2-Chupa-Demo/bert",
|
| 90 |
+
Path(temp_dir) / "sbv2-chupa-demo/bert",
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
for loc in possible_locations:
|
| 94 |
+
if loc.exists():
|
| 95 |
+
src_path = loc
|
| 96 |
+
break
|
| 97 |
+
|
| 98 |
+
if src_path.exists():
|
| 99 |
+
# Pastikan folder bert ada
|
| 100 |
+
bert_dir = Path("./bert")
|
| 101 |
+
bert_dir.mkdir(exist_ok=True)
|
| 102 |
+
|
| 103 |
+
# Salin semua isi folder bert
|
| 104 |
+
for item in src_path.rglob("*"):
|
| 105 |
+
if item.is_file():
|
| 106 |
+
rel_path = item.relative_to(src_path)
|
| 107 |
+
dest_path = bert_dir / rel_path
|
| 108 |
+
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
| 109 |
+
shutil.copy2(item, dest_path)
|
| 110 |
+
|
| 111 |
+
logger.info(f"✅ BERT assets disalin ke ./bert")
|
| 112 |
+
|
| 113 |
+
# Verifikasi struktur
|
| 114 |
+
if bert_jp_path.exists():
|
| 115 |
+
logger.info(f"✅ Struktur BERT JP valid: {bert_jp_path}")
|
| 116 |
+
return True
|
| 117 |
+
else:
|
| 118 |
+
# Coba buat struktur yang diharapkan
|
| 119 |
+
logger.info("🔄 Membuat struktur BERT JP yang diharapkan...")
|
| 120 |
+
|
| 121 |
+
# Cari model BERT dalam folder bert
|
| 122 |
+
bert_base_dir = None
|
| 123 |
+
for subdir in bert_dir.iterdir():
|
| 124 |
+
if subdir.is_dir() and "japanese" in subdir.name.lower():
|
| 125 |
+
bert_base_dir = subdir
|
| 126 |
+
break
|
| 127 |
+
|
| 128 |
+
if bert_base_dir and bert_base_dir.exists():
|
| 129 |
+
# Salin ke lokasi yang diharapkan
|
| 130 |
+
bert_jp_path.mkdir(parents=True, exist_ok=True)
|
| 131 |
+
for item in bert_base_dir.iterdir():
|
| 132 |
+
if item.is_file():
|
| 133 |
+
shutil.copy2(item, bert_jp_path / item.name)
|
| 134 |
+
logger.info(f"✅ Model BERT JP disalin ke {bert_jp_path}")
|
| 135 |
+
return True
|
| 136 |
+
|
| 137 |
+
except Exception as e:
|
| 138 |
+
logger.warning(f"⚠️ Gagal mengunduh BERT dari repo premium: {e}")
|
| 139 |
+
|
| 140 |
+
# Fallback: Unduh model BERT dasar dari Hugging Face
|
| 141 |
+
logger.info("🔄 Mencoba mengunduh model BERT dasar...")
|
| 142 |
+
try:
|
| 143 |
+
# Download bert-base-japanese-v3 dari huggingface
|
| 144 |
+
from transformers import AutoTokenizer, AutoModel
|
| 145 |
+
import huggingface_hub
|
| 146 |
+
|
| 147 |
+
token = os.environ.get("HF_TOKEN")
|
| 148 |
+
|
| 149 |
+
# Download tokenizer dan model
|
| 150 |
+
logger.info("📥 Mengunduh tokenizer BERT JP...")
|
| 151 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 152 |
+
"cl-tohoku/bert-base-japanese-v3",
|
| 153 |
+
use_auth_token=token if token else None
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
logger.info("📥 Mengunduh model BERT JP...")
|
| 157 |
+
model = AutoModel.from_pretrained(
|
| 158 |
+
"cl-tohoku/bert-base-japanese-v3",
|
| 159 |
+
use_auth_token=token if token else None
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Simpan ke disk
|
| 163 |
+
bert_jp_path.mkdir(parents=True, exist_ok=True)
|
| 164 |
+
tokenizer.save_pretrained(str(bert_jp_path))
|
| 165 |
+
model.save_pretrained(str(bert_jp_path))
|
| 166 |
+
|
| 167 |
+
logger.info(f"✅ Model BERT dasar berhasil diunduh ke {bert_jp_path}")
|
| 168 |
+
return True
|
| 169 |
+
|
| 170 |
+
except Exception as e:
|
| 171 |
+
logger.error(f"❌ Gagal mengunduh model BERT dasar: {e}")
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
except Exception as e:
|
| 175 |
+
logger.error(f"❌ Error dalam setup BERT: {e}")
|
| 176 |
+
return False
|
| 177 |
+
|
| 178 |
+
def download_model_assets():
|
| 179 |
+
"""Download model TTS assets dari repo privat"""
|
| 180 |
+
REPO_ID = "Plana-Archive/Premium-Model"
|
| 181 |
+
SOURCE_SUBFOLDER = "SBV2-Chupa-Demo/model_assets"
|
| 182 |
+
DEST_FOLDER = Path("./model_assets")
|
| 183 |
+
|
| 184 |
+
# Cek apakah sudah ada
|
| 185 |
+
if DEST_FOLDER.exists():
|
| 186 |
+
model_files = list(DEST_FOLDER.glob("*.pth")) + list(DEST_FOLDER.glob("*.json"))
|
| 187 |
+
if model_files:
|
| 188 |
+
logger.info(f"✅ Model assets sudah ada di {DEST_FOLDER}")
|
| 189 |
+
return True
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
logger.info(f"📥 Mengunduh model assets dari {REPO_ID}/{SOURCE_SUBFOLDER}")
|
| 193 |
+
|
| 194 |
+
token = os.environ.get("HF_TOKEN")
|
| 195 |
+
|
| 196 |
+
if token:
|
| 197 |
+
temp_dir = snapshot_download(
|
| 198 |
+
repo_id=REPO_ID,
|
| 199 |
+
allow_patterns=[f"{SOURCE_SUBFOLDER}/**/*"],
|
| 200 |
+
token=token,
|
| 201 |
+
local_dir_use_symlinks=False
|
| 202 |
+
)
|
| 203 |
+
else:
|
| 204 |
+
temp_dir = snapshot_download(
|
| 205 |
+
repo_id=REPO_ID,
|
| 206 |
+
allow_patterns=[f"{SOURCE_SUBFOLDER}/**/*"],
|
| 207 |
+
local_dir_use_symlinks=False
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Temukan dan salin model assets
|
| 211 |
+
src_path = Path(temp_dir) / SOURCE_SUBFOLDER
|
| 212 |
+
|
| 213 |
+
if not src_path.exists():
|
| 214 |
+
# Coba cari di lokasi lain
|
| 215 |
+
possible_locations = [
|
| 216 |
+
Path(temp_dir) / "model_assets",
|
| 217 |
+
Path(temp_dir) / "SBV2-Chupa-Demo",
|
| 218 |
+
Path(temp_dir) / "sbv2-chupa-demo",
|
| 219 |
+
]
|
| 220 |
+
|
| 221 |
+
for loc in possible_locations:
|
| 222 |
+
if loc.exists():
|
| 223 |
+
# Cari file .pth dan .json
|
| 224 |
+
model_files = list(loc.rglob("*.pth")) + list(loc.rglob("*.json"))
|
| 225 |
+
if model_files:
|
| 226 |
+
DEST_FOLDER.mkdir(exist_ok=True)
|
| 227 |
+
for file in model_files:
|
| 228 |
+
shutil.copy2(file, DEST_FOLDER / file.name)
|
| 229 |
+
logger.info(f"✅ Model files disalin ke {DEST_FOLDER}")
|
| 230 |
+
return True
|
| 231 |
+
|
| 232 |
+
if src_path.exists():
|
| 233 |
+
DEST_FOLDER.mkdir(exist_ok=True)
|
| 234 |
+
for item in src_path.iterdir():
|
| 235 |
+
if item.is_file():
|
| 236 |
+
shutil.copy2(item, DEST_FOLDER / item.name)
|
| 237 |
+
logger.info(f"✅ Model assets disalin ke {DEST_FOLDER}")
|
| 238 |
+
return True
|
| 239 |
+
|
| 240 |
+
except Exception as e:
|
| 241 |
+
logger.error(f"❌ Gagal mengunduh model assets: {e}")
|
| 242 |
+
# Buat folder kosong
|
| 243 |
+
DEST_FOLDER.mkdir(exist_ok=True)
|
| 244 |
+
return False
|
| 245 |
+
|
| 246 |
+
# Setup semua assets
|
| 247 |
+
try:
|
| 248 |
+
if setup_bert_structure():
|
| 249 |
+
logger.info("✅ Setup BERT berhasil")
|
| 250 |
+
else:
|
| 251 |
+
logger.error("❌ Setup BERT gagal")
|
| 252 |
+
|
| 253 |
+
if download_model_assets():
|
| 254 |
+
logger.info("✅ Download model assets berhasil")
|
| 255 |
+
else:
|
| 256 |
+
logger.warning("⚠️ Download model assets gagal, menggunakan folder kosong")
|
| 257 |
+
|
| 258 |
+
except Exception as e:
|
| 259 |
+
logger.error(f"❌ Error saat setup assets: {e}")
|
| 260 |
+
|
| 261 |
+
# --- BAGIAN 2: CSS CUSTOM (ESTETIK & CLEAN) ---
|
| 262 |
+
css = """
|
| 263 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Quicksand:wght@400;600;700&display=swap');
|
| 264 |
+
body, .gradio-container {
|
| 265 |
+
background-color: #ffffff !important;
|
| 266 |
+
font-family: 'Inter', sans-serif !important;
|
| 267 |
+
max-width: 1200px !important;
|
| 268 |
+
margin: 0 auto !important;
|
| 269 |
+
}
|
| 270 |
+
footer { display: none !important; }
|
| 271 |
+
|
| 272 |
+
/* Verifikasi CSS */
|
| 273 |
+
.age-verification-overlay {
|
| 274 |
+
position: fixed;
|
| 275 |
+
top: 0;
|
| 276 |
+
left: 0;
|
| 277 |
+
width: 100%;
|
| 278 |
+
height: 100%;
|
| 279 |
+
background: linear-gradient(135deg, #fff5f9 0%, #ffeaf3 100%);
|
| 280 |
+
z-index: 9999;
|
| 281 |
+
display: flex;
|
| 282 |
+
justify-content: center;
|
| 283 |
+
align-items: center;
|
| 284 |
+
animation: fadeIn 0.3s ease;
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
.age-verification-box {
|
| 288 |
+
background: white;
|
| 289 |
+
border-radius: 20px;
|
| 290 |
+
padding: 25px 30px;
|
| 291 |
+
max-width: 420px;
|
| 292 |
+
width: 90%;
|
| 293 |
+
text-align: center;
|
| 294 |
+
box-shadow: 0 15px 40px rgba(255, 105, 180, 0.2);
|
| 295 |
+
border: 2px solid #ffe4ec;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
.verification-image {
|
| 299 |
+
width: 80px;
|
| 300 |
+
height: 80px;
|
| 301 |
+
border-radius: 50%;
|
| 302 |
+
object-fit: cover;
|
| 303 |
+
border: 3px solid #ffe4ec;
|
| 304 |
+
margin: 0 auto 15px;
|
| 305 |
+
display: block;
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
.age-verification-title {
|
| 309 |
+
font-family: 'Quicksand', sans-serif;
|
| 310 |
+
font-weight: 800;
|
| 311 |
+
font-size: 22px;
|
| 312 |
+
color: #ff69b4;
|
| 313 |
+
margin-bottom: 15px;
|
| 314 |
+
display: flex;
|
| 315 |
+
align-items: center;
|
| 316 |
+
justify-content: center;
|
| 317 |
+
gap: 10px;
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
.verification-message {
|
| 321 |
+
font-size: 14px;
|
| 322 |
+
line-height: 1.5;
|
| 323 |
+
color: #7b4d5a;
|
| 324 |
+
margin: 15px 0;
|
| 325 |
+
padding: 12px;
|
| 326 |
+
background: #fffafc;
|
| 327 |
+
border-radius: 10px;
|
| 328 |
+
border: 1px solid #ffe4ec;
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
.age-verification-buttons {
|
| 332 |
+
display: flex;
|
| 333 |
+
gap: 12px;
|
| 334 |
+
margin-top: 20px;
|
| 335 |
+
justify-content: center;
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
.age-btn {
|
| 339 |
+
padding: 10px 25px !important;
|
| 340 |
+
border-radius: 8px !important;
|
| 341 |
+
font-weight: 700 !important;
|
| 342 |
+
font-size: 14px !important;
|
| 343 |
+
transition: all 0.2s ease !important;
|
| 344 |
+
border: 2px solid transparent !important;
|
| 345 |
+
min-width: 110px;
|
| 346 |
+
flex: 1;
|
| 347 |
+
height: 40px !important;
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
.age-btn-yes {
|
| 351 |
+
background: linear-gradient(135deg, #ff69b4 0%, #ff1493 100%) !important;
|
| 352 |
+
color: white !important;
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
.age-btn-yes:hover:not(:disabled) {
|
| 356 |
+
transform: translateY(-2px);
|
| 357 |
+
box-shadow: 0 6px 12px rgba(255, 105, 180, 0.3) !important;
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
.age-btn-no {
|
| 361 |
+
background: white !important;
|
| 362 |
+
color: #ff69b4 !important;
|
| 363 |
+
border-color: #ffe4ec !important;
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
.age-btn-no:hover:not(:disabled) {
|
| 367 |
+
background: #fff5f9 !important;
|
| 368 |
+
border-color: #ff69b4 !important;
|
| 369 |
+
transform: translateY(-2px);
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
.age-btn:disabled {
|
| 373 |
+
opacity: 0.7;
|
| 374 |
+
cursor: not-allowed !important;
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
.loading-spinner {
|
| 378 |
+
display: inline-block;
|
| 379 |
+
width: 16px;
|
| 380 |
+
height: 16px;
|
| 381 |
+
border: 2px solid #ffffff;
|
| 382 |
+
border-radius: 50%;
|
| 383 |
+
border-top-color: transparent;
|
| 384 |
+
animation: spin 0.8s linear infinite;
|
| 385 |
+
margin-right: 8px;
|
| 386 |
+
vertical-align: middle;
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
.loading-spinner-no {
|
| 390 |
+
display: inline-block;
|
| 391 |
+
width: 16px;
|
| 392 |
+
height: 16px;
|
| 393 |
+
border: 2px solid #ff69b4;
|
| 394 |
+
border-radius: 50%;
|
| 395 |
+
border-top-color: transparent;
|
| 396 |
+
animation: spin 0.8s linear infinite;
|
| 397 |
+
margin-right: 8px;
|
| 398 |
+
vertical-align: middle;
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
@keyframes spin {
|
| 402 |
+
0% { transform: rotate(0deg); }
|
| 403 |
+
100% { transform: rotate(360deg); }
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
@keyframes fadeIn {
|
| 407 |
+
from { opacity: 0; }
|
| 408 |
+
to { opacity: 1; }
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
/* Loading Screen */
|
| 412 |
+
.loading-screen {
|
| 413 |
+
position: fixed;
|
| 414 |
+
top: 0;
|
| 415 |
+
left: 0;
|
| 416 |
+
width: 100%;
|
| 417 |
+
height: 100%;
|
| 418 |
+
background: white;
|
| 419 |
+
z-index: 10000;
|
| 420 |
+
display: flex;
|
| 421 |
+
justify-content: center;
|
| 422 |
+
align-items: center;
|
| 423 |
+
flex-direction: column;
|
| 424 |
+
animation: fadeIn 0.3s ease;
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
.loading-content {
|
| 428 |
+
text-align: center;
|
| 429 |
+
padding: 40px;
|
| 430 |
+
border-radius: 20px;
|
| 431 |
+
background: white;
|
| 432 |
+
box-shadow: 0 10px 30px rgba(255, 105, 180, 0.1);
|
| 433 |
+
border: 2px solid #ffe4ec;
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
.loading-logo {
|
| 437 |
+
width: 60px;
|
| 438 |
+
height: 60px;
|
| 439 |
+
border-radius: 50%;
|
| 440 |
+
object-fit: cover;
|
| 441 |
+
border: 2px solid #ffe4ec;
|
| 442 |
+
margin-bottom: 20px;
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
.loading-title {
|
| 446 |
+
font-family: 'Quicksand', sans-serif;
|
| 447 |
+
font-weight: 700;
|
| 448 |
+
font-size: 18px;
|
| 449 |
+
color: #ff69b4;
|
| 450 |
+
margin-bottom: 15px;
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
.loading-message {
|
| 454 |
+
font-size: 14px;
|
| 455 |
+
color: #7b4d5a;
|
| 456 |
+
margin-bottom: 20px;
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
.loading-large-spinner {
|
| 460 |
+
display: inline-block;
|
| 461 |
+
width: 40px;
|
| 462 |
+
height: 40px;
|
| 463 |
+
border: 3px solid #ffe4ec;
|
| 464 |
+
border-radius: 50%;
|
| 465 |
+
border-top-color: #ff69b4;
|
| 466 |
+
animation: spin 1s linear infinite;
|
| 467 |
+
margin-top: 10px;
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
/* Loading Screen untuk Tidak */
|
| 471 |
+
.loading-screen-no {
|
| 472 |
+
position: fixed;
|
| 473 |
+
top: 0;
|
| 474 |
+
left: 0;
|
| 475 |
+
width: 100%;
|
| 476 |
+
height: 100%;
|
| 477 |
+
background: linear-gradient(135deg, #fff5f9 0%, #ffeaf3 100%);
|
| 478 |
+
z-index: 10000;
|
| 479 |
+
display: flex;
|
| 480 |
+
justify-content: center;
|
| 481 |
+
align-items: center;
|
| 482 |
+
flex-direction: column;
|
| 483 |
+
animation: fadeIn 0.3s ease;
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
.loading-content-no {
|
| 487 |
+
text-align: center;
|
| 488 |
+
padding: 40px;
|
| 489 |
+
border-radius: 20px;
|
| 490 |
+
background: white;
|
| 491 |
+
box-shadow: 0 10px 30px rgba(255, 105, 180, 0.2);
|
| 492 |
+
border: 2px solid #ff69b4;
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
.loading-title-no {
|
| 496 |
+
font-family: 'Quicksand', sans-serif;
|
| 497 |
+
font-weight: 700;
|
| 498 |
+
font-size: 18px;
|
| 499 |
+
color: #ff1493;
|
| 500 |
+
margin-bottom: 15px;
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
.loading-message-no {
|
| 504 |
+
font-size: 14px;
|
| 505 |
+
color: #7b4d5a;
|
| 506 |
+
margin-bottom: 20px;
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
.loading-large-spinner-no {
|
| 510 |
+
display: inline-block;
|
| 511 |
+
width: 40px;
|
| 512 |
+
height: 40px;
|
| 513 |
+
border: 3px solid #ff69b4;
|
| 514 |
+
border-radius: 50%;
|
| 515 |
+
border-top-color: #ff1493;
|
| 516 |
+
animation: spin 1s linear infinite;
|
| 517 |
+
margin-top: 10px;
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
/* Main Content Layout */
|
| 521 |
+
.main-container {
|
| 522 |
+
display: flex;
|
| 523 |
+
flex-direction: column;
|
| 524 |
+
gap: 15px;
|
| 525 |
+
width: 100%;
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
.header-img-container {
|
| 529 |
+
text-align: center;
|
| 530 |
+
padding: 10px 0;
|
| 531 |
+
}
|
| 532 |
+
.header-img {
|
| 533 |
+
width: 100%;
|
| 534 |
+
max-width: 500px;
|
| 535 |
+
border-radius: 15px;
|
| 536 |
+
margin: 0 auto;
|
| 537 |
+
display: block;
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
.status-card {
|
| 541 |
+
background: #ffffff;
|
| 542 |
+
border: 2px solid #ffe4ec;
|
| 543 |
+
border-radius: 14px;
|
| 544 |
+
padding: 15px 10px;
|
| 545 |
+
margin: 0 auto 20px auto;
|
| 546 |
+
max-width: 400px;
|
| 547 |
+
display: flex;
|
| 548 |
+
flex-direction: column;
|
| 549 |
+
align-items: center;
|
| 550 |
+
box-shadow: 0 4px 15px rgba(255, 105, 180, 0.1);
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
.content-row {
|
| 554 |
+
display: flex;
|
| 555 |
+
flex-direction: row;
|
| 556 |
+
gap: 20px;
|
| 557 |
+
width: 100%;
|
| 558 |
+
align-items: flex-start;
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
.sidebar-column {
|
| 562 |
+
flex: 1;
|
| 563 |
+
border-right: 3px solid #ff69b4 !important;
|
| 564 |
+
padding-right: 20px !important;
|
| 565 |
+
min-width: 300px;
|
| 566 |
+
}
|
| 567 |
+
|
| 568 |
+
.main-column {
|
| 569 |
+
flex: 2;
|
| 570 |
+
min-width: 500px;
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
.pink-accordion {
|
| 574 |
+
border: 1px solid #ffe4ec !important;
|
| 575 |
+
border-radius: 10px !important;
|
| 576 |
+
overflow: hidden;
|
| 577 |
+
margin-top: 10px;
|
| 578 |
+
}
|
| 579 |
+
.pink-accordion .label-wrap {
|
| 580 |
+
background: linear-gradient(135deg, #ff69b4 0%, #ff1493 100%) !important;
|
| 581 |
+
padding: 10px !important;
|
| 582 |
+
}
|
| 583 |
+
.pink-accordion .label-wrap span {
|
| 584 |
+
color: white !important;
|
| 585 |
+
font-weight: 700 !important;
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
.generate-btn {
|
| 589 |
+
background: linear-gradient(135deg, #ff69b4 0%, #ff1493 100%) !important;
|
| 590 |
+
color: white !important;
|
| 591 |
+
border-radius: 10px !important;
|
| 592 |
+
font-weight: 700 !important;
|
| 593 |
+
height: 45px !important;
|
| 594 |
+
font-size: 1em !important;
|
| 595 |
+
margin-top: 15px;
|
| 596 |
+
border: none !important;
|
| 597 |
+
width: 100% !important;
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
.output-audio-box {
|
| 601 |
+
border: none !important;
|
| 602 |
+
box-shadow: none !important;
|
| 603 |
+
background: transparent !important;
|
| 604 |
+
padding: 1px 1px 8px 1px !important;
|
| 605 |
+
}
|
| 606 |
+
.output-audio-box > div {
|
| 607 |
+
border: 1px solid #ffe4ec !important;
|
| 608 |
+
border-bottom: 1px solid #ffe4ec !important;
|
| 609 |
+
border-radius: 10px !important;
|
| 610 |
+
background: #ffffff !important;
|
| 611 |
+
overflow: hidden !important;
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
/* --- CHATBOT SIMULATION CSS --- */
|
| 615 |
+
.chat-container {
|
| 616 |
+
background: #ffffff;
|
| 617 |
+
border: 2px solid #ffe4ec;
|
| 618 |
+
border-radius: 15px;
|
| 619 |
+
padding: 20px;
|
| 620 |
+
margin-top: 20px;
|
| 621 |
+
box-shadow: 0 5px 15px rgba(255, 105, 180, 0.05);
|
| 622 |
+
}
|
| 623 |
+
.chat-header {
|
| 624 |
+
display: flex;
|
| 625 |
+
justify-content: space-between;
|
| 626 |
+
align-items: center;
|
| 627 |
+
border-bottom: 2px solid #fff0f7;
|
| 628 |
+
padding-bottom: 10px;
|
| 629 |
+
margin-bottom: 15px;
|
| 630 |
+
}
|
| 631 |
+
.chat-title {
|
| 632 |
+
color: #ff69b4;
|
| 633 |
+
font-weight: 800;
|
| 634 |
+
font-size: 15px;
|
| 635 |
+
}
|
| 636 |
+
.chat-status {
|
| 637 |
+
background: #e6fffa;
|
| 638 |
+
color: #38b2ac;
|
| 639 |
+
padding: 2px 10px;
|
| 640 |
+
border-radius: 20px;
|
| 641 |
+
font-size: 10px;
|
| 642 |
+
font-weight: 700;
|
| 643 |
+
letter-spacing: 1px;
|
| 644 |
+
}
|
| 645 |
+
.chat-bubble-bot {
|
| 646 |
+
background: #fff5f8;
|
| 647 |
+
border: 1px solid #ffe4ec;
|
| 648 |
+
padding: 12px;
|
| 649 |
+
border-radius: 15px 15px 15px 0px;
|
| 650 |
+
color: #7b4d5a;
|
| 651 |
+
font-size: 13px;
|
| 652 |
+
line-height: 1.6;
|
| 653 |
+
}
|
| 654 |
+
.chat-button-group {
|
| 655 |
+
display: flex;
|
| 656 |
+
flex-direction: column;
|
| 657 |
+
gap: 6px;
|
| 658 |
+
margin-top: 15px;
|
| 659 |
+
}
|
| 660 |
+
.chat-btn-opt {
|
| 661 |
+
background: white !important;
|
| 662 |
+
border: 1px solid #ffe4ec !important;
|
| 663 |
+
color: #7b4d5a !important;
|
| 664 |
+
text-align: left !important;
|
| 665 |
+
font-size: 12px !important;
|
| 666 |
+
padding: 8px 12px !important;
|
| 667 |
+
min-height: unset !important;
|
| 668 |
+
border-radius: 8px !important;
|
| 669 |
+
}
|
| 670 |
+
.chat-btn-opt:hover {
|
| 671 |
+
border-color: #ff69b4 !important;
|
| 672 |
+
color: #ff69b4 !important;
|
| 673 |
+
background: #fffafc !important;
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
.note-box {
|
| 677 |
+
background: #fffafa;
|
| 678 |
+
padding: 20px;
|
| 679 |
+
border-radius: 12px;
|
| 680 |
+
margin-top: 25px;
|
| 681 |
+
border: 1px solid #ffe4ec;
|
| 682 |
+
}
|
| 683 |
+
.note-title {
|
| 684 |
+
color: #ff69b4;
|
| 685 |
+
font-weight: 800;
|
| 686 |
+
font-size: 14px;
|
| 687 |
+
margin-bottom: 12px;
|
| 688 |
+
display: flex;
|
| 689 |
+
align-items: center;
|
| 690 |
+
gap: 8px;
|
| 691 |
+
text-transform: uppercase;
|
| 692 |
+
letter-spacing: 1px;
|
| 693 |
+
}
|
| 694 |
+
.note-content {
|
| 695 |
+
color: #7b4d5a;
|
| 696 |
+
font-size: 13px;
|
| 697 |
+
line-height: 1.6;
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
.footer-container {
|
| 701 |
+
text-align: center;
|
| 702 |
+
margin-top: 30px;
|
| 703 |
+
padding: 25px;
|
| 704 |
+
border-top: 2px solid #ffe4ec;
|
| 705 |
+
background: #fffafc;
|
| 706 |
+
}
|
| 707 |
+
.dot-online {
|
| 708 |
+
height: 8px;
|
| 709 |
+
width: 8px;
|
| 710 |
+
background-color: #ff69b4;
|
| 711 |
+
border-radius: 50%;
|
| 712 |
+
display: inline-block;
|
| 713 |
+
animation: blink 1.5s infinite;
|
| 714 |
+
}
|
| 715 |
+
@keyframes blink {
|
| 716 |
+
0% { opacity: 1; }
|
| 717 |
+
50% { opacity: 0.4; }
|
| 718 |
+
100% { opacity: 1; }
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
/* Responsive */
|
| 722 |
+
@media (max-width: 900px) {
|
| 723 |
+
.content-row {
|
| 724 |
+
flex-direction: column;
|
| 725 |
+
}
|
| 726 |
+
.sidebar-column {
|
| 727 |
+
border-right: none !important;
|
| 728 |
+
border-bottom: 3px solid #ff69b4 !important;
|
| 729 |
+
padding-right: 0 !important;
|
| 730 |
+
padding-bottom: 20px !important;
|
| 731 |
+
min-width: 100%;
|
| 732 |
+
}
|
| 733 |
+
.main-column {
|
| 734 |
+
min-width: 100%;
|
| 735 |
+
}
|
| 736 |
+
.age-btn {
|
| 737 |
+
padding: 8px 20px !important;
|
| 738 |
+
min-width: 100px;
|
| 739 |
+
}
|
| 740 |
+
}
|
| 741 |
+
"""
|
| 742 |
+
|
| 743 |
+
def get_random_text():
|
| 744 |
+
return random.choice([
|
| 745 |
+
"ちゅぱ、ちゅるる、ぢゅ、んく、れーれゅれろれろれろ、じゅぽぽぽぽぽ……ちゅううう!",
|
| 746 |
+
"んっ……ぷはっ……はぁ……ぺろっ、ちゅ、ちゅうぅ……。",
|
| 747 |
+
"あむっ、んぐっ、んちゅ……はぁ、じゅるっ……。"
|
| 748 |
+
])
|
| 749 |
+
|
| 750 |
+
# --- BAGIAN 3: APLIKASI UTAMA ---
|
| 751 |
+
def create_inference_app(model_holder: TTSModelHolder) -> gr.Blocks:
|
| 752 |
+
model_names = model_holder.model_names
|
| 753 |
+
current_model_name = model_names[0] if model_names else None
|
| 754 |
+
initial_pth_files = [str(f) for f in model_holder.model_files_dict[current_model_name]] if current_model_name else []
|
| 755 |
+
current_model_path = initial_pth_files[0] if initial_pth_files else None
|
| 756 |
+
|
| 757 |
+
if current_model_name and current_model_path:
|
| 758 |
+
model_holder.get_model(current_model_name, current_model_path)
|
| 759 |
+
|
| 760 |
+
# Variabel pesan awal
|
| 761 |
+
welcome_msg = '''
|
| 762 |
+
<div class="chat-bubble-bot">
|
| 763 |
+
(*≧ω≦*) Halo! Saya Mutsumi 🌥️.<br>
|
| 764 |
+
Saya bisa membantu hal ini :<br>
|
| 765 |
+
• Cara menggunakan TTS<br>
|
| 766 |
+
• Informasi bahasa<br>
|
| 767 |
+
• Efek input non-Jepang<br>
|
| 768 |
+
Klik tombol di bawah untuk melihat detail!
|
| 769 |
+
</div>
|
| 770 |
+
'''
|
| 771 |
+
|
| 772 |
+
def tts_fn(text, sdp_ratio, noise_scale, noise_scale_w, length_scale):
|
| 773 |
+
try:
|
| 774 |
+
sr, audio = model_holder.current_model.infer(
|
| 775 |
+
text=text, language="JP", sdp_ratio=sdp_ratio,
|
| 776 |
+
noise=noise_scale, noise_w=noise_scale_w, length=length_scale,
|
| 777 |
+
line_split=False, split_interval=0.5, speaker_id=0,
|
| 778 |
+
)
|
| 779 |
+
return "Generation Complete! ✅", (sr, audio)
|
| 780 |
+
except Exception as e: return f"Error: {e}", None
|
| 781 |
+
|
| 782 |
+
def chat_respond(choice):
|
| 783 |
+
responses = {
|
| 784 |
+
1: '''<div class="chat-bubble-bot">
|
| 785 |
+
<b>Cara Menggunakan:</b><br>
|
| 786 |
+
1. Masukkan teks Jepang di input<br>
|
| 787 |
+
2. Settings jika perlu<br>
|
| 788 |
+
3. Atur kecepatan jika perlu<br>
|
| 789 |
+
4. Klik 'Generate Voice'<br>
|
| 790 |
+
5. dan hasil muncul!<br><br>
|
| 791 |
+
🌥️ <b>NOTES :</b> tidak di sarankan mengubah settingan kecuali bagian atur kecepatan aja.
|
| 792 |
+
</div>''',
|
| 793 |
+
2: '''<div class="chat-bubble-bot">
|
| 794 |
+
Model ini hanya support <b>bahasa Jepang</b> aja sementara lainnya tidak bisa.
|
| 795 |
+
</div>''',
|
| 796 |
+
3: '''<div class="chat-bubble-bot">
|
| 797 |
+
⚠️ <b>Input Bukan Jepang</b> ⚠️<br>
|
| 798 |
+
Karakter akan terdengar aneh karena model khusus bahasa Jepang.
|
| 799 |
+
</div>'''
|
| 800 |
+
}
|
| 801 |
+
return responses.get(choice, welcome_msg)
|
| 802 |
+
|
| 803 |
+
with gr.Blocks(css=css, theme=gr.themes.Soft(primary_hue="pink")) as app:
|
| 804 |
+
# --- LOADING SCREEN (untuk Yes) ---
|
| 805 |
+
with gr.Column(visible=False, elem_id="loading-screen-yes") as loading_screen_yes:
|
| 806 |
+
with gr.Column(elem_classes="loading-screen"):
|
| 807 |
+
with gr.Column(elem_classes="loading-content"):
|
| 808 |
+
gr.HTML('<img src="https://huggingface.co/spaces/Plana-Archive/NSW-CHUPA/resolve/main/Plana-Archive.PNG" class="loading-logo">')
|
| 809 |
+
gr.HTML('<div class="loading-title">Memuat Aplikasi...</div>')
|
| 810 |
+
gr.HTML('<div class="loading-message">Harap tunggu sebentar, aplikasi sedang dimuat.</div>')
|
| 811 |
+
gr.HTML('<div class="loading-large-spinner"></div>')
|
| 812 |
+
|
| 813 |
+
# --- LOADING SCREEN (untuk Tidak) ---
|
| 814 |
+
with gr.Column(visible=False, elem_id="loading-screen-no") as loading_screen_no:
|
| 815 |
+
with gr.Column(elem_classes="loading-screen-no"):
|
| 816 |
+
with gr.Column(elem_classes="loading-content-no"):
|
| 817 |
+
gr.HTML('<img src="https://huggingface.co/spaces/Plana-Archive/NSW-CHUPA/resolve/main/Plana-Archive.PNG" class="loading-logo">')
|
| 818 |
+
gr.HTML('<div class="loading-title-no">⚠️ Peringatan Minna ⚠️</div>')
|
| 819 |
+
gr.HTML('<div class="loading-message-no">Silahkan kembali jika belum cukup umurmu, Hargai Author yah! 🌥️</div>')
|
| 820 |
+
gr.HTML('<div class="loading-large-spinner-no"></div>')
|
| 821 |
+
|
| 822 |
+
# --- VERIFIKASI USIA OVERLAY ---
|
| 823 |
+
with gr.Column(visible=True, elem_id="age-verification") as verification_overlay:
|
| 824 |
+
with gr.Column(elem_classes="age-verification-overlay"):
|
| 825 |
+
with gr.Column(elem_classes="age-verification-box"):
|
| 826 |
+
gr.HTML('<img src="https://huggingface.co/spaces/Plana-Archive/NSW-CHUPA/resolve/main/Plana-Archive.PNG" class="verification-image">')
|
| 827 |
+
gr.HTML('<div class="age-verification-title">🍂 Verifikasi Usia 🍂</div>')
|
| 828 |
+
|
| 829 |
+
gr.HTML('''
|
| 830 |
+
<div class="verification-message">
|
| 831 |
+
Model ini hanya untuk 18+ Tahun. Pastikan umur kamu sudah cukup dewasa untuk pakai model ini.<br>
|
| 832 |
+
Apakah usiamu sudah mencapai 18+ tahun? (⸝⸝╸▵╺⸝⸝)
|
| 833 |
+
</div>
|
| 834 |
+
''')
|
| 835 |
+
|
| 836 |
+
with gr.Row(elem_classes="age-verification-buttons"):
|
| 837 |
+
btn_no = gr.Button("Tidak", variant="secondary", elem_classes="age-btn age-btn-no")
|
| 838 |
+
btn_yes = gr.Button("Yes", variant="primary", elem_classes="age-btn age-btn-yes")
|
| 839 |
+
|
| 840 |
+
# --- KONTEN UTAMA (tersembunyi sampai verifikasi) ---
|
| 841 |
+
with gr.Column(visible=False, elem_id="main-content") as main_content:
|
| 842 |
+
with gr.Column(elem_classes="main-container"):
|
| 843 |
+
gr.HTML('<div class="header-img-container"><img src="https://huggingface.co/spaces/Plana-Archive/sbv2-chupa-demo-space/resolve/main/Plana-Archive.PNG" class="header-img"></div>')
|
| 844 |
+
|
| 845 |
+
# STATUS CARD
|
| 846 |
+
gr.HTML('''
|
| 847 |
+
<div class="status-card">
|
| 848 |
+
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 12px;">
|
| 849 |
+
<span class="dot-online"></span><b style="color: #ff69b4;">Voice Conversion System Online</b>
|
| 850 |
+
</div>
|
| 851 |
+
<div style="display: flex; width: 100%; border-top: 1px solid #fff0f7; padding-top: 10px; justify-content: space-around;">
|
| 852 |
+
<div style="text-align:center;"><span style="font-size: 13px; font-weight: 600; color: #7b4d5a;">👥 1 Students</span><br><span style="font-size: 11px; color: #b07d8b;">Ready</span></div>
|
| 853 |
+
<div style="text-align:center;"><span style="font-size: 13px; font-weight: 600; color: #7b4d5a;">📊 Total Models</span><br><span style="font-size: 11px; color: #b07d8b;">Database: 1</span></div>
|
| 854 |
+
</div>
|
| 855 |
+
</div>
|
| 856 |
+
''')
|
| 857 |
+
|
| 858 |
+
with gr.Row(elem_classes="content-row"):
|
| 859 |
+
# SIDEBAR
|
| 860 |
+
with gr.Column(scale=1, elem_classes="sidebar-column"):
|
| 861 |
+
gr.Markdown("### ⚙️ Audio Settings")
|
| 862 |
+
length_scale = gr.Slider(0.1, 2, value=1.0, step=0.1, label="Kecepatan")
|
| 863 |
+
sdp_ratio = gr.Slider(0, 1, value=0.2, step=0.1, label="SDP Ratio")
|
| 864 |
+
|
| 865 |
+
with gr.Accordion("🔮 Advanced Settings 🔮", open=False, elem_classes="pink-accordion"):
|
| 866 |
+
noise_scale = gr.Slider(0.1, 2, value=0.6, step=0.1, label="Noise")
|
| 867 |
+
noise_scale_w = gr.Slider(0.1, 2, value=0.8, step=0.1, label="Noise_W")
|
| 868 |
+
|
| 869 |
+
# MAIN CONTENT
|
| 870 |
+
with gr.Column(scale=2, elem_classes="main-column"):
|
| 871 |
+
with gr.Group():
|
| 872 |
+
text_input = gr.TextArea(label="Input Teks (JP)", value="ちゅぱ、ちゅるる...", lines=10)
|
| 873 |
+
random_button = gr.Button("🎲 KLIK ACAK ISI TEXT 🎲", variant="secondary")
|
| 874 |
+
|
| 875 |
+
tts_button = gr.Button("Generate Voice", variant="primary", elem_classes="generate-btn")
|
| 876 |
+
|
| 877 |
+
# --- CHATBOT AREA ---
|
| 878 |
+
with gr.Column(elem_classes="chat-container"):
|
| 879 |
+
gr.HTML('''
|
| 880 |
+
<div class="chat-header">
|
| 881 |
+
<span class="chat-title">Plana AI - Asisten</span>
|
| 882 |
+
<span class="chat-status">● CONNECTED</span>
|
| 883 |
+
</div>
|
| 884 |
+
''')
|
| 885 |
+
|
| 886 |
+
chat_display = gr.HTML(welcome_msg)
|
| 887 |
+
|
| 888 |
+
with gr.Column(elem_classes="chat-button-group"):
|
| 889 |
+
btn_opt1 = gr.Button("1. Cara pakai VITS ini", elem_classes="chat-btn-opt")
|
| 890 |
+
btn_opt2 = gr.Button("2. Support bahasa apa aja VITS ini", elem_classes="chat-btn-opt")
|
| 891 |
+
btn_opt3 = gr.Button("3. Apa yang terjadi jika inputs bukan Jepang", elem_classes="chat-btn-opt")
|
| 892 |
+
|
| 893 |
+
with gr.Row():
|
| 894 |
+
text_output = gr.Textbox(label="Status", interactive=False)
|
| 895 |
+
audio_output = gr.Audio(label="Output", interactive=False, elem_classes="output-audio-box")
|
| 896 |
+
|
| 897 |
+
gr.HTML('''
|
| 898 |
+
<div class="note-box">
|
| 899 |
+
<div class="note-title">📑 TENTANG SETTINGS 📑</div>
|
| 900 |
+
<div class="note-content">
|
| 901 |
+
<b>Kecepatan:</b> Mengatur tempo bicara (Default 1.0).<br>
|
| 902 |
+
<b>SDP Ratio:</b> Ritme bicara. Angka tinggi lebih ekspresif.<br>
|
| 903 |
+
<b>Noise:</b> Stabilitas suara. Kurangi jika suara pecah.<br>
|
| 904 |
+
<b>Noise_W:</b> Dinamika durasi antar kata.
|
| 905 |
+
</div>
|
| 906 |
+
</div>
|
| 907 |
+
''')
|
| 908 |
+
|
| 909 |
+
# FOOTER
|
| 910 |
+
gr.HTML('''
|
| 911 |
+
<div class="footer-container">
|
| 912 |
+
<div style="font-family: 'Quicksand', sans-serif; font-size: 14px; color: #b07d8b; font-weight: 700;">
|
| 913 |
+
👅 NSW - VITS Anime • TTS 👅
|
| 914 |
+
</div>
|
| 915 |
+
<div style="font-size: 11px; color: #d0a4b0; margin-top: 5px;">By Mutsumi • Style-Bert-VITS2</div>
|
| 916 |
+
</div>
|
| 917 |
+
''')
|
| 918 |
+
|
| 919 |
+
# --- EVENT HANDLERS VERIFIKASI ---
|
| 920 |
+
def show_loading_yes():
|
| 921 |
+
"""Tampilkan loading screen untuk tombol Yes"""
|
| 922 |
+
return {
|
| 923 |
+
verification_overlay: gr.Column(visible=False),
|
| 924 |
+
loading_screen_yes: gr.Column(visible=True)
|
| 925 |
+
}
|
| 926 |
+
|
| 927 |
+
def show_main_content():
|
| 928 |
+
"""Tampilkan konten utama setelah loading"""
|
| 929 |
+
time.sleep(5) # Tunggu 5 detik
|
| 930 |
+
return {
|
| 931 |
+
loading_screen_yes: gr.Column(visible=False),
|
| 932 |
+
main_content: gr.Column(visible=True)
|
| 933 |
+
}
|
| 934 |
+
|
| 935 |
+
def show_loading_no():
|
| 936 |
+
"""Tampilkan loading screen untuk tombol Tidak"""
|
| 937 |
+
return {
|
| 938 |
+
verification_overlay: gr.Column(visible=False),
|
| 939 |
+
loading_screen_no: gr.Column(visible=True)
|
| 940 |
+
}
|
| 941 |
+
|
| 942 |
+
def redirect_to_huggingface():
|
| 943 |
+
"""Redirect ke Hugging Face setelah delay"""
|
| 944 |
+
time.sleep(3) # Tunggu 3 detik untuk efek loading
|
| 945 |
+
return {
|
| 946 |
+
loading_screen_no: gr.Column(visible=False),
|
| 947 |
+
verification_overlay: gr.Column(visible=True)
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
# Event Handlers Utama
|
| 951 |
+
random_button.click(get_random_text, outputs=[text_input])
|
| 952 |
+
tts_button.click(
|
| 953 |
+
tts_fn,
|
| 954 |
+
inputs=[text_input, sdp_ratio, noise_scale, noise_scale_w, length_scale],
|
| 955 |
+
outputs=[text_output, audio_output]
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
# Chatbot Handlers
|
| 959 |
+
btn_opt1.click(fn=lambda: chat_respond(1), outputs=chat_display)
|
| 960 |
+
btn_opt2.click(fn=lambda: chat_respond(2), outputs=chat_display)
|
| 961 |
+
btn_opt3.click(fn=lambda: chat_respond(3), outputs=chat_display)
|
| 962 |
+
|
| 963 |
+
# Verifikasi Handlers
|
| 964 |
+
# Handler untuk tombol Yes dengan loading screen
|
| 965 |
+
btn_yes.click(
|
| 966 |
+
fn=show_loading_yes,
|
| 967 |
+
outputs=[verification_overlay, loading_screen_yes]
|
| 968 |
+
).then(
|
| 969 |
+
fn=show_main_content,
|
| 970 |
+
outputs=[loading_screen_yes, main_content]
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
# Handler untuk tombol No dengan loading screen dan redirect
|
| 974 |
+
btn_no.click(
|
| 975 |
+
fn=show_loading_no,
|
| 976 |
+
outputs=[verification_overlay, loading_screen_no]
|
| 977 |
+
).then(
|
| 978 |
+
fn=redirect_to_huggingface,
|
| 979 |
+
outputs=[loading_screen_no, verification_overlay]
|
| 980 |
+
).then(
|
| 981 |
+
# JavaScript untuk membuka tab baru ke Hugging Face
|
| 982 |
+
fn=None,
|
| 983 |
+
inputs=[],
|
| 984 |
+
outputs=[],
|
| 985 |
+
js="window.open('https://huggingface.co/Plana-Archive', '_blank');"
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
return app
|
| 989 |
+
|
| 990 |
+
if __name__ == "__main__":
|
| 991 |
+
# Load BERT model dan tokenizer untuk JP
|
| 992 |
+
try:
|
| 993 |
+
bert_models.load_model(Languages.JP)
|
| 994 |
+
bert_models.load_tokenizer(Languages.JP)
|
| 995 |
+
logger.info("✅ BERT model dan tokenizer berhasil dimuat")
|
| 996 |
+
except Exception as e:
|
| 997 |
+
logger.error(f"❌ Gagal memuat BERT model: {e}")
|
| 998 |
+
# Coba load dengan path eksplisit
|
| 999 |
+
bert_path = Path("./bert/bert-base-japanese-v3")
|
| 1000 |
+
if bert_path.exists():
|
| 1001 |
+
try:
|
| 1002 |
+
from style_bert_vits2.nlp import bert_models
|
| 1003 |
+
import sys
|
| 1004 |
+
# Tambahkan path bert ke sys.path
|
| 1005 |
+
sys.path.insert(0, str(bert_path.parent))
|
| 1006 |
+
logger.info(f"🔄 Mencoba memuat BERT dari {bert_path}")
|
| 1007 |
+
# Reload module
|
| 1008 |
+
import importlib
|
| 1009 |
+
importlib.reload(bert_models)
|
| 1010 |
+
bert_models.load_model(Languages.JP)
|
| 1011 |
+
bert_models.load_tokenizer(Languages.JP)
|
| 1012 |
+
logger.info("✅ BERT model berhasil dimuat dengan path eksplisit")
|
| 1013 |
+
except Exception as e2:
|
| 1014 |
+
logger.error(f"❌ Masih gagal memuat BERT: {e2}")
|
| 1015 |
+
# Fallback ke model dasar
|
| 1016 |
+
logger.info("🔄 Fallback ke model dasar...")
|
| 1017 |
+
else:
|
| 1018 |
+
logger.error("❌ Path BERT tidak ditemukan")
|
| 1019 |
+
|
| 1020 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1021 |
+
model_holder = TTSModelHolder(Path("model_assets"), device)
|
| 1022 |
+
create_inference_app(model_holder).launch()
|
Mutsumi-Chan/NSW-CHUPA/chupa_examples.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Mutsumi-Chan/NSW-CHUPA/model_assets/chupa_1/chupa_1spk_e1000_s194312.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8af08fae399f64bbc506a4accaf6c56b0d294def6435235dbe60755728784d8c
|
| 3 |
+
size 251150980
|
Mutsumi-Chan/NSW-CHUPA/model_assets/chupa_1/config.json
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_name": "chupa_1spk",
|
| 3 |
+
"train": {
|
| 4 |
+
"log_interval": 50,
|
| 5 |
+
"eval_interval": 1000,
|
| 6 |
+
"seed": 42,
|
| 7 |
+
"epochs": 1000,
|
| 8 |
+
"learning_rate": 0.0001,
|
| 9 |
+
"betas": [0.8, 0.99],
|
| 10 |
+
"eps": 1e-9,
|
| 11 |
+
"batch_size": 2,
|
| 12 |
+
"bf16_run": false,
|
| 13 |
+
"fp16_run": false,
|
| 14 |
+
"lr_decay": 0.99996,
|
| 15 |
+
"segment_size": 16384,
|
| 16 |
+
"init_lr_ratio": 1,
|
| 17 |
+
"warmup_epochs": 0,
|
| 18 |
+
"c_mel": 45,
|
| 19 |
+
"c_kl": 1.0,
|
| 20 |
+
"c_commit": 100,
|
| 21 |
+
"skip_optimizer": false,
|
| 22 |
+
"freeze_ZH_bert": false,
|
| 23 |
+
"freeze_JP_bert": false,
|
| 24 |
+
"freeze_EN_bert": false,
|
| 25 |
+
"freeze_emo": false,
|
| 26 |
+
"freeze_style": false,
|
| 27 |
+
"freeze_decoder": false
|
| 28 |
+
},
|
| 29 |
+
"data": {
|
| 30 |
+
"use_jp_extra": true,
|
| 31 |
+
"training_files": "Data/chupa_1/train.list",
|
| 32 |
+
"validation_files": "Data/chupa_1/val.list",
|
| 33 |
+
"max_wav_value": 32768.0,
|
| 34 |
+
"sampling_rate": 44100,
|
| 35 |
+
"filter_length": 2048,
|
| 36 |
+
"hop_length": 512,
|
| 37 |
+
"win_length": 2048,
|
| 38 |
+
"n_mel_channels": 128,
|
| 39 |
+
"mel_fmin": 0.0,
|
| 40 |
+
"mel_fmax": null,
|
| 41 |
+
"add_blank": true,
|
| 42 |
+
"n_speakers": 1,
|
| 43 |
+
"spk2id": {
|
| 44 |
+
"1": 0
|
| 45 |
+
},
|
| 46 |
+
"cleaned_text": true,
|
| 47 |
+
"num_styles": 1,
|
| 48 |
+
"style2id": {
|
| 49 |
+
"Neutral": 0
|
| 50 |
+
}
|
| 51 |
+
},
|
| 52 |
+
"model": {
|
| 53 |
+
"use_spk_conditioned_encoder": true,
|
| 54 |
+
"use_noise_scaled_mas": true,
|
| 55 |
+
"use_mel_posterior_encoder": false,
|
| 56 |
+
"use_duration_discriminator": false,
|
| 57 |
+
"use_wavlm_discriminator": true,
|
| 58 |
+
"inter_channels": 192,
|
| 59 |
+
"hidden_channels": 192,
|
| 60 |
+
"filter_channels": 768,
|
| 61 |
+
"n_heads": 2,
|
| 62 |
+
"n_layers": 6,
|
| 63 |
+
"kernel_size": 3,
|
| 64 |
+
"p_dropout": 0.1,
|
| 65 |
+
"resblock": "1",
|
| 66 |
+
"resblock_kernel_sizes": [3, 7, 11],
|
| 67 |
+
"resblock_dilation_sizes": [
|
| 68 |
+
[1, 3, 5],
|
| 69 |
+
[1, 3, 5],
|
| 70 |
+
[1, 3, 5]
|
| 71 |
+
],
|
| 72 |
+
"upsample_rates": [8, 8, 2, 2, 2],
|
| 73 |
+
"upsample_initial_channel": 512,
|
| 74 |
+
"upsample_kernel_sizes": [16, 16, 8, 2, 2],
|
| 75 |
+
"n_layers_q": 3,
|
| 76 |
+
"use_spectral_norm": false,
|
| 77 |
+
"gin_channels": 512,
|
| 78 |
+
"slm": {
|
| 79 |
+
"model": "./slm/wavlm-base-plus",
|
| 80 |
+
"sr": 16000,
|
| 81 |
+
"hidden": 768,
|
| 82 |
+
"nlayers": 13,
|
| 83 |
+
"initial_channel": 64
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
"version": "2.6.0-JP-Extra"
|
| 87 |
+
}
|
Mutsumi-Chan/NSW-CHUPA/model_assets/chupa_1/style_vectors.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9fd42ba186b887c87b57fa66f5781f3fdf4382504d971d5338288d50b8b40461
|
| 3 |
+
size 1152
|
Mutsumi-Chan/NSW-CHUPA/requirements.txt
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --- Tambahan untuk Download Aset ---
|
| 2 |
+
huggingface_hub
|
| 3 |
+
hf_transfer
|
| 4 |
+
|
| 5 |
+
# --- UI & Server ---
|
| 6 |
+
gradio==4.44.1
|
| 7 |
+
numpy==1.26.4
|
| 8 |
+
pydantic==2.8.2
|
| 9 |
+
pydantic-core==2.20.1
|
| 10 |
+
fastapi
|
| 11 |
+
uvicorn==0.30.6
|
| 12 |
+
|
| 13 |
+
# --- TTS Core & Audio ---
|
| 14 |
+
torch==2.4.0
|
| 15 |
+
torchaudio==2.4.0
|
| 16 |
+
transformers==4.44.2
|
| 17 |
+
librosa==0.10.1
|
| 18 |
+
scipy==1.12.0
|
| 19 |
+
numba==0.59.0
|
| 20 |
+
pyworld-prebuilt==0.3.5.post2
|
| 21 |
+
|
| 22 |
+
# --- Text Processing & Dictionaries ---
|
| 23 |
+
mecab-python3==1.0.8
|
| 24 |
+
unidic-lite
|
| 25 |
+
pyopenjtalk-prebuilt==0.3.0
|
| 26 |
+
pypinyin
|
| 27 |
+
jieba
|
| 28 |
+
cn2an
|
| 29 |
+
langid
|
| 30 |
+
g2p_en
|
| 31 |
+
cmudict
|
| 32 |
+
jaconv
|
| 33 |
+
num2words
|
| 34 |
+
|
| 35 |
+
# --- Utilities ---
|
| 36 |
+
PyYAML
|
| 37 |
+
requests
|
| 38 |
+
safetensors
|
| 39 |
+
sentencepiece
|
| 40 |
+
loguru
|
| 41 |
+
psutil
|
| 42 |
+
GPUtil
|
| 43 |
+
matplotlib
|
| 44 |
+
tensorboard
|
| 45 |
+
nltk
|
| 46 |
+
umap-learn
|
| 47 |
+
pyannote.audio==3.3.1
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/.editorconfig
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
root = true
|
| 2 |
+
|
| 3 |
+
[*]
|
| 4 |
+
charset = utf-8
|
| 5 |
+
end_of_line = lf
|
| 6 |
+
insert_final_newline = true
|
| 7 |
+
indent_size = 4
|
| 8 |
+
indent_style = space
|
| 9 |
+
trim_trailing_whitespace = true
|
| 10 |
+
|
| 11 |
+
[*.md]
|
| 12 |
+
trim_trailing_whitespace = false
|
| 13 |
+
|
| 14 |
+
[*.yml]
|
| 15 |
+
indent_size = 2
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/__init__.py
ADDED
|
File without changes
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/constants.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
from style_bert_vits2.utils.strenum import StrEnum
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Style-Bert-VITS2 のバージョン
|
| 7 |
+
VERSION = "2.6.0"
|
| 8 |
+
|
| 9 |
+
# Style-Bert-VITS2 のベースディレクトリ
|
| 10 |
+
BASE_DIR = Path(__file__).parent.parent
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# 利用可能な言語
|
| 14 |
+
## JP-Extra モデル利用時は JP 以外の言語の音声合成はできない
|
| 15 |
+
class Languages(StrEnum):
|
| 16 |
+
JP = "JP"
|
| 17 |
+
EN = "EN"
|
| 18 |
+
ZH = "ZH"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# 言語ごとのデフォルトの BERT トークナイザーのパス
|
| 22 |
+
DEFAULT_BERT_TOKENIZER_PATHS = {
|
| 23 |
+
Languages.JP: BASE_DIR / "bert" / "deberta-v2-large-japanese-char-wwm",
|
| 24 |
+
Languages.EN: BASE_DIR / "bert" / "deberta-v3-large",
|
| 25 |
+
Languages.ZH: BASE_DIR / "bert" / "chinese-roberta-wwm-ext-large",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
# デフォルトのユーザー辞書ディレクトリ
|
| 29 |
+
## style_bert_vits2.nlp.japanese.user_dict モジュールのデフォルト値として利用される
|
| 30 |
+
## ライブラリとしての利用などで外部のユーザー辞書を指定したい場合は、user_dict 以下の各関数の実行時、引数に辞書データファイルのパスを指定する
|
| 31 |
+
DEFAULT_USER_DICT_DIR = BASE_DIR / "dict_data"
|
| 32 |
+
|
| 33 |
+
# デフォルトの推論パラメータ
|
| 34 |
+
DEFAULT_STYLE = "Neutral"
|
| 35 |
+
DEFAULT_STYLE_WEIGHT = 1.0
|
| 36 |
+
DEFAULT_SDP_RATIO = 0.2
|
| 37 |
+
DEFAULT_NOISE = 0.6
|
| 38 |
+
DEFAULT_NOISEW = 0.8
|
| 39 |
+
DEFAULT_LENGTH = 1.0
|
| 40 |
+
DEFAULT_LINE_SPLIT = True
|
| 41 |
+
DEFAULT_SPLIT_INTERVAL = 0.5
|
| 42 |
+
DEFAULT_ASSIST_TEXT_WEIGHT = 0.7
|
| 43 |
+
DEFAULT_ASSIST_TEXT_WEIGHT = 1.0
|
| 44 |
+
|
| 45 |
+
# Gradio のテーマ
|
| 46 |
+
## Built-in theme: "default", "base", "monochrome", "soft", "glass"
|
| 47 |
+
## See https://huggingface.co/spaces/gradio/theme-gallery for more themes
|
| 48 |
+
GRADIO_THEME = "NoCrypt/miku"
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/logging.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from loguru import logger
|
| 2 |
+
|
| 3 |
+
from style_bert_vits2.utils.stdout_wrapper import SAFE_STDOUT
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Remove all default handlers
|
| 7 |
+
logger.remove()
|
| 8 |
+
|
| 9 |
+
# Add a new handler
|
| 10 |
+
logger.add(
|
| 11 |
+
SAFE_STDOUT,
|
| 12 |
+
format="<g>{time:MM-DD HH:mm:ss}</g> |<lvl>{level:^8}</lvl>| {file}:{line} | {message}",
|
| 13 |
+
backtrace=True,
|
| 14 |
+
diagnose=True,
|
| 15 |
+
)
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/__init__.py
ADDED
|
File without changes
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/attentions.py
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import Any, Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
|
| 8 |
+
from style_bert_vits2.models import commons
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class LayerNorm(nn.Module):
|
| 12 |
+
def __init__(self, channels: int, eps: float = 1e-5) -> None:
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.channels = channels
|
| 15 |
+
self.eps = eps
|
| 16 |
+
|
| 17 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
| 18 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
| 19 |
+
|
| 20 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 21 |
+
x = x.transpose(1, -1)
|
| 22 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
| 23 |
+
return x.transpose(1, -1)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@torch.jit.script # type: ignore
|
| 27 |
+
def fused_add_tanh_sigmoid_multiply(
|
| 28 |
+
input_a: torch.Tensor, input_b: torch.Tensor, n_channels: list[int]
|
| 29 |
+
) -> torch.Tensor:
|
| 30 |
+
n_channels_int = n_channels[0]
|
| 31 |
+
in_act = input_a + input_b
|
| 32 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
| 33 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
| 34 |
+
acts = t_act * s_act
|
| 35 |
+
return acts
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Encoder(nn.Module):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
hidden_channels: int,
|
| 42 |
+
filter_channels: int,
|
| 43 |
+
n_heads: int,
|
| 44 |
+
n_layers: int,
|
| 45 |
+
kernel_size: int = 1,
|
| 46 |
+
p_dropout: float = 0.0,
|
| 47 |
+
window_size: int = 4,
|
| 48 |
+
isflow: bool = True,
|
| 49 |
+
**kwargs: Any,
|
| 50 |
+
) -> None:
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.hidden_channels = hidden_channels
|
| 53 |
+
self.filter_channels = filter_channels
|
| 54 |
+
self.n_heads = n_heads
|
| 55 |
+
self.n_layers = n_layers
|
| 56 |
+
self.kernel_size = kernel_size
|
| 57 |
+
self.p_dropout = p_dropout
|
| 58 |
+
self.window_size = window_size
|
| 59 |
+
# if isflow:
|
| 60 |
+
# cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
|
| 61 |
+
# self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
|
| 62 |
+
# self.cond_layer = weight_norm(cond_layer, name='weight')
|
| 63 |
+
# self.gin_channels = 256
|
| 64 |
+
self.cond_layer_idx = self.n_layers
|
| 65 |
+
if "gin_channels" in kwargs:
|
| 66 |
+
self.gin_channels = kwargs["gin_channels"]
|
| 67 |
+
if self.gin_channels != 0:
|
| 68 |
+
self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
|
| 69 |
+
# vits2 says 3rd block, so idx is 2 by default
|
| 70 |
+
self.cond_layer_idx = (
|
| 71 |
+
kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
|
| 72 |
+
)
|
| 73 |
+
# logger.debug(self.gin_channels, self.cond_layer_idx)
|
| 74 |
+
assert (
|
| 75 |
+
self.cond_layer_idx < self.n_layers
|
| 76 |
+
), "cond_layer_idx should be less than n_layers"
|
| 77 |
+
self.drop = nn.Dropout(p_dropout)
|
| 78 |
+
self.attn_layers = nn.ModuleList()
|
| 79 |
+
self.norm_layers_1 = nn.ModuleList()
|
| 80 |
+
self.ffn_layers = nn.ModuleList()
|
| 81 |
+
self.norm_layers_2 = nn.ModuleList()
|
| 82 |
+
for i in range(self.n_layers):
|
| 83 |
+
self.attn_layers.append(
|
| 84 |
+
MultiHeadAttention(
|
| 85 |
+
hidden_channels,
|
| 86 |
+
hidden_channels,
|
| 87 |
+
n_heads,
|
| 88 |
+
p_dropout=p_dropout,
|
| 89 |
+
window_size=window_size,
|
| 90 |
+
)
|
| 91 |
+
)
|
| 92 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
| 93 |
+
self.ffn_layers.append(
|
| 94 |
+
FFN(
|
| 95 |
+
hidden_channels,
|
| 96 |
+
hidden_channels,
|
| 97 |
+
filter_channels,
|
| 98 |
+
kernel_size,
|
| 99 |
+
p_dropout=p_dropout,
|
| 100 |
+
)
|
| 101 |
+
)
|
| 102 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
| 103 |
+
|
| 104 |
+
def forward(
|
| 105 |
+
self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None
|
| 106 |
+
) -> torch.Tensor:
|
| 107 |
+
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
| 108 |
+
x = x * x_mask
|
| 109 |
+
for i in range(self.n_layers):
|
| 110 |
+
if i == self.cond_layer_idx and g is not None:
|
| 111 |
+
g = self.spk_emb_linear(g.transpose(1, 2))
|
| 112 |
+
assert g is not None
|
| 113 |
+
g = g.transpose(1, 2)
|
| 114 |
+
x = x + g
|
| 115 |
+
x = x * x_mask
|
| 116 |
+
y = self.attn_layers[i](x, x, attn_mask)
|
| 117 |
+
y = self.drop(y)
|
| 118 |
+
x = self.norm_layers_1[i](x + y)
|
| 119 |
+
|
| 120 |
+
y = self.ffn_layers[i](x, x_mask)
|
| 121 |
+
y = self.drop(y)
|
| 122 |
+
x = self.norm_layers_2[i](x + y)
|
| 123 |
+
x = x * x_mask
|
| 124 |
+
return x
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class Decoder(nn.Module):
|
| 128 |
+
def __init__(
|
| 129 |
+
self,
|
| 130 |
+
hidden_channels: int,
|
| 131 |
+
filter_channels: int,
|
| 132 |
+
n_heads: int,
|
| 133 |
+
n_layers: int,
|
| 134 |
+
kernel_size: int = 1,
|
| 135 |
+
p_dropout: float = 0.0,
|
| 136 |
+
proximal_bias: bool = False,
|
| 137 |
+
proximal_init: bool = True,
|
| 138 |
+
**kwargs: Any,
|
| 139 |
+
) -> None:
|
| 140 |
+
super().__init__()
|
| 141 |
+
self.hidden_channels = hidden_channels
|
| 142 |
+
self.filter_channels = filter_channels
|
| 143 |
+
self.n_heads = n_heads
|
| 144 |
+
self.n_layers = n_layers
|
| 145 |
+
self.kernel_size = kernel_size
|
| 146 |
+
self.p_dropout = p_dropout
|
| 147 |
+
self.proximal_bias = proximal_bias
|
| 148 |
+
self.proximal_init = proximal_init
|
| 149 |
+
|
| 150 |
+
self.drop = nn.Dropout(p_dropout)
|
| 151 |
+
self.self_attn_layers = nn.ModuleList()
|
| 152 |
+
self.norm_layers_0 = nn.ModuleList()
|
| 153 |
+
self.encdec_attn_layers = nn.ModuleList()
|
| 154 |
+
self.norm_layers_1 = nn.ModuleList()
|
| 155 |
+
self.ffn_layers = nn.ModuleList()
|
| 156 |
+
self.norm_layers_2 = nn.ModuleList()
|
| 157 |
+
for i in range(self.n_layers):
|
| 158 |
+
self.self_attn_layers.append(
|
| 159 |
+
MultiHeadAttention(
|
| 160 |
+
hidden_channels,
|
| 161 |
+
hidden_channels,
|
| 162 |
+
n_heads,
|
| 163 |
+
p_dropout=p_dropout,
|
| 164 |
+
proximal_bias=proximal_bias,
|
| 165 |
+
proximal_init=proximal_init,
|
| 166 |
+
)
|
| 167 |
+
)
|
| 168 |
+
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
| 169 |
+
self.encdec_attn_layers.append(
|
| 170 |
+
MultiHeadAttention(
|
| 171 |
+
hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
|
| 172 |
+
)
|
| 173 |
+
)
|
| 174 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
| 175 |
+
self.ffn_layers.append(
|
| 176 |
+
FFN(
|
| 177 |
+
hidden_channels,
|
| 178 |
+
hidden_channels,
|
| 179 |
+
filter_channels,
|
| 180 |
+
kernel_size,
|
| 181 |
+
p_dropout=p_dropout,
|
| 182 |
+
causal=True,
|
| 183 |
+
)
|
| 184 |
+
)
|
| 185 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
| 186 |
+
|
| 187 |
+
def forward(
|
| 188 |
+
self,
|
| 189 |
+
x: torch.Tensor,
|
| 190 |
+
x_mask: torch.Tensor,
|
| 191 |
+
h: torch.Tensor,
|
| 192 |
+
h_mask: torch.Tensor,
|
| 193 |
+
) -> torch.Tensor:
|
| 194 |
+
"""
|
| 195 |
+
x: decoder input
|
| 196 |
+
h: encoder output
|
| 197 |
+
"""
|
| 198 |
+
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
|
| 199 |
+
device=x.device, dtype=x.dtype
|
| 200 |
+
)
|
| 201 |
+
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
| 202 |
+
x = x * x_mask
|
| 203 |
+
for i in range(self.n_layers):
|
| 204 |
+
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
| 205 |
+
y = self.drop(y)
|
| 206 |
+
x = self.norm_layers_0[i](x + y)
|
| 207 |
+
|
| 208 |
+
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
| 209 |
+
y = self.drop(y)
|
| 210 |
+
x = self.norm_layers_1[i](x + y)
|
| 211 |
+
|
| 212 |
+
y = self.ffn_layers[i](x, x_mask)
|
| 213 |
+
y = self.drop(y)
|
| 214 |
+
x = self.norm_layers_2[i](x + y)
|
| 215 |
+
x = x * x_mask
|
| 216 |
+
return x
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class MultiHeadAttention(nn.Module):
|
| 220 |
+
def __init__(
|
| 221 |
+
self,
|
| 222 |
+
channels: int,
|
| 223 |
+
out_channels: int,
|
| 224 |
+
n_heads: int,
|
| 225 |
+
p_dropout: float = 0.0,
|
| 226 |
+
window_size: Optional[int] = None,
|
| 227 |
+
heads_share: bool = True,
|
| 228 |
+
block_length: Optional[int] = None,
|
| 229 |
+
proximal_bias: bool = False,
|
| 230 |
+
proximal_init: bool = False,
|
| 231 |
+
) -> None:
|
| 232 |
+
super().__init__()
|
| 233 |
+
assert channels % n_heads == 0
|
| 234 |
+
|
| 235 |
+
self.channels = channels
|
| 236 |
+
self.out_channels = out_channels
|
| 237 |
+
self.n_heads = n_heads
|
| 238 |
+
self.p_dropout = p_dropout
|
| 239 |
+
self.window_size = window_size
|
| 240 |
+
self.heads_share = heads_share
|
| 241 |
+
self.block_length = block_length
|
| 242 |
+
self.proximal_bias = proximal_bias
|
| 243 |
+
self.proximal_init = proximal_init
|
| 244 |
+
self.attn = None
|
| 245 |
+
|
| 246 |
+
self.k_channels = channels // n_heads
|
| 247 |
+
self.conv_q = nn.Conv1d(channels, channels, 1)
|
| 248 |
+
self.conv_k = nn.Conv1d(channels, channels, 1)
|
| 249 |
+
self.conv_v = nn.Conv1d(channels, channels, 1)
|
| 250 |
+
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
| 251 |
+
self.drop = nn.Dropout(p_dropout)
|
| 252 |
+
|
| 253 |
+
if window_size is not None:
|
| 254 |
+
n_heads_rel = 1 if heads_share else n_heads
|
| 255 |
+
rel_stddev = self.k_channels**-0.5
|
| 256 |
+
self.emb_rel_k = nn.Parameter(
|
| 257 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
| 258 |
+
* rel_stddev
|
| 259 |
+
)
|
| 260 |
+
self.emb_rel_v = nn.Parameter(
|
| 261 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
| 262 |
+
* rel_stddev
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
nn.init.xavier_uniform_(self.conv_q.weight)
|
| 266 |
+
nn.init.xavier_uniform_(self.conv_k.weight)
|
| 267 |
+
nn.init.xavier_uniform_(self.conv_v.weight)
|
| 268 |
+
if proximal_init:
|
| 269 |
+
with torch.no_grad():
|
| 270 |
+
self.conv_k.weight.copy_(self.conv_q.weight)
|
| 271 |
+
assert self.conv_k.bias is not None
|
| 272 |
+
assert self.conv_q.bias is not None
|
| 273 |
+
self.conv_k.bias.copy_(self.conv_q.bias)
|
| 274 |
+
|
| 275 |
+
def forward(
|
| 276 |
+
self, x: torch.Tensor, c: torch.Tensor, attn_mask: Optional[torch.Tensor] = None
|
| 277 |
+
) -> torch.Tensor:
|
| 278 |
+
q = self.conv_q(x)
|
| 279 |
+
k = self.conv_k(c)
|
| 280 |
+
v = self.conv_v(c)
|
| 281 |
+
|
| 282 |
+
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
| 283 |
+
|
| 284 |
+
x = self.conv_o(x)
|
| 285 |
+
return x
|
| 286 |
+
|
| 287 |
+
def attention(
|
| 288 |
+
self,
|
| 289 |
+
query: torch.Tensor,
|
| 290 |
+
key: torch.Tensor,
|
| 291 |
+
value: torch.Tensor,
|
| 292 |
+
mask: Optional[torch.Tensor] = None,
|
| 293 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 294 |
+
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
| 295 |
+
b, d, t_s, t_t = (*key.size(), query.size(2))
|
| 296 |
+
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
|
| 297 |
+
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
| 298 |
+
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
| 299 |
+
|
| 300 |
+
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
| 301 |
+
if self.window_size is not None:
|
| 302 |
+
assert (
|
| 303 |
+
t_s == t_t
|
| 304 |
+
), "Relative attention is only available for self-attention."
|
| 305 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
| 306 |
+
rel_logits = self._matmul_with_relative_keys(
|
| 307 |
+
query / math.sqrt(self.k_channels), key_relative_embeddings
|
| 308 |
+
)
|
| 309 |
+
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
| 310 |
+
scores = scores + scores_local
|
| 311 |
+
if self.proximal_bias:
|
| 312 |
+
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
| 313 |
+
scores = scores + self._attention_bias_proximal(t_s).to(
|
| 314 |
+
device=scores.device, dtype=scores.dtype
|
| 315 |
+
)
|
| 316 |
+
if mask is not None:
|
| 317 |
+
scores = scores.masked_fill(mask == 0, -1e4)
|
| 318 |
+
if self.block_length is not None:
|
| 319 |
+
assert (
|
| 320 |
+
t_s == t_t
|
| 321 |
+
), "Local attention is only available for self-attention."
|
| 322 |
+
block_mask = (
|
| 323 |
+
torch.ones_like(scores)
|
| 324 |
+
.triu(-self.block_length)
|
| 325 |
+
.tril(self.block_length)
|
| 326 |
+
)
|
| 327 |
+
scores = scores.masked_fill(block_mask == 0, -1e4)
|
| 328 |
+
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
| 329 |
+
p_attn = self.drop(p_attn)
|
| 330 |
+
output = torch.matmul(p_attn, value)
|
| 331 |
+
if self.window_size is not None:
|
| 332 |
+
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
| 333 |
+
value_relative_embeddings = self._get_relative_embeddings(
|
| 334 |
+
self.emb_rel_v, t_s
|
| 335 |
+
)
|
| 336 |
+
output = output + self._matmul_with_relative_values(
|
| 337 |
+
relative_weights, value_relative_embeddings
|
| 338 |
+
)
|
| 339 |
+
output = (
|
| 340 |
+
output.transpose(2, 3).contiguous().view(b, d, t_t)
|
| 341 |
+
) # [b, n_h, t_t, d_k] -> [b, d, t_t]
|
| 342 |
+
return output, p_attn
|
| 343 |
+
|
| 344 |
+
def _matmul_with_relative_values(
|
| 345 |
+
self, x: torch.Tensor, y: torch.Tensor
|
| 346 |
+
) -> torch.Tensor:
|
| 347 |
+
"""
|
| 348 |
+
x: [b, h, l, m]
|
| 349 |
+
y: [h or 1, m, d]
|
| 350 |
+
ret: [b, h, l, d]
|
| 351 |
+
"""
|
| 352 |
+
ret = torch.matmul(x, y.unsqueeze(0))
|
| 353 |
+
return ret
|
| 354 |
+
|
| 355 |
+
def _matmul_with_relative_keys(
|
| 356 |
+
self, x: torch.Tensor, y: torch.Tensor
|
| 357 |
+
) -> torch.Tensor:
|
| 358 |
+
"""
|
| 359 |
+
x: [b, h, l, d]
|
| 360 |
+
y: [h or 1, m, d]
|
| 361 |
+
ret: [b, h, l, m]
|
| 362 |
+
"""
|
| 363 |
+
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
| 364 |
+
return ret
|
| 365 |
+
|
| 366 |
+
def _get_relative_embeddings(
|
| 367 |
+
self, relative_embeddings: torch.Tensor, length: int
|
| 368 |
+
) -> torch.Tensor:
|
| 369 |
+
assert self.window_size is not None
|
| 370 |
+
2 * self.window_size + 1 # type: ignore
|
| 371 |
+
# Pad first before slice to avoid using cond ops.
|
| 372 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
| 373 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
| 374 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
| 375 |
+
if pad_length > 0:
|
| 376 |
+
padded_relative_embeddings = F.pad(
|
| 377 |
+
relative_embeddings,
|
| 378 |
+
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
|
| 379 |
+
)
|
| 380 |
+
else:
|
| 381 |
+
padded_relative_embeddings = relative_embeddings
|
| 382 |
+
used_relative_embeddings = padded_relative_embeddings[
|
| 383 |
+
:, slice_start_position:slice_end_position
|
| 384 |
+
]
|
| 385 |
+
return used_relative_embeddings
|
| 386 |
+
|
| 387 |
+
def _relative_position_to_absolute_position(self, x: torch.Tensor) -> torch.Tensor:
|
| 388 |
+
"""
|
| 389 |
+
x: [b, h, l, 2*l-1]
|
| 390 |
+
ret: [b, h, l, l]
|
| 391 |
+
"""
|
| 392 |
+
batch, heads, length, _ = x.size()
|
| 393 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
| 394 |
+
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
|
| 395 |
+
|
| 396 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
| 397 |
+
x_flat = x.view([batch, heads, length * 2 * length])
|
| 398 |
+
x_flat = F.pad(
|
| 399 |
+
x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
# Reshape and slice out the padded elements.
|
| 403 |
+
x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
|
| 404 |
+
:, :, :length, length - 1 :
|
| 405 |
+
]
|
| 406 |
+
return x_final
|
| 407 |
+
|
| 408 |
+
def _absolute_position_to_relative_position(self, x: torch.Tensor) -> torch.Tensor:
|
| 409 |
+
"""
|
| 410 |
+
x: [b, h, l, l]
|
| 411 |
+
ret: [b, h, l, 2*l-1]
|
| 412 |
+
"""
|
| 413 |
+
batch, heads, length, _ = x.size()
|
| 414 |
+
# pad along column
|
| 415 |
+
x = F.pad(
|
| 416 |
+
x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
|
| 417 |
+
)
|
| 418 |
+
x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
|
| 419 |
+
# add 0's in the beginning that will skew the elements after reshape
|
| 420 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
| 421 |
+
x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
|
| 422 |
+
return x_final
|
| 423 |
+
|
| 424 |
+
def _attention_bias_proximal(self, length: int) -> torch.Tensor:
|
| 425 |
+
"""Bias for self-attention to encourage attention to close positions.
|
| 426 |
+
Args:
|
| 427 |
+
length: an integer scalar.
|
| 428 |
+
Returns:
|
| 429 |
+
a Tensor with shape [1, 1, length, length]
|
| 430 |
+
"""
|
| 431 |
+
r = torch.arange(length, dtype=torch.float32)
|
| 432 |
+
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
| 433 |
+
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class FFN(nn.Module):
|
| 437 |
+
def __init__(
|
| 438 |
+
self,
|
| 439 |
+
in_channels: int,
|
| 440 |
+
out_channels: int,
|
| 441 |
+
filter_channels: int,
|
| 442 |
+
kernel_size: int,
|
| 443 |
+
p_dropout: float = 0.0,
|
| 444 |
+
activation: Optional[str] = None,
|
| 445 |
+
causal: bool = False,
|
| 446 |
+
) -> None:
|
| 447 |
+
super().__init__()
|
| 448 |
+
self.in_channels = in_channels
|
| 449 |
+
self.out_channels = out_channels
|
| 450 |
+
self.filter_channels = filter_channels
|
| 451 |
+
self.kernel_size = kernel_size
|
| 452 |
+
self.p_dropout = p_dropout
|
| 453 |
+
self.activation = activation
|
| 454 |
+
self.causal = causal
|
| 455 |
+
|
| 456 |
+
if causal:
|
| 457 |
+
self.padding = self._causal_padding
|
| 458 |
+
else:
|
| 459 |
+
self.padding = self._same_padding
|
| 460 |
+
|
| 461 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
| 462 |
+
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
| 463 |
+
self.drop = nn.Dropout(p_dropout)
|
| 464 |
+
|
| 465 |
+
def forward(self, x: torch.Tensor, x_mask: torch.Tensor) -> torch.Tensor:
|
| 466 |
+
x = self.conv_1(self.padding(x * x_mask))
|
| 467 |
+
if self.activation == "gelu":
|
| 468 |
+
x = x * torch.sigmoid(1.702 * x)
|
| 469 |
+
else:
|
| 470 |
+
x = torch.relu(x)
|
| 471 |
+
x = self.drop(x)
|
| 472 |
+
x = self.conv_2(self.padding(x * x_mask))
|
| 473 |
+
return x * x_mask
|
| 474 |
+
|
| 475 |
+
def _causal_padding(self, x: torch.Tensor) -> torch.Tensor:
|
| 476 |
+
if self.kernel_size == 1:
|
| 477 |
+
return x
|
| 478 |
+
pad_l = self.kernel_size - 1
|
| 479 |
+
pad_r = 0
|
| 480 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
| 481 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
| 482 |
+
return x
|
| 483 |
+
|
| 484 |
+
def _same_padding(self, x: torch.Tensor) -> torch.Tensor:
|
| 485 |
+
if self.kernel_size == 1:
|
| 486 |
+
return x
|
| 487 |
+
pad_l = (self.kernel_size - 1) // 2
|
| 488 |
+
pad_r = self.kernel_size // 2
|
| 489 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
| 490 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
| 491 |
+
return x
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/commons.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
以下に記述されている関数のコメントはリファクタリング時に GPT-4 に生成させたもので、
|
| 3 |
+
コードと完全に一致している保証はない。あくまで参考程度とすること。
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Any, Optional, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def init_weights(m: torch.nn.Module, mean: float = 0.0, std: float = 0.01) -> None:
|
| 13 |
+
"""
|
| 14 |
+
モジュールの重みを初期化する
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
m (torch.nn.Module): 重みを初期化する対象のモジュール
|
| 18 |
+
mean (float): 正規分布の平均
|
| 19 |
+
std (float): 正規分布の標準偏差
|
| 20 |
+
"""
|
| 21 |
+
classname = m.__class__.__name__
|
| 22 |
+
if classname.find("Conv") != -1:
|
| 23 |
+
m.weight.data.normal_(mean, std)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_padding(kernel_size: int, dilation: int = 1) -> int:
|
| 27 |
+
"""
|
| 28 |
+
カーネルサイズと膨張率からパディングの大きさを計算する
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
kernel_size (int): カーネルのサイズ
|
| 32 |
+
dilation (int): 膨張率
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
int: 計算されたパディングの大きさ
|
| 36 |
+
"""
|
| 37 |
+
return int((kernel_size * dilation - dilation) / 2)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def convert_pad_shape(pad_shape: list[list[Any]]) -> list[Any]:
|
| 41 |
+
"""
|
| 42 |
+
パディングの形状を変換する
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
pad_shape (list[list[Any]]): 変換前のパディングの形状
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
list[Any]: 変換後のパディングの形状
|
| 49 |
+
"""
|
| 50 |
+
layer = pad_shape[::-1]
|
| 51 |
+
new_pad_shape = [item for sublist in layer for item in sublist]
|
| 52 |
+
return new_pad_shape
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def intersperse(lst: list[Any], item: Any) -> list[Any]:
|
| 56 |
+
"""
|
| 57 |
+
リストの要素の間に特定のアイテムを挿入する
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
lst (list[Any]): 元のリスト
|
| 61 |
+
item (Any): 挿入するアイテム
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
list[Any]: 新しいリスト
|
| 65 |
+
"""
|
| 66 |
+
result = [item] * (len(lst) * 2 + 1)
|
| 67 |
+
result[1::2] = lst
|
| 68 |
+
return result
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def slice_segments(
|
| 72 |
+
x: torch.Tensor, ids_str: torch.Tensor, segment_size: int = 4
|
| 73 |
+
) -> torch.Tensor:
|
| 74 |
+
"""
|
| 75 |
+
テンソルからセグメントをスライスする
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
x (torch.Tensor): 入力テンソル
|
| 79 |
+
ids_str (torch.Tensor): スライスを開始するインデックス
|
| 80 |
+
segment_size (int, optional): スライスのサイズ (デフォルト: 4)
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
torch.Tensor: スライスされたセグメント
|
| 84 |
+
"""
|
| 85 |
+
gather_indices = ids_str.view(x.size(0), 1, 1).repeat(
|
| 86 |
+
1, x.size(1), 1
|
| 87 |
+
) + torch.arange(segment_size, device=x.device)
|
| 88 |
+
return torch.gather(x, 2, gather_indices)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def rand_slice_segments(
|
| 92 |
+
x: torch.Tensor, x_lengths: Optional[torch.Tensor] = None, segment_size: int = 4
|
| 93 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 94 |
+
"""
|
| 95 |
+
ランダムなセグメントをスライスする
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
x (torch.Tensor): 入力テンソル
|
| 99 |
+
x_lengths (Optional[torch.Tensor], optional): 各バッチの長さ (デフォルト: None)
|
| 100 |
+
segment_size (int, optional): スライスのサイズ (デフォルト: 4)
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
tuple[torch.Tensor, torch.Tensor]: スライスされたセグメントと開始インデックス
|
| 104 |
+
"""
|
| 105 |
+
b, d, t = x.size()
|
| 106 |
+
if x_lengths is None:
|
| 107 |
+
x_lengths = t # type: ignore
|
| 108 |
+
ids_str_max = torch.clamp(x_lengths - segment_size + 1, min=0) # type: ignore
|
| 109 |
+
ids_str = (torch.rand([b], device=x.device) * ids_str_max).to(dtype=torch.long)
|
| 110 |
+
ret = slice_segments(x, ids_str, segment_size)
|
| 111 |
+
return ret, ids_str
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def subsequent_mask(length: int) -> torch.Tensor:
|
| 115 |
+
"""
|
| 116 |
+
後続のマスクを生成する
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
length (int): マスクのサイズ
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
torch.Tensor: 生成されたマスク
|
| 123 |
+
"""
|
| 124 |
+
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
|
| 125 |
+
return mask
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@torch.jit.script # type: ignore
|
| 129 |
+
def fused_add_tanh_sigmoid_multiply(
|
| 130 |
+
input_a: torch.Tensor, input_b: torch.Tensor, n_channels: torch.Tensor
|
| 131 |
+
) -> torch.Tensor:
|
| 132 |
+
"""
|
| 133 |
+
加算、tanh、sigmoid の活性化関数を組み合わせた演算を行う
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
input_a (torch.Tensor): 入力テンソル A
|
| 137 |
+
input_b (torch.Tensor): 入力テンソル B
|
| 138 |
+
n_channels (torch.Tensor): チャネル数
|
| 139 |
+
|
| 140 |
+
Returns:
|
| 141 |
+
torch.Tensor: 演算結果
|
| 142 |
+
"""
|
| 143 |
+
n_channels_int = n_channels[0]
|
| 144 |
+
in_act = input_a + input_b
|
| 145 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
| 146 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
| 147 |
+
acts = t_act * s_act
|
| 148 |
+
return acts
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def sequence_mask(
|
| 152 |
+
length: torch.Tensor, max_length: Optional[int] = None
|
| 153 |
+
) -> torch.Tensor:
|
| 154 |
+
"""
|
| 155 |
+
シーケンスマスクを生成する
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
length (torch.Tensor): 各シーケンスの長さ
|
| 159 |
+
max_length (Optional[int]): 最大のシーケンス長さ。指定されていない場合は length の最大値を使用
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
torch.Tensor: 生成されたシーケンスマスク
|
| 163 |
+
"""
|
| 164 |
+
if max_length is None:
|
| 165 |
+
max_length = length.max() # type: ignore
|
| 166 |
+
x = torch.arange(max_length, dtype=length.dtype, device=length.device) # type: ignore
|
| 167 |
+
return x.unsqueeze(0) < length.unsqueeze(1)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def generate_path(duration: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
|
| 171 |
+
"""
|
| 172 |
+
パスを生成する
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
duration (torch.Tensor): 各時間ステップの持続時間
|
| 176 |
+
mask (torch.Tensor): マスクテンソル
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
torch.Tensor: 生成されたパス
|
| 180 |
+
"""
|
| 181 |
+
b, _, t_y, t_x = mask.shape
|
| 182 |
+
cum_duration = torch.cumsum(duration, -1)
|
| 183 |
+
|
| 184 |
+
cum_duration_flat = cum_duration.view(b * t_x)
|
| 185 |
+
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
|
| 186 |
+
path = path.view(b, t_x, t_y)
|
| 187 |
+
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
|
| 188 |
+
path = path.unsqueeze(1).transpose(2, 3) * mask
|
| 189 |
+
return path
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def clip_grad_value_(
|
| 193 |
+
parameters: Union[torch.Tensor, list[torch.Tensor]],
|
| 194 |
+
clip_value: Optional[float],
|
| 195 |
+
norm_type: float = 2.0,
|
| 196 |
+
) -> float:
|
| 197 |
+
"""
|
| 198 |
+
勾配の値をクリップする
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
parameters (Union[torch.Tensor, list[torch.Tensor]]): クリップするパラメータ
|
| 202 |
+
clip_value (Optional[float]): クリップする値。None の場合はクリップしない
|
| 203 |
+
norm_type (float): ノルムの種類
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
float: 総ノルム
|
| 207 |
+
"""
|
| 208 |
+
if isinstance(parameters, torch.Tensor):
|
| 209 |
+
parameters = [parameters]
|
| 210 |
+
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
| 211 |
+
norm_type = float(norm_type)
|
| 212 |
+
if clip_value is not None:
|
| 213 |
+
clip_value = float(clip_value)
|
| 214 |
+
|
| 215 |
+
total_norm = 0.0
|
| 216 |
+
for p in parameters:
|
| 217 |
+
assert p.grad is not None
|
| 218 |
+
param_norm = p.grad.data.norm(norm_type)
|
| 219 |
+
total_norm += param_norm.item() ** norm_type
|
| 220 |
+
if clip_value is not None:
|
| 221 |
+
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
| 222 |
+
total_norm = total_norm ** (1.0 / norm_type)
|
| 223 |
+
return total_norm
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/hyper_parameters.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Style-Bert-VITS2 モデルのハイパーパラメータを表す Pydantic モデル。
|
| 3 |
+
デフォルト値は configs/config_jp_extra.json 内の定義と概ね同一で、
|
| 4 |
+
万が一ロードした config.json に存在しないキーがあった際のフェイルセーフとして適用される。
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Optional, Union
|
| 9 |
+
|
| 10 |
+
from pydantic import BaseModel, ConfigDict
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class HyperParametersTrain(BaseModel):
|
| 14 |
+
log_interval: int = 200
|
| 15 |
+
eval_interval: int = 1000
|
| 16 |
+
seed: int = 42
|
| 17 |
+
epochs: int = 1000
|
| 18 |
+
learning_rate: float = 0.0001
|
| 19 |
+
betas: tuple[float, float] = (0.8, 0.99)
|
| 20 |
+
eps: float = 1e-9
|
| 21 |
+
batch_size: int = 2
|
| 22 |
+
bf16_run: bool = False
|
| 23 |
+
fp16_run: bool = False
|
| 24 |
+
lr_decay: float = 0.99996
|
| 25 |
+
segment_size: int = 16384
|
| 26 |
+
init_lr_ratio: int = 1
|
| 27 |
+
warmup_epochs: int = 0
|
| 28 |
+
c_mel: int = 45
|
| 29 |
+
c_kl: float = 1.0
|
| 30 |
+
c_commit: int = 100
|
| 31 |
+
skip_optimizer: bool = False
|
| 32 |
+
freeze_ZH_bert: bool = False
|
| 33 |
+
freeze_JP_bert: bool = False
|
| 34 |
+
freeze_EN_bert: bool = False
|
| 35 |
+
freeze_emo: bool = False
|
| 36 |
+
freeze_style: bool = False
|
| 37 |
+
freeze_decoder: bool = False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class HyperParametersData(BaseModel):
|
| 41 |
+
use_jp_extra: bool = True
|
| 42 |
+
training_files: str = "Data/Dummy/train.list"
|
| 43 |
+
validation_files: str = "Data/Dummy/val.list"
|
| 44 |
+
max_wav_value: float = 32768.0
|
| 45 |
+
sampling_rate: int = 44100
|
| 46 |
+
filter_length: int = 2048
|
| 47 |
+
hop_length: int = 512
|
| 48 |
+
win_length: int = 2048
|
| 49 |
+
n_mel_channels: int = 128
|
| 50 |
+
mel_fmin: float = 0.0
|
| 51 |
+
mel_fmax: Optional[float] = None
|
| 52 |
+
add_blank: bool = True
|
| 53 |
+
n_speakers: int = 1
|
| 54 |
+
cleaned_text: bool = True
|
| 55 |
+
spk2id: dict[str, int] = {
|
| 56 |
+
"Dummy": 0,
|
| 57 |
+
}
|
| 58 |
+
num_styles: int = 1
|
| 59 |
+
style2id: dict[str, int] = {
|
| 60 |
+
"Neutral": 0,
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class HyperParametersModelSLM(BaseModel):
|
| 65 |
+
model: str = "./slm/wavlm-base-plus"
|
| 66 |
+
sr: int = 16000
|
| 67 |
+
hidden: int = 768
|
| 68 |
+
nlayers: int = 13
|
| 69 |
+
initial_channel: int = 64
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class HyperParametersModel(BaseModel):
|
| 73 |
+
use_spk_conditioned_encoder: bool = True
|
| 74 |
+
use_noise_scaled_mas: bool = True
|
| 75 |
+
use_mel_posterior_encoder: bool = False
|
| 76 |
+
use_duration_discriminator: bool = False
|
| 77 |
+
use_wavlm_discriminator: bool = True
|
| 78 |
+
inter_channels: int = 192
|
| 79 |
+
hidden_channels: int = 192
|
| 80 |
+
filter_channels: int = 768
|
| 81 |
+
n_heads: int = 2
|
| 82 |
+
n_layers: int = 6
|
| 83 |
+
kernel_size: int = 3
|
| 84 |
+
p_dropout: float = 0.1
|
| 85 |
+
resblock: str = "1"
|
| 86 |
+
resblock_kernel_sizes: list[int] = [3, 7, 11]
|
| 87 |
+
resblock_dilation_sizes: list[list[int]] = [
|
| 88 |
+
[1, 3, 5],
|
| 89 |
+
[1, 3, 5],
|
| 90 |
+
[1, 3, 5],
|
| 91 |
+
]
|
| 92 |
+
upsample_rates: list[int] = [8, 8, 2, 2, 2]
|
| 93 |
+
upsample_initial_channel: int = 512
|
| 94 |
+
upsample_kernel_sizes: list[int] = [16, 16, 8, 2, 2]
|
| 95 |
+
n_layers_q: int = 3
|
| 96 |
+
use_spectral_norm: bool = False
|
| 97 |
+
gin_channels: int = 512
|
| 98 |
+
slm: HyperParametersModelSLM = HyperParametersModelSLM()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class HyperParameters(BaseModel):
|
| 102 |
+
model_name: str = "Dummy"
|
| 103 |
+
version: str = "2.0-JP-Extra"
|
| 104 |
+
train: HyperParametersTrain = HyperParametersTrain()
|
| 105 |
+
data: HyperParametersData = HyperParametersData()
|
| 106 |
+
model: HyperParametersModel = HyperParametersModel()
|
| 107 |
+
|
| 108 |
+
# 以下は学習時にのみ動的に設定されるパラメータ (通常 config.json には存在しない)
|
| 109 |
+
model_dir: Optional[str] = None
|
| 110 |
+
speedup: bool = False
|
| 111 |
+
repo_id: Optional[str] = None
|
| 112 |
+
|
| 113 |
+
# model_ 以下を Pydantic の保護対象から除外する
|
| 114 |
+
model_config = ConfigDict(protected_namespaces=())
|
| 115 |
+
|
| 116 |
+
@staticmethod
|
| 117 |
+
def load_from_json(json_path: Union[str, Path]) -> "HyperParameters":
|
| 118 |
+
"""
|
| 119 |
+
与えられた JSON ファイルからハイパーパラメータを読み込む。
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
json_path (Union[str, Path]): JSON ファイルのパス
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
HyperParameters: ハイパーパラメータ
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
with open(json_path, encoding="utf-8") as f:
|
| 129 |
+
return HyperParameters.model_validate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bert_vits2.logging import logger
|
| 8 |
+
from style_bert_vits2.models import commons, utils
|
| 9 |
+
from style_bert_vits2.models.hyper_parameters import HyperParameters
|
| 10 |
+
from style_bert_vits2.models.models import SynthesizerTrn
|
| 11 |
+
from style_bert_vits2.models.models_jp_extra import (
|
| 12 |
+
SynthesizerTrn as SynthesizerTrnJPExtra,
|
| 13 |
+
)
|
| 14 |
+
from style_bert_vits2.nlp import (
|
| 15 |
+
clean_text,
|
| 16 |
+
cleaned_text_to_sequence,
|
| 17 |
+
extract_bert_feature,
|
| 18 |
+
)
|
| 19 |
+
from style_bert_vits2.nlp.symbols import SYMBOLS
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_net_g(model_path: str, version: str, device: str, hps: HyperParameters):
|
| 23 |
+
if version.endswith("JP-Extra"):
|
| 24 |
+
logger.info("Using JP-Extra model")
|
| 25 |
+
net_g = SynthesizerTrnJPExtra(
|
| 26 |
+
n_vocab=len(SYMBOLS),
|
| 27 |
+
spec_channels=hps.data.filter_length // 2 + 1,
|
| 28 |
+
segment_size=hps.train.segment_size // hps.data.hop_length,
|
| 29 |
+
n_speakers=hps.data.n_speakers,
|
| 30 |
+
# hps.model 以下のすべての値を引数に渡す
|
| 31 |
+
use_spk_conditioned_encoder=hps.model.use_spk_conditioned_encoder,
|
| 32 |
+
use_noise_scaled_mas=hps.model.use_noise_scaled_mas,
|
| 33 |
+
use_mel_posterior_encoder=hps.model.use_mel_posterior_encoder,
|
| 34 |
+
use_duration_discriminator=hps.model.use_duration_discriminator,
|
| 35 |
+
use_wavlm_discriminator=hps.model.use_wavlm_discriminator,
|
| 36 |
+
inter_channels=hps.model.inter_channels,
|
| 37 |
+
hidden_channels=hps.model.hidden_channels,
|
| 38 |
+
filter_channels=hps.model.filter_channels,
|
| 39 |
+
n_heads=hps.model.n_heads,
|
| 40 |
+
n_layers=hps.model.n_layers,
|
| 41 |
+
kernel_size=hps.model.kernel_size,
|
| 42 |
+
p_dropout=hps.model.p_dropout,
|
| 43 |
+
resblock=hps.model.resblock,
|
| 44 |
+
resblock_kernel_sizes=hps.model.resblock_kernel_sizes,
|
| 45 |
+
resblock_dilation_sizes=hps.model.resblock_dilation_sizes,
|
| 46 |
+
upsample_rates=hps.model.upsample_rates,
|
| 47 |
+
upsample_initial_channel=hps.model.upsample_initial_channel,
|
| 48 |
+
upsample_kernel_sizes=hps.model.upsample_kernel_sizes,
|
| 49 |
+
n_layers_q=hps.model.n_layers_q,
|
| 50 |
+
use_spectral_norm=hps.model.use_spectral_norm,
|
| 51 |
+
gin_channels=hps.model.gin_channels,
|
| 52 |
+
slm=hps.model.slm,
|
| 53 |
+
).to(device)
|
| 54 |
+
else:
|
| 55 |
+
logger.info("Using normal model")
|
| 56 |
+
net_g = SynthesizerTrn(
|
| 57 |
+
n_vocab=len(SYMBOLS),
|
| 58 |
+
spec_channels=hps.data.filter_length // 2 + 1,
|
| 59 |
+
segment_size=hps.train.segment_size // hps.data.hop_length,
|
| 60 |
+
n_speakers=hps.data.n_speakers,
|
| 61 |
+
# hps.model 以下のすべての値を引数に渡す
|
| 62 |
+
use_spk_conditioned_encoder=hps.model.use_spk_conditioned_encoder,
|
| 63 |
+
use_noise_scaled_mas=hps.model.use_noise_scaled_mas,
|
| 64 |
+
use_mel_posterior_encoder=hps.model.use_mel_posterior_encoder,
|
| 65 |
+
use_duration_discriminator=hps.model.use_duration_discriminator,
|
| 66 |
+
use_wavlm_discriminator=hps.model.use_wavlm_discriminator,
|
| 67 |
+
inter_channels=hps.model.inter_channels,
|
| 68 |
+
hidden_channels=hps.model.hidden_channels,
|
| 69 |
+
filter_channels=hps.model.filter_channels,
|
| 70 |
+
n_heads=hps.model.n_heads,
|
| 71 |
+
n_layers=hps.model.n_layers,
|
| 72 |
+
kernel_size=hps.model.kernel_size,
|
| 73 |
+
p_dropout=hps.model.p_dropout,
|
| 74 |
+
resblock=hps.model.resblock,
|
| 75 |
+
resblock_kernel_sizes=hps.model.resblock_kernel_sizes,
|
| 76 |
+
resblock_dilation_sizes=hps.model.resblock_dilation_sizes,
|
| 77 |
+
upsample_rates=hps.model.upsample_rates,
|
| 78 |
+
upsample_initial_channel=hps.model.upsample_initial_channel,
|
| 79 |
+
upsample_kernel_sizes=hps.model.upsample_kernel_sizes,
|
| 80 |
+
n_layers_q=hps.model.n_layers_q,
|
| 81 |
+
use_spectral_norm=hps.model.use_spectral_norm,
|
| 82 |
+
gin_channels=hps.model.gin_channels,
|
| 83 |
+
slm=hps.model.slm,
|
| 84 |
+
).to(device)
|
| 85 |
+
net_g.state_dict()
|
| 86 |
+
_ = net_g.eval()
|
| 87 |
+
if model_path.endswith(".pth") or model_path.endswith(".pt"):
|
| 88 |
+
_ = utils.checkpoints.load_checkpoint(
|
| 89 |
+
model_path, net_g, None, skip_optimizer=True
|
| 90 |
+
)
|
| 91 |
+
elif model_path.endswith(".safetensors"):
|
| 92 |
+
_ = utils.safetensors.load_safetensors(model_path, net_g, True)
|
| 93 |
+
else:
|
| 94 |
+
raise ValueError(f"Unknown model format: {model_path}")
|
| 95 |
+
return net_g
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def get_text(
|
| 99 |
+
text: str,
|
| 100 |
+
language_str: Languages,
|
| 101 |
+
hps: HyperParameters,
|
| 102 |
+
device: str,
|
| 103 |
+
assist_text: Optional[str] = None,
|
| 104 |
+
assist_text_weight: float = 0.7,
|
| 105 |
+
given_phone: Optional[list[str]] = None,
|
| 106 |
+
given_tone: Optional[list[int]] = None,
|
| 107 |
+
):
|
| 108 |
+
use_jp_extra = hps.version.endswith("JP-Extra")
|
| 109 |
+
# 推論時のみ呼び出されるので、raise_yomi_error は False に設定
|
| 110 |
+
norm_text, phone, tone, word2ph = clean_text(
|
| 111 |
+
text,
|
| 112 |
+
language_str,
|
| 113 |
+
use_jp_extra=use_jp_extra,
|
| 114 |
+
raise_yomi_error=False,
|
| 115 |
+
)
|
| 116 |
+
# phone と tone の両方が与えられた場合はそれを使う
|
| 117 |
+
if given_phone is not None and given_tone is not None:
|
| 118 |
+
# 指定された phone と指定された tone 両方の長さが一致していなければならない
|
| 119 |
+
if len(given_phone) != len(given_tone):
|
| 120 |
+
raise InvalidPhoneError(
|
| 121 |
+
f"Length of given_phone ({len(given_phone)}) != length of given_tone ({len(given_tone)})"
|
| 122 |
+
)
|
| 123 |
+
# 与えられた音素数と pyopenjtalk で生成した読みの音素数が一致しない
|
| 124 |
+
if len(given_phone) != sum(word2ph):
|
| 125 |
+
# 日本語の場合、len(given_phone) と sum(word2ph) が一致するように word2ph を適切に調整する
|
| 126 |
+
# 他の言語は word2ph の調整方法が思いつかないのでエラー
|
| 127 |
+
if language_str == Languages.JP:
|
| 128 |
+
from style_bert_vits2.nlp.japanese.g2p import adjust_word2ph
|
| 129 |
+
|
| 130 |
+
word2ph = adjust_word2ph(word2ph, phone, given_phone)
|
| 131 |
+
# 上記処理により word2ph の合計が given_phone の長さと一致するはず
|
| 132 |
+
# それでも一致しない場合、大半は読み上げテキストと given_phone が著しく乖離していて調整し切れなかったことを意味する
|
| 133 |
+
if len(given_phone) != sum(word2ph):
|
| 134 |
+
raise InvalidPhoneError(
|
| 135 |
+
f"Length of given_phone ({len(given_phone)}) != sum of word2ph ({sum(word2ph)})"
|
| 136 |
+
)
|
| 137 |
+
else:
|
| 138 |
+
raise InvalidPhoneError(
|
| 139 |
+
f"Length of given_phone ({len(given_phone)}) != sum of word2ph ({sum(word2ph)})"
|
| 140 |
+
)
|
| 141 |
+
phone = given_phone
|
| 142 |
+
# 生成あるいは指定された phone と指定された tone 両方の長さが一致していなければならない
|
| 143 |
+
if len(phone) != len(given_tone):
|
| 144 |
+
raise InvalidToneError(
|
| 145 |
+
f"Length of phone ({len(phone)}) != length of given_tone ({len(given_tone)})"
|
| 146 |
+
)
|
| 147 |
+
tone = given_tone
|
| 148 |
+
# tone だけが与えられた場合は clean_text() で生成した phone と合わせて使う
|
| 149 |
+
elif given_tone is not None:
|
| 150 |
+
# 生成した phone と指定された tone 両方の長さが一致していなければならない
|
| 151 |
+
if len(phone) != len(given_tone):
|
| 152 |
+
raise InvalidToneError(
|
| 153 |
+
f"Length of phone ({len(phone)}) != length of given_tone ({len(given_tone)})"
|
| 154 |
+
)
|
| 155 |
+
tone = given_tone
|
| 156 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
| 157 |
+
|
| 158 |
+
if hps.data.add_blank:
|
| 159 |
+
phone = commons.intersperse(phone, 0)
|
| 160 |
+
tone = commons.intersperse(tone, 0)
|
| 161 |
+
language = commons.intersperse(language, 0)
|
| 162 |
+
for i in range(len(word2ph)):
|
| 163 |
+
word2ph[i] = word2ph[i] * 2
|
| 164 |
+
word2ph[0] += 1
|
| 165 |
+
bert_ori = extract_bert_feature(
|
| 166 |
+
norm_text,
|
| 167 |
+
word2ph,
|
| 168 |
+
language_str,
|
| 169 |
+
device,
|
| 170 |
+
assist_text,
|
| 171 |
+
assist_text_weight,
|
| 172 |
+
)
|
| 173 |
+
del word2ph
|
| 174 |
+
assert bert_ori.shape[-1] == len(phone), phone
|
| 175 |
+
|
| 176 |
+
if language_str == Languages.ZH:
|
| 177 |
+
bert = bert_ori
|
| 178 |
+
ja_bert = torch.zeros(1024, len(phone))
|
| 179 |
+
en_bert = torch.zeros(1024, len(phone))
|
| 180 |
+
elif language_str == Languages.JP:
|
| 181 |
+
bert = torch.zeros(1024, len(phone))
|
| 182 |
+
ja_bert = bert_ori
|
| 183 |
+
en_bert = torch.zeros(1024, len(phone))
|
| 184 |
+
elif language_str == Languages.EN:
|
| 185 |
+
bert = torch.zeros(1024, len(phone))
|
| 186 |
+
ja_bert = torch.zeros(1024, len(phone))
|
| 187 |
+
en_bert = bert_ori
|
| 188 |
+
else:
|
| 189 |
+
raise ValueError("language_str should be ZH, JP or EN")
|
| 190 |
+
|
| 191 |
+
assert bert.shape[-1] == len(
|
| 192 |
+
phone
|
| 193 |
+
), f"Bert seq len {bert.shape[-1]} != {len(phone)}"
|
| 194 |
+
|
| 195 |
+
phone = torch.LongTensor(phone)
|
| 196 |
+
tone = torch.LongTensor(tone)
|
| 197 |
+
language = torch.LongTensor(language)
|
| 198 |
+
return bert, ja_bert, en_bert, phone, tone, language
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def infer(
|
| 202 |
+
text: str,
|
| 203 |
+
style_vec: NDArray[Any],
|
| 204 |
+
sdp_ratio: float,
|
| 205 |
+
noise_scale: float,
|
| 206 |
+
noise_scale_w: float,
|
| 207 |
+
length_scale: float,
|
| 208 |
+
sid: int, # In the original Bert-VITS2, its speaker_name: str, but here it's id
|
| 209 |
+
language: Languages,
|
| 210 |
+
hps: HyperParameters,
|
| 211 |
+
net_g: Union[SynthesizerTrn, SynthesizerTrnJPExtra],
|
| 212 |
+
device: str,
|
| 213 |
+
skip_start: bool = False,
|
| 214 |
+
skip_end: bool = False,
|
| 215 |
+
assist_text: Optional[str] = None,
|
| 216 |
+
assist_text_weight: float = 0.7,
|
| 217 |
+
given_phone: Optional[list[str]] = None,
|
| 218 |
+
given_tone: Optional[list[int]] = None,
|
| 219 |
+
):
|
| 220 |
+
is_jp_extra = hps.version.endswith("JP-Extra")
|
| 221 |
+
bert, ja_bert, en_bert, phones, tones, lang_ids = get_text(
|
| 222 |
+
text,
|
| 223 |
+
language,
|
| 224 |
+
hps,
|
| 225 |
+
device,
|
| 226 |
+
assist_text=assist_text,
|
| 227 |
+
assist_text_weight=assist_text_weight,
|
| 228 |
+
given_phone=given_phone,
|
| 229 |
+
given_tone=given_tone,
|
| 230 |
+
)
|
| 231 |
+
if skip_start:
|
| 232 |
+
phones = phones[3:]
|
| 233 |
+
tones = tones[3:]
|
| 234 |
+
lang_ids = lang_ids[3:]
|
| 235 |
+
bert = bert[:, 3:]
|
| 236 |
+
ja_bert = ja_bert[:, 3:]
|
| 237 |
+
en_bert = en_bert[:, 3:]
|
| 238 |
+
if skip_end:
|
| 239 |
+
phones = phones[:-2]
|
| 240 |
+
tones = tones[:-2]
|
| 241 |
+
lang_ids = lang_ids[:-2]
|
| 242 |
+
bert = bert[:, :-2]
|
| 243 |
+
ja_bert = ja_bert[:, :-2]
|
| 244 |
+
en_bert = en_bert[:, :-2]
|
| 245 |
+
with torch.no_grad():
|
| 246 |
+
x_tst = phones.to(device).unsqueeze(0)
|
| 247 |
+
tones = tones.to(device).unsqueeze(0)
|
| 248 |
+
lang_ids = lang_ids.to(device).unsqueeze(0)
|
| 249 |
+
bert = bert.to(device).unsqueeze(0)
|
| 250 |
+
ja_bert = ja_bert.to(device).unsqueeze(0)
|
| 251 |
+
en_bert = en_bert.to(device).unsqueeze(0)
|
| 252 |
+
x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
|
| 253 |
+
style_vec_tensor = torch.from_numpy(style_vec).to(device).unsqueeze(0)
|
| 254 |
+
del phones
|
| 255 |
+
sid_tensor = torch.LongTensor([sid]).to(device)
|
| 256 |
+
if is_jp_extra:
|
| 257 |
+
output = cast(SynthesizerTrnJPExtra, net_g).infer(
|
| 258 |
+
x_tst,
|
| 259 |
+
x_tst_lengths,
|
| 260 |
+
sid_tensor,
|
| 261 |
+
tones,
|
| 262 |
+
lang_ids,
|
| 263 |
+
ja_bert,
|
| 264 |
+
style_vec=style_vec_tensor,
|
| 265 |
+
sdp_ratio=sdp_ratio,
|
| 266 |
+
noise_scale=noise_scale,
|
| 267 |
+
noise_scale_w=noise_scale_w,
|
| 268 |
+
length_scale=length_scale,
|
| 269 |
+
)
|
| 270 |
+
else:
|
| 271 |
+
output = cast(SynthesizerTrn, net_g).infer(
|
| 272 |
+
x_tst,
|
| 273 |
+
x_tst_lengths,
|
| 274 |
+
sid_tensor,
|
| 275 |
+
tones,
|
| 276 |
+
lang_ids,
|
| 277 |
+
bert,
|
| 278 |
+
ja_bert,
|
| 279 |
+
en_bert,
|
| 280 |
+
style_vec=style_vec_tensor,
|
| 281 |
+
sdp_ratio=sdp_ratio,
|
| 282 |
+
noise_scale=noise_scale,
|
| 283 |
+
noise_scale_w=noise_scale_w,
|
| 284 |
+
length_scale=length_scale,
|
| 285 |
+
)
|
| 286 |
+
audio = output[0][0, 0].data.cpu().float().numpy()
|
| 287 |
+
del (
|
| 288 |
+
x_tst,
|
| 289 |
+
tones,
|
| 290 |
+
lang_ids,
|
| 291 |
+
bert,
|
| 292 |
+
x_tst_lengths,
|
| 293 |
+
sid_tensor,
|
| 294 |
+
ja_bert,
|
| 295 |
+
en_bert,
|
| 296 |
+
style_vec,
|
| 297 |
+
) # , emo
|
| 298 |
+
if torch.cuda.is_available():
|
| 299 |
+
torch.cuda.empty_cache()
|
| 300 |
+
return audio
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class InvalidPhoneError(ValueError):
|
| 304 |
+
pass
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class InvalidToneError(ValueError):
|
| 308 |
+
pass
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/models.py
ADDED
|
@@ -0,0 +1,1102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
from torch.nn import Conv1d, Conv2d, ConvTranspose1d
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
|
| 9 |
+
|
| 10 |
+
from style_bert_vits2.models import attentions, commons, modules, monotonic_alignment
|
| 11 |
+
from style_bert_vits2.nlp.symbols import NUM_LANGUAGES, NUM_TONES, SYMBOLS
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class DurationDiscriminator(nn.Module): # vits2
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
in_channels: int,
|
| 18 |
+
filter_channels: int,
|
| 19 |
+
kernel_size: int,
|
| 20 |
+
p_dropout: float,
|
| 21 |
+
gin_channels: int = 0,
|
| 22 |
+
) -> None:
|
| 23 |
+
super().__init__()
|
| 24 |
+
|
| 25 |
+
self.in_channels = in_channels
|
| 26 |
+
self.filter_channels = filter_channels
|
| 27 |
+
self.kernel_size = kernel_size
|
| 28 |
+
self.p_dropout = p_dropout
|
| 29 |
+
self.gin_channels = gin_channels
|
| 30 |
+
|
| 31 |
+
self.drop = nn.Dropout(p_dropout)
|
| 32 |
+
self.conv_1 = nn.Conv1d(
|
| 33 |
+
in_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 34 |
+
)
|
| 35 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
| 36 |
+
self.conv_2 = nn.Conv1d(
|
| 37 |
+
filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 38 |
+
)
|
| 39 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
| 40 |
+
self.dur_proj = nn.Conv1d(1, filter_channels, 1)
|
| 41 |
+
|
| 42 |
+
self.pre_out_conv_1 = nn.Conv1d(
|
| 43 |
+
2 * filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 44 |
+
)
|
| 45 |
+
self.pre_out_norm_1 = modules.LayerNorm(filter_channels)
|
| 46 |
+
self.pre_out_conv_2 = nn.Conv1d(
|
| 47 |
+
filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 48 |
+
)
|
| 49 |
+
self.pre_out_norm_2 = modules.LayerNorm(filter_channels)
|
| 50 |
+
|
| 51 |
+
if gin_channels != 0:
|
| 52 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
| 53 |
+
|
| 54 |
+
self.output_layer = nn.Sequential(nn.Linear(filter_channels, 1), nn.Sigmoid())
|
| 55 |
+
|
| 56 |
+
def forward_probability(
|
| 57 |
+
self,
|
| 58 |
+
x: torch.Tensor,
|
| 59 |
+
x_mask: torch.Tensor,
|
| 60 |
+
dur: torch.Tensor,
|
| 61 |
+
g: Optional[torch.Tensor] = None,
|
| 62 |
+
) -> torch.Tensor:
|
| 63 |
+
dur = self.dur_proj(dur)
|
| 64 |
+
x = torch.cat([x, dur], dim=1)
|
| 65 |
+
x = self.pre_out_conv_1(x * x_mask)
|
| 66 |
+
x = torch.relu(x)
|
| 67 |
+
x = self.pre_out_norm_1(x)
|
| 68 |
+
x = self.drop(x)
|
| 69 |
+
x = self.pre_out_conv_2(x * x_mask)
|
| 70 |
+
x = torch.relu(x)
|
| 71 |
+
x = self.pre_out_norm_2(x)
|
| 72 |
+
x = self.drop(x)
|
| 73 |
+
x = x * x_mask
|
| 74 |
+
x = x.transpose(1, 2)
|
| 75 |
+
output_prob = self.output_layer(x)
|
| 76 |
+
return output_prob
|
| 77 |
+
|
| 78 |
+
def forward(
|
| 79 |
+
self,
|
| 80 |
+
x: torch.Tensor,
|
| 81 |
+
x_mask: torch.Tensor,
|
| 82 |
+
dur_r: torch.Tensor,
|
| 83 |
+
dur_hat: torch.Tensor,
|
| 84 |
+
g: Optional[torch.Tensor] = None,
|
| 85 |
+
) -> list[torch.Tensor]:
|
| 86 |
+
x = torch.detach(x)
|
| 87 |
+
if g is not None:
|
| 88 |
+
g = torch.detach(g)
|
| 89 |
+
x = x + self.cond(g)
|
| 90 |
+
x = self.conv_1(x * x_mask)
|
| 91 |
+
x = torch.relu(x)
|
| 92 |
+
x = self.norm_1(x)
|
| 93 |
+
x = self.drop(x)
|
| 94 |
+
x = self.conv_2(x * x_mask)
|
| 95 |
+
x = torch.relu(x)
|
| 96 |
+
x = self.norm_2(x)
|
| 97 |
+
x = self.drop(x)
|
| 98 |
+
|
| 99 |
+
output_probs = []
|
| 100 |
+
for dur in [dur_r, dur_hat]:
|
| 101 |
+
output_prob = self.forward_probability(x, x_mask, dur, g)
|
| 102 |
+
output_probs.append(output_prob)
|
| 103 |
+
|
| 104 |
+
return output_probs
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class TransformerCouplingBlock(nn.Module):
|
| 108 |
+
def __init__(
|
| 109 |
+
self,
|
| 110 |
+
channels: int,
|
| 111 |
+
hidden_channels: int,
|
| 112 |
+
filter_channels: int,
|
| 113 |
+
n_heads: int,
|
| 114 |
+
n_layers: int,
|
| 115 |
+
kernel_size: int,
|
| 116 |
+
p_dropout: float,
|
| 117 |
+
n_flows: int = 4,
|
| 118 |
+
gin_channels: int = 0,
|
| 119 |
+
share_parameter: bool = False,
|
| 120 |
+
) -> None:
|
| 121 |
+
super().__init__()
|
| 122 |
+
self.channels = channels
|
| 123 |
+
self.hidden_channels = hidden_channels
|
| 124 |
+
self.kernel_size = kernel_size
|
| 125 |
+
self.n_layers = n_layers
|
| 126 |
+
self.n_flows = n_flows
|
| 127 |
+
self.gin_channels = gin_channels
|
| 128 |
+
|
| 129 |
+
self.flows = nn.ModuleList()
|
| 130 |
+
|
| 131 |
+
self.wn = (
|
| 132 |
+
# attentions.FFT(
|
| 133 |
+
# hidden_channels,
|
| 134 |
+
# filter_channels,
|
| 135 |
+
# n_heads,
|
| 136 |
+
# n_layers,
|
| 137 |
+
# kernel_size,
|
| 138 |
+
# p_dropout,
|
| 139 |
+
# isflow=True,
|
| 140 |
+
# gin_channels=self.gin_channels,
|
| 141 |
+
# )
|
| 142 |
+
None
|
| 143 |
+
if share_parameter
|
| 144 |
+
else None
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
for i in range(n_flows):
|
| 148 |
+
self.flows.append(
|
| 149 |
+
modules.TransformerCouplingLayer(
|
| 150 |
+
channels,
|
| 151 |
+
hidden_channels,
|
| 152 |
+
kernel_size,
|
| 153 |
+
n_layers,
|
| 154 |
+
n_heads,
|
| 155 |
+
p_dropout,
|
| 156 |
+
filter_channels,
|
| 157 |
+
mean_only=True,
|
| 158 |
+
wn_sharing_parameter=self.wn,
|
| 159 |
+
gin_channels=self.gin_channels,
|
| 160 |
+
)
|
| 161 |
+
)
|
| 162 |
+
self.flows.append(modules.Flip())
|
| 163 |
+
|
| 164 |
+
def forward(
|
| 165 |
+
self,
|
| 166 |
+
x: torch.Tensor,
|
| 167 |
+
x_mask: torch.Tensor,
|
| 168 |
+
g: Optional[torch.Tensor] = None,
|
| 169 |
+
reverse: bool = False,
|
| 170 |
+
) -> torch.Tensor:
|
| 171 |
+
if not reverse:
|
| 172 |
+
for flow in self.flows:
|
| 173 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
| 174 |
+
else:
|
| 175 |
+
for flow in reversed(self.flows):
|
| 176 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
| 177 |
+
return x
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class StochasticDurationPredictor(nn.Module):
|
| 181 |
+
def __init__(
|
| 182 |
+
self,
|
| 183 |
+
in_channels: int,
|
| 184 |
+
filter_channels: int,
|
| 185 |
+
kernel_size: int,
|
| 186 |
+
p_dropout: float,
|
| 187 |
+
n_flows: int = 4,
|
| 188 |
+
gin_channels: int = 0,
|
| 189 |
+
) -> None:
|
| 190 |
+
super().__init__()
|
| 191 |
+
filter_channels = in_channels # it needs to be removed from future version.
|
| 192 |
+
self.in_channels = in_channels
|
| 193 |
+
self.filter_channels = filter_channels
|
| 194 |
+
self.kernel_size = kernel_size
|
| 195 |
+
self.p_dropout = p_dropout
|
| 196 |
+
self.n_flows = n_flows
|
| 197 |
+
self.gin_channels = gin_channels
|
| 198 |
+
|
| 199 |
+
self.log_flow = modules.Log()
|
| 200 |
+
self.flows = nn.ModuleList()
|
| 201 |
+
self.flows.append(modules.ElementwiseAffine(2))
|
| 202 |
+
for i in range(n_flows):
|
| 203 |
+
self.flows.append(
|
| 204 |
+
modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
|
| 205 |
+
)
|
| 206 |
+
self.flows.append(modules.Flip())
|
| 207 |
+
|
| 208 |
+
self.post_pre = nn.Conv1d(1, filter_channels, 1)
|
| 209 |
+
self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 210 |
+
self.post_convs = modules.DDSConv(
|
| 211 |
+
filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
|
| 212 |
+
)
|
| 213 |
+
self.post_flows = nn.ModuleList()
|
| 214 |
+
self.post_flows.append(modules.ElementwiseAffine(2))
|
| 215 |
+
for i in range(4):
|
| 216 |
+
self.post_flows.append(
|
| 217 |
+
modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
|
| 218 |
+
)
|
| 219 |
+
self.post_flows.append(modules.Flip())
|
| 220 |
+
|
| 221 |
+
self.pre = nn.Conv1d(in_channels, filter_channels, 1)
|
| 222 |
+
self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 223 |
+
self.convs = modules.DDSConv(
|
| 224 |
+
filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
|
| 225 |
+
)
|
| 226 |
+
if gin_channels != 0:
|
| 227 |
+
self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
|
| 228 |
+
|
| 229 |
+
def forward(
|
| 230 |
+
self,
|
| 231 |
+
x: torch.Tensor,
|
| 232 |
+
x_mask: torch.Tensor,
|
| 233 |
+
w: Optional[torch.Tensor] = None,
|
| 234 |
+
g: Optional[torch.Tensor] = None,
|
| 235 |
+
reverse: bool = False,
|
| 236 |
+
noise_scale: float = 1.0,
|
| 237 |
+
) -> torch.Tensor:
|
| 238 |
+
x = torch.detach(x)
|
| 239 |
+
x = self.pre(x)
|
| 240 |
+
if g is not None:
|
| 241 |
+
g = torch.detach(g)
|
| 242 |
+
x = x + self.cond(g)
|
| 243 |
+
x = self.convs(x, x_mask)
|
| 244 |
+
x = self.proj(x) * x_mask
|
| 245 |
+
|
| 246 |
+
if not reverse:
|
| 247 |
+
flows = self.flows
|
| 248 |
+
assert w is not None
|
| 249 |
+
|
| 250 |
+
logdet_tot_q = 0
|
| 251 |
+
h_w = self.post_pre(w)
|
| 252 |
+
h_w = self.post_convs(h_w, x_mask)
|
| 253 |
+
h_w = self.post_proj(h_w) * x_mask
|
| 254 |
+
e_q = (
|
| 255 |
+
torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype)
|
| 256 |
+
* x_mask
|
| 257 |
+
)
|
| 258 |
+
z_q = e_q
|
| 259 |
+
for flow in self.post_flows:
|
| 260 |
+
z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
|
| 261 |
+
logdet_tot_q += logdet_q
|
| 262 |
+
z_u, z1 = torch.split(z_q, [1, 1], 1)
|
| 263 |
+
u = torch.sigmoid(z_u) * x_mask
|
| 264 |
+
z0 = (w - u) * x_mask
|
| 265 |
+
logdet_tot_q += torch.sum(
|
| 266 |
+
(F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]
|
| 267 |
+
)
|
| 268 |
+
logq = (
|
| 269 |
+
torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2])
|
| 270 |
+
- logdet_tot_q
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
logdet_tot = 0
|
| 274 |
+
z0, logdet = self.log_flow(z0, x_mask)
|
| 275 |
+
logdet_tot += logdet
|
| 276 |
+
z = torch.cat([z0, z1], 1)
|
| 277 |
+
for flow in flows:
|
| 278 |
+
z, logdet = flow(z, x_mask, g=x, reverse=reverse)
|
| 279 |
+
logdet_tot = logdet_tot + logdet
|
| 280 |
+
nll = (
|
| 281 |
+
torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2])
|
| 282 |
+
- logdet_tot
|
| 283 |
+
)
|
| 284 |
+
return nll + logq # [b]
|
| 285 |
+
else:
|
| 286 |
+
flows = list(reversed(self.flows))
|
| 287 |
+
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
|
| 288 |
+
z = (
|
| 289 |
+
torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype)
|
| 290 |
+
* noise_scale
|
| 291 |
+
)
|
| 292 |
+
for flow in flows:
|
| 293 |
+
z = flow(z, x_mask, g=x, reverse=reverse)
|
| 294 |
+
z0, z1 = torch.split(z, [1, 1], 1)
|
| 295 |
+
logw = z0
|
| 296 |
+
return logw
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class DurationPredictor(nn.Module):
|
| 300 |
+
def __init__(
|
| 301 |
+
self,
|
| 302 |
+
in_channels: int,
|
| 303 |
+
filter_channels: int,
|
| 304 |
+
kernel_size: int,
|
| 305 |
+
p_dropout: float,
|
| 306 |
+
gin_channels: int = 0,
|
| 307 |
+
) -> None:
|
| 308 |
+
super().__init__()
|
| 309 |
+
|
| 310 |
+
self.in_channels = in_channels
|
| 311 |
+
self.filter_channels = filter_channels
|
| 312 |
+
self.kernel_size = kernel_size
|
| 313 |
+
self.p_dropout = p_dropout
|
| 314 |
+
self.gin_channels = gin_channels
|
| 315 |
+
|
| 316 |
+
self.drop = nn.Dropout(p_dropout)
|
| 317 |
+
self.conv_1 = nn.Conv1d(
|
| 318 |
+
in_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 319 |
+
)
|
| 320 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
| 321 |
+
self.conv_2 = nn.Conv1d(
|
| 322 |
+
filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 323 |
+
)
|
| 324 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
| 325 |
+
self.proj = nn.Conv1d(filter_channels, 1, 1)
|
| 326 |
+
|
| 327 |
+
if gin_channels != 0:
|
| 328 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
| 329 |
+
|
| 330 |
+
def forward(
|
| 331 |
+
self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None
|
| 332 |
+
) -> torch.Tensor:
|
| 333 |
+
x = torch.detach(x)
|
| 334 |
+
if g is not None:
|
| 335 |
+
g = torch.detach(g)
|
| 336 |
+
x = x + self.cond(g)
|
| 337 |
+
x = self.conv_1(x * x_mask)
|
| 338 |
+
x = torch.relu(x)
|
| 339 |
+
x = self.norm_1(x)
|
| 340 |
+
x = self.drop(x)
|
| 341 |
+
x = self.conv_2(x * x_mask)
|
| 342 |
+
x = torch.relu(x)
|
| 343 |
+
x = self.norm_2(x)
|
| 344 |
+
x = self.drop(x)
|
| 345 |
+
x = self.proj(x * x_mask)
|
| 346 |
+
return x * x_mask
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class TextEncoder(nn.Module):
|
| 350 |
+
def __init__(
|
| 351 |
+
self,
|
| 352 |
+
n_vocab: int,
|
| 353 |
+
out_channels: int,
|
| 354 |
+
hidden_channels: int,
|
| 355 |
+
filter_channels: int,
|
| 356 |
+
n_heads: int,
|
| 357 |
+
n_layers: int,
|
| 358 |
+
kernel_size: int,
|
| 359 |
+
p_dropout: float,
|
| 360 |
+
n_speakers: int,
|
| 361 |
+
gin_channels: int = 0,
|
| 362 |
+
) -> None:
|
| 363 |
+
super().__init__()
|
| 364 |
+
self.n_vocab = n_vocab
|
| 365 |
+
self.out_channels = out_channels
|
| 366 |
+
self.hidden_channels = hidden_channels
|
| 367 |
+
self.filter_channels = filter_channels
|
| 368 |
+
self.n_heads = n_heads
|
| 369 |
+
self.n_layers = n_layers
|
| 370 |
+
self.kernel_size = kernel_size
|
| 371 |
+
self.p_dropout = p_dropout
|
| 372 |
+
self.gin_channels = gin_channels
|
| 373 |
+
self.emb = nn.Embedding(len(SYMBOLS), hidden_channels)
|
| 374 |
+
nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
|
| 375 |
+
self.tone_emb = nn.Embedding(NUM_TONES, hidden_channels)
|
| 376 |
+
nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels**-0.5)
|
| 377 |
+
self.language_emb = nn.Embedding(NUM_LANGUAGES, hidden_channels)
|
| 378 |
+
nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels**-0.5)
|
| 379 |
+
self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
|
| 380 |
+
self.ja_bert_proj = nn.Conv1d(1024, hidden_channels, 1)
|
| 381 |
+
self.en_bert_proj = nn.Conv1d(1024, hidden_channels, 1)
|
| 382 |
+
self.style_proj = nn.Linear(256, hidden_channels)
|
| 383 |
+
|
| 384 |
+
self.encoder = attentions.Encoder(
|
| 385 |
+
hidden_channels,
|
| 386 |
+
filter_channels,
|
| 387 |
+
n_heads,
|
| 388 |
+
n_layers,
|
| 389 |
+
kernel_size,
|
| 390 |
+
p_dropout,
|
| 391 |
+
gin_channels=self.gin_channels,
|
| 392 |
+
)
|
| 393 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
| 394 |
+
|
| 395 |
+
def forward(
|
| 396 |
+
self,
|
| 397 |
+
x: torch.Tensor,
|
| 398 |
+
x_lengths: torch.Tensor,
|
| 399 |
+
tone: torch.Tensor,
|
| 400 |
+
language: torch.Tensor,
|
| 401 |
+
bert: torch.Tensor,
|
| 402 |
+
ja_bert: torch.Tensor,
|
| 403 |
+
en_bert: torch.Tensor,
|
| 404 |
+
style_vec: torch.Tensor,
|
| 405 |
+
sid: torch.Tensor,
|
| 406 |
+
g: Optional[torch.Tensor] = None,
|
| 407 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 408 |
+
bert_emb = self.bert_proj(bert).transpose(1, 2)
|
| 409 |
+
ja_bert_emb = self.ja_bert_proj(ja_bert).transpose(1, 2)
|
| 410 |
+
en_bert_emb = self.en_bert_proj(en_bert).transpose(1, 2)
|
| 411 |
+
style_emb = self.style_proj(style_vec.unsqueeze(1))
|
| 412 |
+
|
| 413 |
+
x = (
|
| 414 |
+
self.emb(x)
|
| 415 |
+
+ self.tone_emb(tone)
|
| 416 |
+
+ self.language_emb(language)
|
| 417 |
+
+ bert_emb
|
| 418 |
+
+ ja_bert_emb
|
| 419 |
+
+ en_bert_emb
|
| 420 |
+
+ style_emb
|
| 421 |
+
) * math.sqrt(
|
| 422 |
+
self.hidden_channels
|
| 423 |
+
) # [b, t, h]
|
| 424 |
+
x = torch.transpose(x, 1, -1) # [b, h, t]
|
| 425 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
|
| 426 |
+
x.dtype
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
x = self.encoder(x * x_mask, x_mask, g=g)
|
| 430 |
+
stats = self.proj(x) * x_mask
|
| 431 |
+
|
| 432 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
| 433 |
+
return x, m, logs, x_mask
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class ResidualCouplingBlock(nn.Module):
|
| 437 |
+
def __init__(
|
| 438 |
+
self,
|
| 439 |
+
channels: int,
|
| 440 |
+
hidden_channels: int,
|
| 441 |
+
kernel_size: int,
|
| 442 |
+
dilation_rate: int,
|
| 443 |
+
n_layers: int,
|
| 444 |
+
n_flows: int = 4,
|
| 445 |
+
gin_channels: int = 0,
|
| 446 |
+
) -> None:
|
| 447 |
+
super().__init__()
|
| 448 |
+
self.channels = channels
|
| 449 |
+
self.hidden_channels = hidden_channels
|
| 450 |
+
self.kernel_size = kernel_size
|
| 451 |
+
self.dilation_rate = dilation_rate
|
| 452 |
+
self.n_layers = n_layers
|
| 453 |
+
self.n_flows = n_flows
|
| 454 |
+
self.gin_channels = gin_channels
|
| 455 |
+
|
| 456 |
+
self.flows = nn.ModuleList()
|
| 457 |
+
for i in range(n_flows):
|
| 458 |
+
self.flows.append(
|
| 459 |
+
modules.ResidualCouplingLayer(
|
| 460 |
+
channels,
|
| 461 |
+
hidden_channels,
|
| 462 |
+
kernel_size,
|
| 463 |
+
dilation_rate,
|
| 464 |
+
n_layers,
|
| 465 |
+
gin_channels=gin_channels,
|
| 466 |
+
mean_only=True,
|
| 467 |
+
)
|
| 468 |
+
)
|
| 469 |
+
self.flows.append(modules.Flip())
|
| 470 |
+
|
| 471 |
+
def forward(
|
| 472 |
+
self,
|
| 473 |
+
x: torch.Tensor,
|
| 474 |
+
x_mask: torch.Tensor,
|
| 475 |
+
g: Optional[torch.Tensor] = None,
|
| 476 |
+
reverse: bool = False,
|
| 477 |
+
) -> torch.Tensor:
|
| 478 |
+
if not reverse:
|
| 479 |
+
for flow in self.flows:
|
| 480 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
| 481 |
+
else:
|
| 482 |
+
for flow in reversed(self.flows):
|
| 483 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
| 484 |
+
return x
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class PosteriorEncoder(nn.Module):
|
| 488 |
+
def __init__(
|
| 489 |
+
self,
|
| 490 |
+
in_channels: int,
|
| 491 |
+
out_channels: int,
|
| 492 |
+
hidden_channels: int,
|
| 493 |
+
kernel_size: int,
|
| 494 |
+
dilation_rate: int,
|
| 495 |
+
n_layers: int,
|
| 496 |
+
gin_channels: int = 0,
|
| 497 |
+
) -> None:
|
| 498 |
+
super().__init__()
|
| 499 |
+
self.in_channels = in_channels
|
| 500 |
+
self.out_channels = out_channels
|
| 501 |
+
self.hidden_channels = hidden_channels
|
| 502 |
+
self.kernel_size = kernel_size
|
| 503 |
+
self.dilation_rate = dilation_rate
|
| 504 |
+
self.n_layers = n_layers
|
| 505 |
+
self.gin_channels = gin_channels
|
| 506 |
+
|
| 507 |
+
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
|
| 508 |
+
self.enc = modules.WN(
|
| 509 |
+
hidden_channels,
|
| 510 |
+
kernel_size,
|
| 511 |
+
dilation_rate,
|
| 512 |
+
n_layers,
|
| 513 |
+
gin_channels=gin_channels,
|
| 514 |
+
)
|
| 515 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
| 516 |
+
|
| 517 |
+
def forward(
|
| 518 |
+
self,
|
| 519 |
+
x: torch.Tensor,
|
| 520 |
+
x_lengths: torch.Tensor,
|
| 521 |
+
g: Optional[torch.Tensor] = None,
|
| 522 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 523 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
|
| 524 |
+
x.dtype
|
| 525 |
+
)
|
| 526 |
+
x = self.pre(x) * x_mask
|
| 527 |
+
x = self.enc(x, x_mask, g=g)
|
| 528 |
+
stats = self.proj(x) * x_mask
|
| 529 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
| 530 |
+
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
|
| 531 |
+
return z, m, logs, x_mask
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
class Generator(torch.nn.Module):
|
| 535 |
+
def __init__(
|
| 536 |
+
self,
|
| 537 |
+
initial_channel: int,
|
| 538 |
+
resblock_str: str,
|
| 539 |
+
resblock_kernel_sizes: list[int],
|
| 540 |
+
resblock_dilation_sizes: list[list[int]],
|
| 541 |
+
upsample_rates: list[int],
|
| 542 |
+
upsample_initial_channel: int,
|
| 543 |
+
upsample_kernel_sizes: list[int],
|
| 544 |
+
gin_channels: int = 0,
|
| 545 |
+
) -> None:
|
| 546 |
+
super(Generator, self).__init__()
|
| 547 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
| 548 |
+
self.num_upsamples = len(upsample_rates)
|
| 549 |
+
self.conv_pre = Conv1d(
|
| 550 |
+
initial_channel, upsample_initial_channel, 7, 1, padding=3
|
| 551 |
+
)
|
| 552 |
+
resblock = modules.ResBlock1 if resblock_str == "1" else modules.ResBlock2
|
| 553 |
+
|
| 554 |
+
self.ups = nn.ModuleList()
|
| 555 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
| 556 |
+
self.ups.append(
|
| 557 |
+
weight_norm(
|
| 558 |
+
ConvTranspose1d(
|
| 559 |
+
upsample_initial_channel // (2**i),
|
| 560 |
+
upsample_initial_channel // (2 ** (i + 1)),
|
| 561 |
+
k,
|
| 562 |
+
u,
|
| 563 |
+
padding=(k - u) // 2,
|
| 564 |
+
)
|
| 565 |
+
)
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
self.resblocks = nn.ModuleList()
|
| 569 |
+
ch = None
|
| 570 |
+
for i in range(len(self.ups)):
|
| 571 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
| 572 |
+
for j, (k, d) in enumerate(
|
| 573 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)
|
| 574 |
+
):
|
| 575 |
+
self.resblocks.append(resblock(ch, k, d)) # type: ignore
|
| 576 |
+
|
| 577 |
+
assert ch is not None
|
| 578 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
| 579 |
+
self.ups.apply(commons.init_weights)
|
| 580 |
+
|
| 581 |
+
if gin_channels != 0:
|
| 582 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
| 583 |
+
|
| 584 |
+
def forward(
|
| 585 |
+
self, x: torch.Tensor, g: Optional[torch.Tensor] = None
|
| 586 |
+
) -> torch.Tensor:
|
| 587 |
+
x = self.conv_pre(x)
|
| 588 |
+
if g is not None:
|
| 589 |
+
x = x + self.cond(g)
|
| 590 |
+
|
| 591 |
+
for i in range(self.num_upsamples):
|
| 592 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 593 |
+
x = self.ups[i](x)
|
| 594 |
+
xs = None
|
| 595 |
+
for j in range(self.num_kernels):
|
| 596 |
+
if xs is None:
|
| 597 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
| 598 |
+
else:
|
| 599 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
| 600 |
+
assert xs is not None
|
| 601 |
+
x = xs / self.num_kernels
|
| 602 |
+
x = F.leaky_relu(x)
|
| 603 |
+
x = self.conv_post(x)
|
| 604 |
+
x = torch.tanh(x)
|
| 605 |
+
|
| 606 |
+
return x
|
| 607 |
+
|
| 608 |
+
def remove_weight_norm(self) -> None:
|
| 609 |
+
print("Removing weight norm...")
|
| 610 |
+
for layer in self.ups:
|
| 611 |
+
remove_weight_norm(layer)
|
| 612 |
+
for layer in self.resblocks:
|
| 613 |
+
layer.remove_weight_norm()
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
class DiscriminatorP(torch.nn.Module):
|
| 617 |
+
def __init__(
|
| 618 |
+
self,
|
| 619 |
+
period: int,
|
| 620 |
+
kernel_size: int = 5,
|
| 621 |
+
stride: int = 3,
|
| 622 |
+
use_spectral_norm: bool = False,
|
| 623 |
+
) -> None:
|
| 624 |
+
super(DiscriminatorP, self).__init__()
|
| 625 |
+
self.period = period
|
| 626 |
+
self.use_spectral_norm = use_spectral_norm
|
| 627 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
| 628 |
+
self.convs = nn.ModuleList(
|
| 629 |
+
[
|
| 630 |
+
norm_f(
|
| 631 |
+
Conv2d(
|
| 632 |
+
1,
|
| 633 |
+
32,
|
| 634 |
+
(kernel_size, 1),
|
| 635 |
+
(stride, 1),
|
| 636 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 637 |
+
)
|
| 638 |
+
),
|
| 639 |
+
norm_f(
|
| 640 |
+
Conv2d(
|
| 641 |
+
32,
|
| 642 |
+
128,
|
| 643 |
+
(kernel_size, 1),
|
| 644 |
+
(stride, 1),
|
| 645 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 646 |
+
)
|
| 647 |
+
),
|
| 648 |
+
norm_f(
|
| 649 |
+
Conv2d(
|
| 650 |
+
128,
|
| 651 |
+
512,
|
| 652 |
+
(kernel_size, 1),
|
| 653 |
+
(stride, 1),
|
| 654 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 655 |
+
)
|
| 656 |
+
),
|
| 657 |
+
norm_f(
|
| 658 |
+
Conv2d(
|
| 659 |
+
512,
|
| 660 |
+
1024,
|
| 661 |
+
(kernel_size, 1),
|
| 662 |
+
(stride, 1),
|
| 663 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 664 |
+
)
|
| 665 |
+
),
|
| 666 |
+
norm_f(
|
| 667 |
+
Conv2d(
|
| 668 |
+
1024,
|
| 669 |
+
1024,
|
| 670 |
+
(kernel_size, 1),
|
| 671 |
+
1,
|
| 672 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 673 |
+
)
|
| 674 |
+
),
|
| 675 |
+
]
|
| 676 |
+
)
|
| 677 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
| 678 |
+
|
| 679 |
+
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, list[torch.Tensor]]:
|
| 680 |
+
fmap = []
|
| 681 |
+
|
| 682 |
+
# 1d to 2d
|
| 683 |
+
b, c, t = x.shape
|
| 684 |
+
if t % self.period != 0: # pad first
|
| 685 |
+
n_pad = self.period - (t % self.period)
|
| 686 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
| 687 |
+
t = t + n_pad
|
| 688 |
+
x = x.view(b, c, t // self.period, self.period)
|
| 689 |
+
|
| 690 |
+
for layer in self.convs:
|
| 691 |
+
x = layer(x)
|
| 692 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 693 |
+
fmap.append(x)
|
| 694 |
+
x = self.conv_post(x)
|
| 695 |
+
fmap.append(x)
|
| 696 |
+
x = torch.flatten(x, 1, -1)
|
| 697 |
+
|
| 698 |
+
return x, fmap
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
class DiscriminatorS(torch.nn.Module):
|
| 702 |
+
def __init__(self, use_spectral_norm: bool = False) -> None:
|
| 703 |
+
super(DiscriminatorS, self).__init__()
|
| 704 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
| 705 |
+
self.convs = nn.ModuleList(
|
| 706 |
+
[
|
| 707 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
| 708 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
| 709 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
| 710 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
| 711 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
| 712 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
| 713 |
+
]
|
| 714 |
+
)
|
| 715 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
| 716 |
+
|
| 717 |
+
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, list[torch.Tensor]]:
|
| 718 |
+
fmap = []
|
| 719 |
+
|
| 720 |
+
for layer in self.convs:
|
| 721 |
+
x = layer(x)
|
| 722 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 723 |
+
fmap.append(x)
|
| 724 |
+
x = self.conv_post(x)
|
| 725 |
+
fmap.append(x)
|
| 726 |
+
x = torch.flatten(x, 1, -1)
|
| 727 |
+
|
| 728 |
+
return x, fmap
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
class MultiPeriodDiscriminator(torch.nn.Module):
|
| 732 |
+
def __init__(self, use_spectral_norm: bool = False) -> None:
|
| 733 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
| 734 |
+
periods = [2, 3, 5, 7, 11]
|
| 735 |
+
|
| 736 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
| 737 |
+
discs = discs + [
|
| 738 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
| 739 |
+
]
|
| 740 |
+
self.discriminators = nn.ModuleList(discs)
|
| 741 |
+
|
| 742 |
+
def forward(
|
| 743 |
+
self,
|
| 744 |
+
y: torch.Tensor,
|
| 745 |
+
y_hat: torch.Tensor,
|
| 746 |
+
) -> tuple[
|
| 747 |
+
list[torch.Tensor], list[torch.Tensor], list[torch.Tensor], list[torch.Tensor]
|
| 748 |
+
]:
|
| 749 |
+
y_d_rs = []
|
| 750 |
+
y_d_gs = []
|
| 751 |
+
fmap_rs = []
|
| 752 |
+
fmap_gs = []
|
| 753 |
+
for i, d in enumerate(self.discriminators):
|
| 754 |
+
y_d_r, fmap_r = d(y)
|
| 755 |
+
y_d_g, fmap_g = d(y_hat)
|
| 756 |
+
y_d_rs.append(y_d_r)
|
| 757 |
+
y_d_gs.append(y_d_g)
|
| 758 |
+
fmap_rs.append(fmap_r)
|
| 759 |
+
fmap_gs.append(fmap_g)
|
| 760 |
+
|
| 761 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
class ReferenceEncoder(nn.Module):
|
| 765 |
+
"""
|
| 766 |
+
inputs --- [N, Ty/r, n_mels*r] mels
|
| 767 |
+
outputs --- [N, ref_enc_gru_size]
|
| 768 |
+
"""
|
| 769 |
+
|
| 770 |
+
def __init__(self, spec_channels: int, gin_channels: int = 0) -> None:
|
| 771 |
+
super().__init__()
|
| 772 |
+
self.spec_channels = spec_channels
|
| 773 |
+
ref_enc_filters = [32, 32, 64, 64, 128, 128]
|
| 774 |
+
K = len(ref_enc_filters)
|
| 775 |
+
filters = [1] + ref_enc_filters
|
| 776 |
+
convs = [
|
| 777 |
+
weight_norm(
|
| 778 |
+
nn.Conv2d(
|
| 779 |
+
in_channels=filters[i],
|
| 780 |
+
out_channels=filters[i + 1],
|
| 781 |
+
kernel_size=(3, 3),
|
| 782 |
+
stride=(2, 2),
|
| 783 |
+
padding=(1, 1),
|
| 784 |
+
)
|
| 785 |
+
)
|
| 786 |
+
for i in range(K)
|
| 787 |
+
]
|
| 788 |
+
self.convs = nn.ModuleList(convs)
|
| 789 |
+
# self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)])
|
| 790 |
+
|
| 791 |
+
out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
|
| 792 |
+
self.gru = nn.GRU(
|
| 793 |
+
input_size=ref_enc_filters[-1] * out_channels,
|
| 794 |
+
hidden_size=256 // 2,
|
| 795 |
+
batch_first=True,
|
| 796 |
+
)
|
| 797 |
+
self.proj = nn.Linear(128, gin_channels)
|
| 798 |
+
|
| 799 |
+
def forward(
|
| 800 |
+
self, inputs: torch.Tensor, mask: Optional[torch.Tensor] = None
|
| 801 |
+
) -> torch.Tensor:
|
| 802 |
+
N = inputs.size(0)
|
| 803 |
+
out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
|
| 804 |
+
for conv in self.convs:
|
| 805 |
+
out = conv(out)
|
| 806 |
+
# out = wn(out)
|
| 807 |
+
out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
|
| 808 |
+
|
| 809 |
+
out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
|
| 810 |
+
T = out.size(1)
|
| 811 |
+
N = out.size(0)
|
| 812 |
+
out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
|
| 813 |
+
|
| 814 |
+
self.gru.flatten_parameters()
|
| 815 |
+
memory, out = self.gru(out) # out --- [1, N, 128]
|
| 816 |
+
|
| 817 |
+
return self.proj(out.squeeze(0))
|
| 818 |
+
|
| 819 |
+
def calculate_channels(
|
| 820 |
+
self, L: int, kernel_size: int, stride: int, pad: int, n_convs: int
|
| 821 |
+
) -> int:
|
| 822 |
+
for i in range(n_convs):
|
| 823 |
+
L = (L - kernel_size + 2 * pad) // stride + 1
|
| 824 |
+
return L
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
class SynthesizerTrn(nn.Module):
|
| 828 |
+
"""
|
| 829 |
+
Synthesizer for Training
|
| 830 |
+
"""
|
| 831 |
+
|
| 832 |
+
def __init__(
|
| 833 |
+
self,
|
| 834 |
+
n_vocab: int,
|
| 835 |
+
spec_channels: int,
|
| 836 |
+
segment_size: int,
|
| 837 |
+
inter_channels: int,
|
| 838 |
+
hidden_channels: int,
|
| 839 |
+
filter_channels: int,
|
| 840 |
+
n_heads: int,
|
| 841 |
+
n_layers: int,
|
| 842 |
+
kernel_size: int,
|
| 843 |
+
p_dropout: float,
|
| 844 |
+
resblock: str,
|
| 845 |
+
resblock_kernel_sizes: list[int],
|
| 846 |
+
resblock_dilation_sizes: list[list[int]],
|
| 847 |
+
upsample_rates: list[int],
|
| 848 |
+
upsample_initial_channel: int,
|
| 849 |
+
upsample_kernel_sizes: list[int],
|
| 850 |
+
n_speakers: int = 256,
|
| 851 |
+
gin_channels: int = 256,
|
| 852 |
+
use_sdp: bool = True,
|
| 853 |
+
n_flow_layer: int = 4,
|
| 854 |
+
n_layers_trans_flow: int = 4,
|
| 855 |
+
flow_share_parameter: bool = False,
|
| 856 |
+
use_transformer_flow: bool = True,
|
| 857 |
+
**kwargs: Any,
|
| 858 |
+
) -> None:
|
| 859 |
+
super().__init__()
|
| 860 |
+
self.n_vocab = n_vocab
|
| 861 |
+
self.spec_channels = spec_channels
|
| 862 |
+
self.inter_channels = inter_channels
|
| 863 |
+
self.hidden_channels = hidden_channels
|
| 864 |
+
self.filter_channels = filter_channels
|
| 865 |
+
self.n_heads = n_heads
|
| 866 |
+
self.n_layers = n_layers
|
| 867 |
+
self.kernel_size = kernel_size
|
| 868 |
+
self.p_dropout = p_dropout
|
| 869 |
+
self.resblock = resblock
|
| 870 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 871 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 872 |
+
self.upsample_rates = upsample_rates
|
| 873 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 874 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 875 |
+
self.segment_size = segment_size
|
| 876 |
+
self.n_speakers = n_speakers
|
| 877 |
+
self.gin_channels = gin_channels
|
| 878 |
+
self.n_layers_trans_flow = n_layers_trans_flow
|
| 879 |
+
self.use_spk_conditioned_encoder = kwargs.get(
|
| 880 |
+
"use_spk_conditioned_encoder", True
|
| 881 |
+
)
|
| 882 |
+
self.use_sdp = use_sdp
|
| 883 |
+
self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
|
| 884 |
+
self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
|
| 885 |
+
self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
|
| 886 |
+
self.current_mas_noise_scale = self.mas_noise_scale_initial
|
| 887 |
+
if self.use_spk_conditioned_encoder and gin_channels > 0:
|
| 888 |
+
self.enc_gin_channels = gin_channels
|
| 889 |
+
self.enc_p = TextEncoder(
|
| 890 |
+
n_vocab,
|
| 891 |
+
inter_channels,
|
| 892 |
+
hidden_channels,
|
| 893 |
+
filter_channels,
|
| 894 |
+
n_heads,
|
| 895 |
+
n_layers,
|
| 896 |
+
kernel_size,
|
| 897 |
+
p_dropout,
|
| 898 |
+
self.n_speakers,
|
| 899 |
+
gin_channels=self.enc_gin_channels,
|
| 900 |
+
)
|
| 901 |
+
self.dec = Generator(
|
| 902 |
+
inter_channels,
|
| 903 |
+
resblock,
|
| 904 |
+
resblock_kernel_sizes,
|
| 905 |
+
resblock_dilation_sizes,
|
| 906 |
+
upsample_rates,
|
| 907 |
+
upsample_initial_channel,
|
| 908 |
+
upsample_kernel_sizes,
|
| 909 |
+
gin_channels=gin_channels,
|
| 910 |
+
)
|
| 911 |
+
self.enc_q = PosteriorEncoder(
|
| 912 |
+
spec_channels,
|
| 913 |
+
inter_channels,
|
| 914 |
+
hidden_channels,
|
| 915 |
+
5,
|
| 916 |
+
1,
|
| 917 |
+
16,
|
| 918 |
+
gin_channels=gin_channels,
|
| 919 |
+
)
|
| 920 |
+
if use_transformer_flow:
|
| 921 |
+
self.flow = TransformerCouplingBlock(
|
| 922 |
+
inter_channels,
|
| 923 |
+
hidden_channels,
|
| 924 |
+
filter_channels,
|
| 925 |
+
n_heads,
|
| 926 |
+
n_layers_trans_flow,
|
| 927 |
+
5,
|
| 928 |
+
p_dropout,
|
| 929 |
+
n_flow_layer,
|
| 930 |
+
gin_channels=gin_channels,
|
| 931 |
+
share_parameter=flow_share_parameter,
|
| 932 |
+
)
|
| 933 |
+
else:
|
| 934 |
+
self.flow = ResidualCouplingBlock(
|
| 935 |
+
inter_channels,
|
| 936 |
+
hidden_channels,
|
| 937 |
+
5,
|
| 938 |
+
1,
|
| 939 |
+
n_flow_layer,
|
| 940 |
+
gin_channels=gin_channels,
|
| 941 |
+
)
|
| 942 |
+
self.sdp = StochasticDurationPredictor(
|
| 943 |
+
hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels
|
| 944 |
+
)
|
| 945 |
+
self.dp = DurationPredictor(
|
| 946 |
+
hidden_channels, 256, 3, 0.5, gin_channels=gin_channels
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
if n_speakers >= 1:
|
| 950 |
+
self.emb_g = nn.Embedding(n_speakers, gin_channels)
|
| 951 |
+
else:
|
| 952 |
+
self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
|
| 953 |
+
|
| 954 |
+
def forward(
|
| 955 |
+
self,
|
| 956 |
+
x: torch.Tensor,
|
| 957 |
+
x_lengths: torch.Tensor,
|
| 958 |
+
y: torch.Tensor,
|
| 959 |
+
y_lengths: torch.Tensor,
|
| 960 |
+
sid: torch.Tensor,
|
| 961 |
+
tone: torch.Tensor,
|
| 962 |
+
language: torch.Tensor,
|
| 963 |
+
bert: torch.Tensor,
|
| 964 |
+
ja_bert: torch.Tensor,
|
| 965 |
+
en_bert: torch.Tensor,
|
| 966 |
+
style_vec: torch.Tensor,
|
| 967 |
+
) -> tuple[
|
| 968 |
+
torch.Tensor,
|
| 969 |
+
torch.Tensor,
|
| 970 |
+
torch.Tensor,
|
| 971 |
+
torch.Tensor,
|
| 972 |
+
torch.Tensor,
|
| 973 |
+
torch.Tensor,
|
| 974 |
+
tuple[torch.Tensor, ...],
|
| 975 |
+
tuple[torch.Tensor, ...],
|
| 976 |
+
]:
|
| 977 |
+
if self.n_speakers > 0:
|
| 978 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
| 979 |
+
else:
|
| 980 |
+
g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
|
| 981 |
+
x, m_p, logs_p, x_mask = self.enc_p(
|
| 982 |
+
x, x_lengths, tone, language, bert, ja_bert, en_bert, style_vec, sid, g=g
|
| 983 |
+
)
|
| 984 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 985 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 986 |
+
|
| 987 |
+
with torch.no_grad():
|
| 988 |
+
# negative cross-entropy
|
| 989 |
+
s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
|
| 990 |
+
neg_cent1 = torch.sum(
|
| 991 |
+
-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True
|
| 992 |
+
) # [b, 1, t_s]
|
| 993 |
+
neg_cent2 = torch.matmul(
|
| 994 |
+
-0.5 * (z_p**2).transpose(1, 2), s_p_sq_r
|
| 995 |
+
) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
| 996 |
+
neg_cent3 = torch.matmul(
|
| 997 |
+
z_p.transpose(1, 2), (m_p * s_p_sq_r)
|
| 998 |
+
) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
| 999 |
+
neg_cent4 = torch.sum(
|
| 1000 |
+
-0.5 * (m_p**2) * s_p_sq_r, [1], keepdim=True
|
| 1001 |
+
) # [b, 1, t_s]
|
| 1002 |
+
neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
|
| 1003 |
+
if self.use_noise_scaled_mas:
|
| 1004 |
+
epsilon = (
|
| 1005 |
+
torch.std(neg_cent)
|
| 1006 |
+
* torch.randn_like(neg_cent)
|
| 1007 |
+
* self.current_mas_noise_scale
|
| 1008 |
+
)
|
| 1009 |
+
neg_cent = neg_cent + epsilon
|
| 1010 |
+
|
| 1011 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
| 1012 |
+
attn = (
|
| 1013 |
+
monotonic_alignment.maximum_path(neg_cent, attn_mask.squeeze(1))
|
| 1014 |
+
.unsqueeze(1)
|
| 1015 |
+
.detach()
|
| 1016 |
+
)
|
| 1017 |
+
|
| 1018 |
+
w = attn.sum(2)
|
| 1019 |
+
|
| 1020 |
+
l_length_sdp = self.sdp(x, x_mask, w, g=g)
|
| 1021 |
+
l_length_sdp = l_length_sdp / torch.sum(x_mask)
|
| 1022 |
+
|
| 1023 |
+
logw_ = torch.log(w + 1e-6) * x_mask
|
| 1024 |
+
logw = self.dp(x, x_mask, g=g)
|
| 1025 |
+
# logw_sdp = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=1.0)
|
| 1026 |
+
l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(
|
| 1027 |
+
x_mask
|
| 1028 |
+
) # for averaging
|
| 1029 |
+
# l_length_sdp += torch.sum((logw_sdp - logw_) ** 2, [1, 2]) / torch.sum(x_mask)
|
| 1030 |
+
|
| 1031 |
+
l_length = l_length_dp + l_length_sdp
|
| 1032 |
+
|
| 1033 |
+
# expand prior
|
| 1034 |
+
m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
|
| 1035 |
+
logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
|
| 1036 |
+
|
| 1037 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 1038 |
+
z, y_lengths, self.segment_size
|
| 1039 |
+
)
|
| 1040 |
+
o = self.dec(z_slice, g=g)
|
| 1041 |
+
return (
|
| 1042 |
+
o,
|
| 1043 |
+
l_length,
|
| 1044 |
+
attn,
|
| 1045 |
+
ids_slice,
|
| 1046 |
+
x_mask,
|
| 1047 |
+
y_mask,
|
| 1048 |
+
(z, z_p, m_p, logs_p, m_q, logs_q),
|
| 1049 |
+
(x, logw, logw_),
|
| 1050 |
+
)
|
| 1051 |
+
|
| 1052 |
+
def infer(
|
| 1053 |
+
self,
|
| 1054 |
+
x: torch.Tensor,
|
| 1055 |
+
x_lengths: torch.Tensor,
|
| 1056 |
+
sid: torch.Tensor,
|
| 1057 |
+
tone: torch.Tensor,
|
| 1058 |
+
language: torch.Tensor,
|
| 1059 |
+
bert: torch.Tensor,
|
| 1060 |
+
ja_bert: torch.Tensor,
|
| 1061 |
+
en_bert: torch.Tensor,
|
| 1062 |
+
style_vec: torch.Tensor,
|
| 1063 |
+
noise_scale: float = 0.667,
|
| 1064 |
+
length_scale: float = 1.0,
|
| 1065 |
+
noise_scale_w: float = 0.8,
|
| 1066 |
+
max_len: Optional[int] = None,
|
| 1067 |
+
sdp_ratio: float = 0.0,
|
| 1068 |
+
y: Optional[torch.Tensor] = None,
|
| 1069 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor, ...]]:
|
| 1070 |
+
# x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
|
| 1071 |
+
# g = self.gst(y)
|
| 1072 |
+
if self.n_speakers > 0:
|
| 1073 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
| 1074 |
+
else:
|
| 1075 |
+
assert y is not None
|
| 1076 |
+
g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
|
| 1077 |
+
x, m_p, logs_p, x_mask = self.enc_p(
|
| 1078 |
+
x, x_lengths, tone, language, bert, ja_bert, en_bert, style_vec, sid, g=g
|
| 1079 |
+
)
|
| 1080 |
+
logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (
|
| 1081 |
+
sdp_ratio
|
| 1082 |
+
) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
|
| 1083 |
+
w = torch.exp(logw) * x_mask * length_scale
|
| 1084 |
+
w_ceil = torch.ceil(w)
|
| 1085 |
+
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
|
| 1086 |
+
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(
|
| 1087 |
+
x_mask.dtype
|
| 1088 |
+
)
|
| 1089 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
| 1090 |
+
attn = commons.generate_path(w_ceil, attn_mask)
|
| 1091 |
+
|
| 1092 |
+
m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(
|
| 1093 |
+
1, 2
|
| 1094 |
+
) # [b, t', t], [b, t, d] -> [b, d, t']
|
| 1095 |
+
logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(
|
| 1096 |
+
1, 2
|
| 1097 |
+
) # [b, t', t], [b, t, d] -> [b, d, t']
|
| 1098 |
+
|
| 1099 |
+
z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
|
| 1100 |
+
z = self.flow(z_p, y_mask, g=g, reverse=True)
|
| 1101 |
+
o = self.dec((z * y_mask)[:, :, :max_len], g=g)
|
| 1102 |
+
return o, attn, y_mask, (z, z_p, m_p, logs_p)
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/models_jp_extra.py
ADDED
|
@@ -0,0 +1,1157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import Any, Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn import Conv1d, Conv2d, ConvTranspose1d
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
|
| 9 |
+
|
| 10 |
+
from style_bert_vits2.models import attentions, commons, modules, monotonic_alignment
|
| 11 |
+
from style_bert_vits2.nlp.symbols import NUM_LANGUAGES, NUM_TONES, SYMBOLS
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class DurationDiscriminator(nn.Module): # vits2
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
in_channels: int,
|
| 18 |
+
filter_channels: int,
|
| 19 |
+
kernel_size: int,
|
| 20 |
+
p_dropout: float,
|
| 21 |
+
gin_channels: int = 0,
|
| 22 |
+
) -> None:
|
| 23 |
+
super().__init__()
|
| 24 |
+
|
| 25 |
+
self.in_channels = in_channels
|
| 26 |
+
self.filter_channels = filter_channels
|
| 27 |
+
self.kernel_size = kernel_size
|
| 28 |
+
self.p_dropout = p_dropout
|
| 29 |
+
self.gin_channels = gin_channels
|
| 30 |
+
|
| 31 |
+
self.drop = nn.Dropout(p_dropout)
|
| 32 |
+
self.conv_1 = nn.Conv1d(
|
| 33 |
+
in_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 34 |
+
)
|
| 35 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
| 36 |
+
self.conv_2 = nn.Conv1d(
|
| 37 |
+
filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 38 |
+
)
|
| 39 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
| 40 |
+
self.dur_proj = nn.Conv1d(1, filter_channels, 1)
|
| 41 |
+
|
| 42 |
+
self.LSTM = nn.LSTM(
|
| 43 |
+
2 * filter_channels, filter_channels, batch_first=True, bidirectional=True
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if gin_channels != 0:
|
| 47 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
| 48 |
+
|
| 49 |
+
self.output_layer = nn.Sequential(
|
| 50 |
+
nn.Linear(2 * filter_channels, 1), nn.Sigmoid()
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def forward_probability(self, x: torch.Tensor, dur: torch.Tensor) -> torch.Tensor:
|
| 54 |
+
dur = self.dur_proj(dur)
|
| 55 |
+
x = torch.cat([x, dur], dim=1)
|
| 56 |
+
x = x.transpose(1, 2)
|
| 57 |
+
x, _ = self.LSTM(x)
|
| 58 |
+
output_prob = self.output_layer(x)
|
| 59 |
+
return output_prob
|
| 60 |
+
|
| 61 |
+
def forward(
|
| 62 |
+
self,
|
| 63 |
+
x: torch.Tensor,
|
| 64 |
+
x_mask: torch.Tensor,
|
| 65 |
+
dur_r: torch.Tensor,
|
| 66 |
+
dur_hat: torch.Tensor,
|
| 67 |
+
g: Optional[torch.Tensor] = None,
|
| 68 |
+
) -> list[torch.Tensor]:
|
| 69 |
+
x = torch.detach(x)
|
| 70 |
+
if g is not None:
|
| 71 |
+
g = torch.detach(g)
|
| 72 |
+
x = x + self.cond(g)
|
| 73 |
+
x = self.conv_1(x * x_mask)
|
| 74 |
+
x = torch.relu(x)
|
| 75 |
+
x = self.norm_1(x)
|
| 76 |
+
x = self.drop(x)
|
| 77 |
+
x = self.conv_2(x * x_mask)
|
| 78 |
+
x = torch.relu(x)
|
| 79 |
+
x = self.norm_2(x)
|
| 80 |
+
x = self.drop(x)
|
| 81 |
+
|
| 82 |
+
output_probs = []
|
| 83 |
+
for dur in [dur_r, dur_hat]:
|
| 84 |
+
output_prob = self.forward_probability(x, dur)
|
| 85 |
+
output_probs.append(output_prob)
|
| 86 |
+
|
| 87 |
+
return output_probs
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class TransformerCouplingBlock(nn.Module):
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
channels: int,
|
| 94 |
+
hidden_channels: int,
|
| 95 |
+
filter_channels: int,
|
| 96 |
+
n_heads: int,
|
| 97 |
+
n_layers: int,
|
| 98 |
+
kernel_size: int,
|
| 99 |
+
p_dropout: float,
|
| 100 |
+
n_flows: int = 4,
|
| 101 |
+
gin_channels: int = 0,
|
| 102 |
+
share_parameter: bool = False,
|
| 103 |
+
) -> None:
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.channels = channels
|
| 106 |
+
self.hidden_channels = hidden_channels
|
| 107 |
+
self.kernel_size = kernel_size
|
| 108 |
+
self.n_layers = n_layers
|
| 109 |
+
self.n_flows = n_flows
|
| 110 |
+
self.gin_channels = gin_channels
|
| 111 |
+
|
| 112 |
+
self.flows = nn.ModuleList()
|
| 113 |
+
|
| 114 |
+
self.wn = (
|
| 115 |
+
# attentions.FFT(
|
| 116 |
+
# hidden_channels,
|
| 117 |
+
# filter_channels,
|
| 118 |
+
# n_heads,
|
| 119 |
+
# n_layers,
|
| 120 |
+
# kernel_size,
|
| 121 |
+
# p_dropout,
|
| 122 |
+
# isflow=True,
|
| 123 |
+
# gin_channels=self.gin_channels,
|
| 124 |
+
# )
|
| 125 |
+
None
|
| 126 |
+
if share_parameter
|
| 127 |
+
else None
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
for i in range(n_flows):
|
| 131 |
+
self.flows.append(
|
| 132 |
+
modules.TransformerCouplingLayer(
|
| 133 |
+
channels,
|
| 134 |
+
hidden_channels,
|
| 135 |
+
kernel_size,
|
| 136 |
+
n_layers,
|
| 137 |
+
n_heads,
|
| 138 |
+
p_dropout,
|
| 139 |
+
filter_channels,
|
| 140 |
+
mean_only=True,
|
| 141 |
+
wn_sharing_parameter=self.wn,
|
| 142 |
+
gin_channels=self.gin_channels,
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
self.flows.append(modules.Flip())
|
| 146 |
+
|
| 147 |
+
def forward(
|
| 148 |
+
self,
|
| 149 |
+
x: torch.Tensor,
|
| 150 |
+
x_mask: torch.Tensor,
|
| 151 |
+
g: Optional[torch.Tensor] = None,
|
| 152 |
+
reverse: bool = False,
|
| 153 |
+
) -> torch.Tensor:
|
| 154 |
+
if not reverse:
|
| 155 |
+
for flow in self.flows:
|
| 156 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
| 157 |
+
else:
|
| 158 |
+
for flow in reversed(self.flows):
|
| 159 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
| 160 |
+
return x
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class StochasticDurationPredictor(nn.Module):
|
| 164 |
+
def __init__(
|
| 165 |
+
self,
|
| 166 |
+
in_channels: int,
|
| 167 |
+
filter_channels: int,
|
| 168 |
+
kernel_size: int,
|
| 169 |
+
p_dropout: float,
|
| 170 |
+
n_flows: int = 4,
|
| 171 |
+
gin_channels: int = 0,
|
| 172 |
+
) -> None:
|
| 173 |
+
super().__init__()
|
| 174 |
+
filter_channels = in_channels # it needs to be removed from future version.
|
| 175 |
+
self.in_channels = in_channels
|
| 176 |
+
self.filter_channels = filter_channels
|
| 177 |
+
self.kernel_size = kernel_size
|
| 178 |
+
self.p_dropout = p_dropout
|
| 179 |
+
self.n_flows = n_flows
|
| 180 |
+
self.gin_channels = gin_channels
|
| 181 |
+
|
| 182 |
+
self.log_flow = modules.Log()
|
| 183 |
+
self.flows = nn.ModuleList()
|
| 184 |
+
self.flows.append(modules.ElementwiseAffine(2))
|
| 185 |
+
for i in range(n_flows):
|
| 186 |
+
self.flows.append(
|
| 187 |
+
modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
|
| 188 |
+
)
|
| 189 |
+
self.flows.append(modules.Flip())
|
| 190 |
+
|
| 191 |
+
self.post_pre = nn.Conv1d(1, filter_channels, 1)
|
| 192 |
+
self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 193 |
+
self.post_convs = modules.DDSConv(
|
| 194 |
+
filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
|
| 195 |
+
)
|
| 196 |
+
self.post_flows = nn.ModuleList()
|
| 197 |
+
self.post_flows.append(modules.ElementwiseAffine(2))
|
| 198 |
+
for i in range(4):
|
| 199 |
+
self.post_flows.append(
|
| 200 |
+
modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)
|
| 201 |
+
)
|
| 202 |
+
self.post_flows.append(modules.Flip())
|
| 203 |
+
|
| 204 |
+
self.pre = nn.Conv1d(in_channels, filter_channels, 1)
|
| 205 |
+
self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
|
| 206 |
+
self.convs = modules.DDSConv(
|
| 207 |
+
filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout
|
| 208 |
+
)
|
| 209 |
+
if gin_channels != 0:
|
| 210 |
+
self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
|
| 211 |
+
|
| 212 |
+
def forward(
|
| 213 |
+
self,
|
| 214 |
+
x: torch.Tensor,
|
| 215 |
+
x_mask: torch.Tensor,
|
| 216 |
+
w: Optional[torch.Tensor] = None,
|
| 217 |
+
g: Optional[torch.Tensor] = None,
|
| 218 |
+
reverse: bool = False,
|
| 219 |
+
noise_scale: float = 1.0,
|
| 220 |
+
) -> torch.Tensor:
|
| 221 |
+
x = torch.detach(x)
|
| 222 |
+
x = self.pre(x)
|
| 223 |
+
if g is not None:
|
| 224 |
+
g = torch.detach(g)
|
| 225 |
+
x = x + self.cond(g)
|
| 226 |
+
x = self.convs(x, x_mask)
|
| 227 |
+
x = self.proj(x) * x_mask
|
| 228 |
+
|
| 229 |
+
if not reverse:
|
| 230 |
+
flows = self.flows
|
| 231 |
+
assert w is not None
|
| 232 |
+
|
| 233 |
+
logdet_tot_q = 0
|
| 234 |
+
h_w = self.post_pre(w)
|
| 235 |
+
h_w = self.post_convs(h_w, x_mask)
|
| 236 |
+
h_w = self.post_proj(h_w) * x_mask
|
| 237 |
+
e_q = (
|
| 238 |
+
torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype)
|
| 239 |
+
* x_mask
|
| 240 |
+
)
|
| 241 |
+
z_q = e_q
|
| 242 |
+
for flow in self.post_flows:
|
| 243 |
+
z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
|
| 244 |
+
logdet_tot_q += logdet_q
|
| 245 |
+
z_u, z1 = torch.split(z_q, [1, 1], 1)
|
| 246 |
+
u = torch.sigmoid(z_u) * x_mask
|
| 247 |
+
z0 = (w - u) * x_mask
|
| 248 |
+
logdet_tot_q += torch.sum(
|
| 249 |
+
(F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]
|
| 250 |
+
)
|
| 251 |
+
logq = (
|
| 252 |
+
torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q**2)) * x_mask, [1, 2])
|
| 253 |
+
- logdet_tot_q
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
logdet_tot = 0
|
| 257 |
+
z0, logdet = self.log_flow(z0, x_mask)
|
| 258 |
+
logdet_tot += logdet
|
| 259 |
+
z = torch.cat([z0, z1], 1)
|
| 260 |
+
for flow in flows:
|
| 261 |
+
z, logdet = flow(z, x_mask, g=x, reverse=reverse)
|
| 262 |
+
logdet_tot = logdet_tot + logdet
|
| 263 |
+
nll = (
|
| 264 |
+
torch.sum(0.5 * (math.log(2 * math.pi) + (z**2)) * x_mask, [1, 2])
|
| 265 |
+
- logdet_tot
|
| 266 |
+
)
|
| 267 |
+
return nll + logq # [b]
|
| 268 |
+
else:
|
| 269 |
+
flows = list(reversed(self.flows))
|
| 270 |
+
flows = flows[:-2] + [flows[-1]] # remove a useless vflow
|
| 271 |
+
z = (
|
| 272 |
+
torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype)
|
| 273 |
+
* noise_scale
|
| 274 |
+
)
|
| 275 |
+
for flow in flows:
|
| 276 |
+
z = flow(z, x_mask, g=x, reverse=reverse)
|
| 277 |
+
z0, z1 = torch.split(z, [1, 1], 1)
|
| 278 |
+
logw = z0
|
| 279 |
+
return logw
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class DurationPredictor(nn.Module):
|
| 283 |
+
def __init__(
|
| 284 |
+
self,
|
| 285 |
+
in_channels: int,
|
| 286 |
+
filter_channels: int,
|
| 287 |
+
kernel_size: int,
|
| 288 |
+
p_dropout: float,
|
| 289 |
+
gin_channels: int = 0,
|
| 290 |
+
) -> None:
|
| 291 |
+
super().__init__()
|
| 292 |
+
|
| 293 |
+
self.in_channels = in_channels
|
| 294 |
+
self.filter_channels = filter_channels
|
| 295 |
+
self.kernel_size = kernel_size
|
| 296 |
+
self.p_dropout = p_dropout
|
| 297 |
+
self.gin_channels = gin_channels
|
| 298 |
+
|
| 299 |
+
self.drop = nn.Dropout(p_dropout)
|
| 300 |
+
self.conv_1 = nn.Conv1d(
|
| 301 |
+
in_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 302 |
+
)
|
| 303 |
+
self.norm_1 = modules.LayerNorm(filter_channels)
|
| 304 |
+
self.conv_2 = nn.Conv1d(
|
| 305 |
+
filter_channels, filter_channels, kernel_size, padding=kernel_size // 2
|
| 306 |
+
)
|
| 307 |
+
self.norm_2 = modules.LayerNorm(filter_channels)
|
| 308 |
+
self.proj = nn.Conv1d(filter_channels, 1, 1)
|
| 309 |
+
|
| 310 |
+
if gin_channels != 0:
|
| 311 |
+
self.cond = nn.Conv1d(gin_channels, in_channels, 1)
|
| 312 |
+
|
| 313 |
+
def forward(
|
| 314 |
+
self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None
|
| 315 |
+
) -> torch.Tensor:
|
| 316 |
+
x = torch.detach(x)
|
| 317 |
+
if g is not None:
|
| 318 |
+
g = torch.detach(g)
|
| 319 |
+
x = x + self.cond(g)
|
| 320 |
+
x = self.conv_1(x * x_mask)
|
| 321 |
+
x = torch.relu(x)
|
| 322 |
+
x = self.norm_1(x)
|
| 323 |
+
x = self.drop(x)
|
| 324 |
+
x = self.conv_2(x * x_mask)
|
| 325 |
+
x = torch.relu(x)
|
| 326 |
+
x = self.norm_2(x)
|
| 327 |
+
x = self.drop(x)
|
| 328 |
+
x = self.proj(x * x_mask)
|
| 329 |
+
return x * x_mask
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class Bottleneck(nn.Sequential):
|
| 333 |
+
def __init__(self, in_dim: int, hidden_dim: int) -> None:
|
| 334 |
+
c_fc1 = nn.Linear(in_dim, hidden_dim, bias=False)
|
| 335 |
+
c_fc2 = nn.Linear(in_dim, hidden_dim, bias=False)
|
| 336 |
+
super().__init__(c_fc1, c_fc2)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class Block(nn.Module):
|
| 340 |
+
def __init__(self, in_dim: int, hidden_dim: int) -> None:
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.norm = nn.LayerNorm(in_dim)
|
| 343 |
+
self.mlp = MLP(in_dim, hidden_dim)
|
| 344 |
+
|
| 345 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 346 |
+
x = x + self.mlp(self.norm(x))
|
| 347 |
+
return x
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class MLP(nn.Module):
|
| 351 |
+
def __init__(self, in_dim: int, hidden_dim: int) -> None:
|
| 352 |
+
super().__init__()
|
| 353 |
+
self.c_fc1 = nn.Linear(in_dim, hidden_dim, bias=False)
|
| 354 |
+
self.c_fc2 = nn.Linear(in_dim, hidden_dim, bias=False)
|
| 355 |
+
self.c_proj = nn.Linear(hidden_dim, in_dim, bias=False)
|
| 356 |
+
|
| 357 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 358 |
+
x = F.silu(self.c_fc1(x)) * self.c_fc2(x)
|
| 359 |
+
x = self.c_proj(x)
|
| 360 |
+
return x
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class TextEncoder(nn.Module):
|
| 364 |
+
def __init__(
|
| 365 |
+
self,
|
| 366 |
+
n_vocab: int,
|
| 367 |
+
out_channels: int,
|
| 368 |
+
hidden_channels: int,
|
| 369 |
+
filter_channels: int,
|
| 370 |
+
n_heads: int,
|
| 371 |
+
n_layers: int,
|
| 372 |
+
kernel_size: int,
|
| 373 |
+
p_dropout: float,
|
| 374 |
+
gin_channels: int = 0,
|
| 375 |
+
) -> None:
|
| 376 |
+
super().__init__()
|
| 377 |
+
self.n_vocab = n_vocab
|
| 378 |
+
self.out_channels = out_channels
|
| 379 |
+
self.hidden_channels = hidden_channels
|
| 380 |
+
self.filter_channels = filter_channels
|
| 381 |
+
self.n_heads = n_heads
|
| 382 |
+
self.n_layers = n_layers
|
| 383 |
+
self.kernel_size = kernel_size
|
| 384 |
+
self.p_dropout = p_dropout
|
| 385 |
+
self.gin_channels = gin_channels
|
| 386 |
+
self.emb = nn.Embedding(len(SYMBOLS), hidden_channels)
|
| 387 |
+
nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
|
| 388 |
+
self.tone_emb = nn.Embedding(NUM_TONES, hidden_channels)
|
| 389 |
+
nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels**-0.5)
|
| 390 |
+
self.language_emb = nn.Embedding(NUM_LANGUAGES, hidden_channels)
|
| 391 |
+
nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels**-0.5)
|
| 392 |
+
self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
|
| 393 |
+
|
| 394 |
+
# Remove emo_vq since it's not working well.
|
| 395 |
+
self.style_proj = nn.Linear(256, hidden_channels)
|
| 396 |
+
|
| 397 |
+
self.encoder = attentions.Encoder(
|
| 398 |
+
hidden_channels,
|
| 399 |
+
filter_channels,
|
| 400 |
+
n_heads,
|
| 401 |
+
n_layers,
|
| 402 |
+
kernel_size,
|
| 403 |
+
p_dropout,
|
| 404 |
+
gin_channels=self.gin_channels,
|
| 405 |
+
)
|
| 406 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
| 407 |
+
|
| 408 |
+
def forward(
|
| 409 |
+
self,
|
| 410 |
+
x: torch.Tensor,
|
| 411 |
+
x_lengths: torch.Tensor,
|
| 412 |
+
tone: torch.Tensor,
|
| 413 |
+
language: torch.Tensor,
|
| 414 |
+
bert: torch.Tensor,
|
| 415 |
+
style_vec: torch.Tensor,
|
| 416 |
+
g: Optional[torch.Tensor] = None,
|
| 417 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 418 |
+
bert_emb = self.bert_proj(bert).transpose(1, 2)
|
| 419 |
+
style_emb = self.style_proj(style_vec.unsqueeze(1))
|
| 420 |
+
x = (
|
| 421 |
+
self.emb(x)
|
| 422 |
+
+ self.tone_emb(tone)
|
| 423 |
+
+ self.language_emb(language)
|
| 424 |
+
+ bert_emb
|
| 425 |
+
+ style_emb
|
| 426 |
+
) * math.sqrt(
|
| 427 |
+
self.hidden_channels
|
| 428 |
+
) # [b, t, h]
|
| 429 |
+
x = torch.transpose(x, 1, -1) # [b, h, t]
|
| 430 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
|
| 431 |
+
x.dtype
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
x = self.encoder(x * x_mask, x_mask, g=g)
|
| 435 |
+
stats = self.proj(x) * x_mask
|
| 436 |
+
|
| 437 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
| 438 |
+
return x, m, logs, x_mask
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
class ResidualCouplingBlock(nn.Module):
|
| 442 |
+
def __init__(
|
| 443 |
+
self,
|
| 444 |
+
channels: int,
|
| 445 |
+
hidden_channels: int,
|
| 446 |
+
kernel_size: int,
|
| 447 |
+
dilation_rate: int,
|
| 448 |
+
n_layers: int,
|
| 449 |
+
n_flows: int = 4,
|
| 450 |
+
gin_channels: int = 0,
|
| 451 |
+
) -> None:
|
| 452 |
+
super().__init__()
|
| 453 |
+
self.channels = channels
|
| 454 |
+
self.hidden_channels = hidden_channels
|
| 455 |
+
self.kernel_size = kernel_size
|
| 456 |
+
self.dilation_rate = dilation_rate
|
| 457 |
+
self.n_layers = n_layers
|
| 458 |
+
self.n_flows = n_flows
|
| 459 |
+
self.gin_channels = gin_channels
|
| 460 |
+
|
| 461 |
+
self.flows = nn.ModuleList()
|
| 462 |
+
for i in range(n_flows):
|
| 463 |
+
self.flows.append(
|
| 464 |
+
modules.ResidualCouplingLayer(
|
| 465 |
+
channels,
|
| 466 |
+
hidden_channels,
|
| 467 |
+
kernel_size,
|
| 468 |
+
dilation_rate,
|
| 469 |
+
n_layers,
|
| 470 |
+
gin_channels=gin_channels,
|
| 471 |
+
mean_only=True,
|
| 472 |
+
)
|
| 473 |
+
)
|
| 474 |
+
self.flows.append(modules.Flip())
|
| 475 |
+
|
| 476 |
+
def forward(
|
| 477 |
+
self,
|
| 478 |
+
x: torch.Tensor,
|
| 479 |
+
x_mask: torch.Tensor,
|
| 480 |
+
g: Optional[torch.Tensor] = None,
|
| 481 |
+
reverse: bool = False,
|
| 482 |
+
) -> torch.Tensor:
|
| 483 |
+
if not reverse:
|
| 484 |
+
for flow in self.flows:
|
| 485 |
+
x, _ = flow(x, x_mask, g=g, reverse=reverse)
|
| 486 |
+
else:
|
| 487 |
+
for flow in reversed(self.flows):
|
| 488 |
+
x = flow(x, x_mask, g=g, reverse=reverse)
|
| 489 |
+
return x
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
class PosteriorEncoder(nn.Module):
|
| 493 |
+
def __init__(
|
| 494 |
+
self,
|
| 495 |
+
in_channels: int,
|
| 496 |
+
out_channels: int,
|
| 497 |
+
hidden_channels: int,
|
| 498 |
+
kernel_size: int,
|
| 499 |
+
dilation_rate: int,
|
| 500 |
+
n_layers: int,
|
| 501 |
+
gin_channels: int = 0,
|
| 502 |
+
) -> None:
|
| 503 |
+
super().__init__()
|
| 504 |
+
self.in_channels = in_channels
|
| 505 |
+
self.out_channels = out_channels
|
| 506 |
+
self.hidden_channels = hidden_channels
|
| 507 |
+
self.kernel_size = kernel_size
|
| 508 |
+
self.dilation_rate = dilation_rate
|
| 509 |
+
self.n_layers = n_layers
|
| 510 |
+
self.gin_channels = gin_channels
|
| 511 |
+
|
| 512 |
+
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
|
| 513 |
+
self.enc = modules.WN(
|
| 514 |
+
hidden_channels,
|
| 515 |
+
kernel_size,
|
| 516 |
+
dilation_rate,
|
| 517 |
+
n_layers,
|
| 518 |
+
gin_channels=gin_channels,
|
| 519 |
+
)
|
| 520 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
|
| 521 |
+
|
| 522 |
+
def forward(
|
| 523 |
+
self,
|
| 524 |
+
x: torch.Tensor,
|
| 525 |
+
x_lengths: torch.Tensor,
|
| 526 |
+
g: Optional[torch.Tensor] = None,
|
| 527 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 528 |
+
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
|
| 529 |
+
x.dtype
|
| 530 |
+
)
|
| 531 |
+
x = self.pre(x) * x_mask
|
| 532 |
+
x = self.enc(x, x_mask, g=g)
|
| 533 |
+
stats = self.proj(x) * x_mask
|
| 534 |
+
m, logs = torch.split(stats, self.out_channels, dim=1)
|
| 535 |
+
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
|
| 536 |
+
return z, m, logs, x_mask
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
class Generator(torch.nn.Module):
|
| 540 |
+
def __init__(
|
| 541 |
+
self,
|
| 542 |
+
initial_channel: int,
|
| 543 |
+
resblock_str: str,
|
| 544 |
+
resblock_kernel_sizes: list[int],
|
| 545 |
+
resblock_dilation_sizes: list[list[int]],
|
| 546 |
+
upsample_rates: list[int],
|
| 547 |
+
upsample_initial_channel: int,
|
| 548 |
+
upsample_kernel_sizes: list[int],
|
| 549 |
+
gin_channels: int = 0,
|
| 550 |
+
) -> None:
|
| 551 |
+
super(Generator, self).__init__()
|
| 552 |
+
self.num_kernels = len(resblock_kernel_sizes)
|
| 553 |
+
self.num_upsamples = len(upsample_rates)
|
| 554 |
+
self.conv_pre = Conv1d(
|
| 555 |
+
initial_channel, upsample_initial_channel, 7, 1, padding=3
|
| 556 |
+
)
|
| 557 |
+
resblock = modules.ResBlock1 if resblock_str == "1" else modules.ResBlock2
|
| 558 |
+
|
| 559 |
+
self.ups = nn.ModuleList()
|
| 560 |
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
| 561 |
+
self.ups.append(
|
| 562 |
+
weight_norm(
|
| 563 |
+
ConvTranspose1d(
|
| 564 |
+
upsample_initial_channel // (2**i),
|
| 565 |
+
upsample_initial_channel // (2 ** (i + 1)),
|
| 566 |
+
k,
|
| 567 |
+
u,
|
| 568 |
+
padding=(k - u) // 2,
|
| 569 |
+
)
|
| 570 |
+
)
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
self.resblocks = nn.ModuleList()
|
| 574 |
+
ch = None
|
| 575 |
+
for i in range(len(self.ups)):
|
| 576 |
+
ch = upsample_initial_channel // (2 ** (i + 1))
|
| 577 |
+
for j, (k, d) in enumerate(
|
| 578 |
+
zip(resblock_kernel_sizes, resblock_dilation_sizes)
|
| 579 |
+
):
|
| 580 |
+
self.resblocks.append(resblock(ch, k, d)) # type: ignore
|
| 581 |
+
|
| 582 |
+
assert ch is not None
|
| 583 |
+
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
| 584 |
+
self.ups.apply(commons.init_weights)
|
| 585 |
+
|
| 586 |
+
if gin_channels != 0:
|
| 587 |
+
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
|
| 588 |
+
|
| 589 |
+
def forward(
|
| 590 |
+
self, x: torch.Tensor, g: Optional[torch.Tensor] = None
|
| 591 |
+
) -> torch.Tensor:
|
| 592 |
+
x = self.conv_pre(x)
|
| 593 |
+
if g is not None:
|
| 594 |
+
x = x + self.cond(g)
|
| 595 |
+
|
| 596 |
+
for i in range(self.num_upsamples):
|
| 597 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 598 |
+
x = self.ups[i](x)
|
| 599 |
+
xs = None
|
| 600 |
+
for j in range(self.num_kernels):
|
| 601 |
+
if xs is None:
|
| 602 |
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
| 603 |
+
else:
|
| 604 |
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
| 605 |
+
assert xs is not None
|
| 606 |
+
x = xs / self.num_kernels
|
| 607 |
+
x = F.leaky_relu(x)
|
| 608 |
+
x = self.conv_post(x)
|
| 609 |
+
x = torch.tanh(x)
|
| 610 |
+
|
| 611 |
+
return x
|
| 612 |
+
|
| 613 |
+
def remove_weight_norm(self) -> None:
|
| 614 |
+
print("Removing weight norm...")
|
| 615 |
+
for layer in self.ups:
|
| 616 |
+
remove_weight_norm(layer)
|
| 617 |
+
for layer in self.resblocks:
|
| 618 |
+
layer.remove_weight_norm()
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
class DiscriminatorP(torch.nn.Module):
|
| 622 |
+
def __init__(
|
| 623 |
+
self,
|
| 624 |
+
period: int,
|
| 625 |
+
kernel_size: int = 5,
|
| 626 |
+
stride: int = 3,
|
| 627 |
+
use_spectral_norm: bool = False,
|
| 628 |
+
) -> None:
|
| 629 |
+
super(DiscriminatorP, self).__init__()
|
| 630 |
+
self.period = period
|
| 631 |
+
self.use_spectral_norm = use_spectral_norm
|
| 632 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
| 633 |
+
self.convs = nn.ModuleList(
|
| 634 |
+
[
|
| 635 |
+
norm_f(
|
| 636 |
+
Conv2d(
|
| 637 |
+
1,
|
| 638 |
+
32,
|
| 639 |
+
(kernel_size, 1),
|
| 640 |
+
(stride, 1),
|
| 641 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 642 |
+
)
|
| 643 |
+
),
|
| 644 |
+
norm_f(
|
| 645 |
+
Conv2d(
|
| 646 |
+
32,
|
| 647 |
+
128,
|
| 648 |
+
(kernel_size, 1),
|
| 649 |
+
(stride, 1),
|
| 650 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 651 |
+
)
|
| 652 |
+
),
|
| 653 |
+
norm_f(
|
| 654 |
+
Conv2d(
|
| 655 |
+
128,
|
| 656 |
+
512,
|
| 657 |
+
(kernel_size, 1),
|
| 658 |
+
(stride, 1),
|
| 659 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 660 |
+
)
|
| 661 |
+
),
|
| 662 |
+
norm_f(
|
| 663 |
+
Conv2d(
|
| 664 |
+
512,
|
| 665 |
+
1024,
|
| 666 |
+
(kernel_size, 1),
|
| 667 |
+
(stride, 1),
|
| 668 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 669 |
+
)
|
| 670 |
+
),
|
| 671 |
+
norm_f(
|
| 672 |
+
Conv2d(
|
| 673 |
+
1024,
|
| 674 |
+
1024,
|
| 675 |
+
(kernel_size, 1),
|
| 676 |
+
1,
|
| 677 |
+
padding=(commons.get_padding(kernel_size, 1), 0),
|
| 678 |
+
)
|
| 679 |
+
),
|
| 680 |
+
]
|
| 681 |
+
)
|
| 682 |
+
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
|
| 683 |
+
|
| 684 |
+
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, list[torch.Tensor]]:
|
| 685 |
+
fmap = []
|
| 686 |
+
|
| 687 |
+
# 1d to 2d
|
| 688 |
+
b, c, t = x.shape
|
| 689 |
+
if t % self.period != 0: # pad first
|
| 690 |
+
n_pad = self.period - (t % self.period)
|
| 691 |
+
x = F.pad(x, (0, n_pad), "reflect")
|
| 692 |
+
t = t + n_pad
|
| 693 |
+
x = x.view(b, c, t // self.period, self.period)
|
| 694 |
+
|
| 695 |
+
for layer in self.convs:
|
| 696 |
+
x = layer(x)
|
| 697 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 698 |
+
fmap.append(x)
|
| 699 |
+
x = self.conv_post(x)
|
| 700 |
+
fmap.append(x)
|
| 701 |
+
x = torch.flatten(x, 1, -1)
|
| 702 |
+
|
| 703 |
+
return x, fmap
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
class DiscriminatorS(torch.nn.Module):
|
| 707 |
+
def __init__(self, use_spectral_norm: bool = False) -> None:
|
| 708 |
+
super(DiscriminatorS, self).__init__()
|
| 709 |
+
norm_f = weight_norm if use_spectral_norm is False else spectral_norm
|
| 710 |
+
self.convs = nn.ModuleList(
|
| 711 |
+
[
|
| 712 |
+
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
|
| 713 |
+
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
|
| 714 |
+
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
|
| 715 |
+
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
|
| 716 |
+
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
|
| 717 |
+
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
|
| 718 |
+
]
|
| 719 |
+
)
|
| 720 |
+
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
|
| 721 |
+
|
| 722 |
+
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, list[torch.Tensor]]:
|
| 723 |
+
fmap = []
|
| 724 |
+
|
| 725 |
+
for layer in self.convs:
|
| 726 |
+
x = layer(x)
|
| 727 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 728 |
+
fmap.append(x)
|
| 729 |
+
x = self.conv_post(x)
|
| 730 |
+
fmap.append(x)
|
| 731 |
+
x = torch.flatten(x, 1, -1)
|
| 732 |
+
|
| 733 |
+
return x, fmap
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class MultiPeriodDiscriminator(torch.nn.Module):
|
| 737 |
+
def __init__(self, use_spectral_norm: bool = False) -> None:
|
| 738 |
+
super(MultiPeriodDiscriminator, self).__init__()
|
| 739 |
+
periods = [2, 3, 5, 7, 11]
|
| 740 |
+
|
| 741 |
+
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
|
| 742 |
+
discs = discs + [
|
| 743 |
+
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
|
| 744 |
+
]
|
| 745 |
+
self.discriminators = nn.ModuleList(discs)
|
| 746 |
+
|
| 747 |
+
def forward(
|
| 748 |
+
self,
|
| 749 |
+
y: torch.Tensor,
|
| 750 |
+
y_hat: torch.Tensor,
|
| 751 |
+
) -> tuple[
|
| 752 |
+
list[torch.Tensor], list[torch.Tensor], list[torch.Tensor], list[torch.Tensor]
|
| 753 |
+
]:
|
| 754 |
+
y_d_rs = []
|
| 755 |
+
y_d_gs = []
|
| 756 |
+
fmap_rs = []
|
| 757 |
+
fmap_gs = []
|
| 758 |
+
for i, d in enumerate(self.discriminators):
|
| 759 |
+
y_d_r, fmap_r = d(y)
|
| 760 |
+
y_d_g, fmap_g = d(y_hat)
|
| 761 |
+
y_d_rs.append(y_d_r)
|
| 762 |
+
y_d_gs.append(y_d_g)
|
| 763 |
+
fmap_rs.append(fmap_r)
|
| 764 |
+
fmap_gs.append(fmap_g)
|
| 765 |
+
|
| 766 |
+
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
class WavLMDiscriminator(nn.Module):
|
| 770 |
+
"""docstring for Discriminator."""
|
| 771 |
+
|
| 772 |
+
def __init__(
|
| 773 |
+
self,
|
| 774 |
+
slm_hidden: int = 768,
|
| 775 |
+
slm_layers: int = 13,
|
| 776 |
+
initial_channel: int = 64,
|
| 777 |
+
use_spectral_norm: bool = False,
|
| 778 |
+
) -> None:
|
| 779 |
+
super(WavLMDiscriminator, self).__init__()
|
| 780 |
+
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
|
| 781 |
+
self.pre = norm_f(
|
| 782 |
+
Conv1d(slm_hidden * slm_layers, initial_channel, 1, 1, padding=0)
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
self.convs = nn.ModuleList(
|
| 786 |
+
[
|
| 787 |
+
norm_f(
|
| 788 |
+
nn.Conv1d(
|
| 789 |
+
initial_channel, initial_channel * 2, kernel_size=5, padding=2
|
| 790 |
+
)
|
| 791 |
+
),
|
| 792 |
+
norm_f(
|
| 793 |
+
nn.Conv1d(
|
| 794 |
+
initial_channel * 2,
|
| 795 |
+
initial_channel * 4,
|
| 796 |
+
kernel_size=5,
|
| 797 |
+
padding=2,
|
| 798 |
+
)
|
| 799 |
+
),
|
| 800 |
+
norm_f(
|
| 801 |
+
nn.Conv1d(initial_channel * 4, initial_channel * 4, 5, 1, padding=2)
|
| 802 |
+
),
|
| 803 |
+
]
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
self.conv_post = norm_f(Conv1d(initial_channel * 4, 1, 3, 1, padding=1))
|
| 807 |
+
|
| 808 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 809 |
+
x = self.pre(x)
|
| 810 |
+
|
| 811 |
+
fmap = []
|
| 812 |
+
for l in self.convs:
|
| 813 |
+
x = l(x)
|
| 814 |
+
x = F.leaky_relu(x, modules.LRELU_SLOPE)
|
| 815 |
+
fmap.append(x)
|
| 816 |
+
x = self.conv_post(x)
|
| 817 |
+
x = torch.flatten(x, 1, -1)
|
| 818 |
+
|
| 819 |
+
return x
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
class ReferenceEncoder(nn.Module):
|
| 823 |
+
"""
|
| 824 |
+
inputs --- [N, Ty/r, n_mels*r] mels
|
| 825 |
+
outputs --- [N, ref_enc_gru_size]
|
| 826 |
+
"""
|
| 827 |
+
|
| 828 |
+
def __init__(self, spec_channels: int, gin_channels: int = 0) -> None:
|
| 829 |
+
super().__init__()
|
| 830 |
+
self.spec_channels = spec_channels
|
| 831 |
+
ref_enc_filters = [32, 32, 64, 64, 128, 128]
|
| 832 |
+
K = len(ref_enc_filters)
|
| 833 |
+
filters = [1] + ref_enc_filters
|
| 834 |
+
convs = [
|
| 835 |
+
weight_norm(
|
| 836 |
+
nn.Conv2d(
|
| 837 |
+
in_channels=filters[i],
|
| 838 |
+
out_channels=filters[i + 1],
|
| 839 |
+
kernel_size=(3, 3),
|
| 840 |
+
stride=(2, 2),
|
| 841 |
+
padding=(1, 1),
|
| 842 |
+
)
|
| 843 |
+
)
|
| 844 |
+
for i in range(K)
|
| 845 |
+
]
|
| 846 |
+
self.convs = nn.ModuleList(convs)
|
| 847 |
+
# self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)])
|
| 848 |
+
|
| 849 |
+
out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
|
| 850 |
+
self.gru = nn.GRU(
|
| 851 |
+
input_size=ref_enc_filters[-1] * out_channels,
|
| 852 |
+
hidden_size=256 // 2,
|
| 853 |
+
batch_first=True,
|
| 854 |
+
)
|
| 855 |
+
self.proj = nn.Linear(128, gin_channels)
|
| 856 |
+
|
| 857 |
+
def forward(
|
| 858 |
+
self, inputs: torch.Tensor, mask: Optional[torch.Tensor] = None
|
| 859 |
+
) -> torch.Tensor:
|
| 860 |
+
N = inputs.size(0)
|
| 861 |
+
out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
|
| 862 |
+
for conv in self.convs:
|
| 863 |
+
out = conv(out)
|
| 864 |
+
# out = wn(out)
|
| 865 |
+
out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
|
| 866 |
+
|
| 867 |
+
out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
|
| 868 |
+
T = out.size(1)
|
| 869 |
+
N = out.size(0)
|
| 870 |
+
out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
|
| 871 |
+
|
| 872 |
+
self.gru.flatten_parameters()
|
| 873 |
+
memory, out = self.gru(out) # out --- [1, N, 128]
|
| 874 |
+
|
| 875 |
+
return self.proj(out.squeeze(0))
|
| 876 |
+
|
| 877 |
+
def calculate_channels(
|
| 878 |
+
self, L: int, kernel_size: int, stride: int, pad: int, n_convs: int
|
| 879 |
+
) -> int:
|
| 880 |
+
for i in range(n_convs):
|
| 881 |
+
L = (L - kernel_size + 2 * pad) // stride + 1
|
| 882 |
+
return L
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
class SynthesizerTrn(nn.Module):
|
| 886 |
+
"""
|
| 887 |
+
Synthesizer for Training
|
| 888 |
+
"""
|
| 889 |
+
|
| 890 |
+
def __init__(
|
| 891 |
+
self,
|
| 892 |
+
n_vocab: int,
|
| 893 |
+
spec_channels: int,
|
| 894 |
+
segment_size: int,
|
| 895 |
+
inter_channels: int,
|
| 896 |
+
hidden_channels: int,
|
| 897 |
+
filter_channels: int,
|
| 898 |
+
n_heads: int,
|
| 899 |
+
n_layers: int,
|
| 900 |
+
kernel_size: int,
|
| 901 |
+
p_dropout: float,
|
| 902 |
+
resblock: str,
|
| 903 |
+
resblock_kernel_sizes: list[int],
|
| 904 |
+
resblock_dilation_sizes: list[list[int]],
|
| 905 |
+
upsample_rates: list[int],
|
| 906 |
+
upsample_initial_channel: int,
|
| 907 |
+
upsample_kernel_sizes: list[int],
|
| 908 |
+
n_speakers: int = 256,
|
| 909 |
+
gin_channels: int = 256,
|
| 910 |
+
use_sdp: bool = True,
|
| 911 |
+
n_flow_layer: int = 4,
|
| 912 |
+
n_layers_trans_flow: int = 6,
|
| 913 |
+
flow_share_parameter: bool = False,
|
| 914 |
+
use_transformer_flow: bool = True,
|
| 915 |
+
**kwargs: Any,
|
| 916 |
+
) -> None:
|
| 917 |
+
super().__init__()
|
| 918 |
+
self.n_vocab = n_vocab
|
| 919 |
+
self.spec_channels = spec_channels
|
| 920 |
+
self.inter_channels = inter_channels
|
| 921 |
+
self.hidden_channels = hidden_channels
|
| 922 |
+
self.filter_channels = filter_channels
|
| 923 |
+
self.n_heads = n_heads
|
| 924 |
+
self.n_layers = n_layers
|
| 925 |
+
self.kernel_size = kernel_size
|
| 926 |
+
self.p_dropout = p_dropout
|
| 927 |
+
self.resblock = resblock
|
| 928 |
+
self.resblock_kernel_sizes = resblock_kernel_sizes
|
| 929 |
+
self.resblock_dilation_sizes = resblock_dilation_sizes
|
| 930 |
+
self.upsample_rates = upsample_rates
|
| 931 |
+
self.upsample_initial_channel = upsample_initial_channel
|
| 932 |
+
self.upsample_kernel_sizes = upsample_kernel_sizes
|
| 933 |
+
self.segment_size = segment_size
|
| 934 |
+
self.n_speakers = n_speakers
|
| 935 |
+
self.gin_channels = gin_channels
|
| 936 |
+
self.n_layers_trans_flow = n_layers_trans_flow
|
| 937 |
+
self.use_spk_conditioned_encoder = kwargs.get(
|
| 938 |
+
"use_spk_conditioned_encoder", True
|
| 939 |
+
)
|
| 940 |
+
self.use_sdp = use_sdp
|
| 941 |
+
self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
|
| 942 |
+
self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
|
| 943 |
+
self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
|
| 944 |
+
self.current_mas_noise_scale = self.mas_noise_scale_initial
|
| 945 |
+
if self.use_spk_conditioned_encoder and gin_channels > 0:
|
| 946 |
+
self.enc_gin_channels = gin_channels
|
| 947 |
+
self.enc_p = TextEncoder(
|
| 948 |
+
n_vocab,
|
| 949 |
+
inter_channels,
|
| 950 |
+
hidden_channels,
|
| 951 |
+
filter_channels,
|
| 952 |
+
n_heads,
|
| 953 |
+
n_layers,
|
| 954 |
+
kernel_size,
|
| 955 |
+
p_dropout,
|
| 956 |
+
gin_channels=self.enc_gin_channels,
|
| 957 |
+
)
|
| 958 |
+
self.dec = Generator(
|
| 959 |
+
inter_channels,
|
| 960 |
+
resblock,
|
| 961 |
+
resblock_kernel_sizes,
|
| 962 |
+
resblock_dilation_sizes,
|
| 963 |
+
upsample_rates,
|
| 964 |
+
upsample_initial_channel,
|
| 965 |
+
upsample_kernel_sizes,
|
| 966 |
+
gin_channels=gin_channels,
|
| 967 |
+
)
|
| 968 |
+
self.enc_q = PosteriorEncoder(
|
| 969 |
+
spec_channels,
|
| 970 |
+
inter_channels,
|
| 971 |
+
hidden_channels,
|
| 972 |
+
5,
|
| 973 |
+
1,
|
| 974 |
+
16,
|
| 975 |
+
gin_channels=gin_channels,
|
| 976 |
+
)
|
| 977 |
+
if use_transformer_flow:
|
| 978 |
+
self.flow = TransformerCouplingBlock(
|
| 979 |
+
inter_channels,
|
| 980 |
+
hidden_channels,
|
| 981 |
+
filter_channels,
|
| 982 |
+
n_heads,
|
| 983 |
+
n_layers_trans_flow,
|
| 984 |
+
5,
|
| 985 |
+
p_dropout,
|
| 986 |
+
n_flow_layer,
|
| 987 |
+
gin_channels=gin_channels,
|
| 988 |
+
share_parameter=flow_share_parameter,
|
| 989 |
+
)
|
| 990 |
+
else:
|
| 991 |
+
self.flow = ResidualCouplingBlock(
|
| 992 |
+
inter_channels,
|
| 993 |
+
hidden_channels,
|
| 994 |
+
5,
|
| 995 |
+
1,
|
| 996 |
+
n_flow_layer,
|
| 997 |
+
gin_channels=gin_channels,
|
| 998 |
+
)
|
| 999 |
+
self.sdp = StochasticDurationPredictor(
|
| 1000 |
+
hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels
|
| 1001 |
+
)
|
| 1002 |
+
self.dp = DurationPredictor(
|
| 1003 |
+
hidden_channels, 256, 3, 0.5, gin_channels=gin_channels
|
| 1004 |
+
)
|
| 1005 |
+
|
| 1006 |
+
if n_speakers >= 1:
|
| 1007 |
+
self.emb_g = nn.Embedding(n_speakers, gin_channels)
|
| 1008 |
+
else:
|
| 1009 |
+
self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
|
| 1010 |
+
|
| 1011 |
+
def forward(
|
| 1012 |
+
self,
|
| 1013 |
+
x: torch.Tensor,
|
| 1014 |
+
x_lengths: torch.Tensor,
|
| 1015 |
+
y: torch.Tensor,
|
| 1016 |
+
y_lengths: torch.Tensor,
|
| 1017 |
+
sid: torch.Tensor,
|
| 1018 |
+
tone: torch.Tensor,
|
| 1019 |
+
language: torch.Tensor,
|
| 1020 |
+
bert: torch.Tensor,
|
| 1021 |
+
style_vec: torch.Tensor,
|
| 1022 |
+
) -> tuple[
|
| 1023 |
+
torch.Tensor,
|
| 1024 |
+
torch.Tensor,
|
| 1025 |
+
torch.Tensor,
|
| 1026 |
+
torch.Tensor,
|
| 1027 |
+
torch.Tensor,
|
| 1028 |
+
torch.Tensor,
|
| 1029 |
+
torch.Tensor,
|
| 1030 |
+
tuple[torch.Tensor, ...],
|
| 1031 |
+
tuple[torch.Tensor, ...],
|
| 1032 |
+
]:
|
| 1033 |
+
if self.n_speakers > 0:
|
| 1034 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
| 1035 |
+
else:
|
| 1036 |
+
g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
|
| 1037 |
+
x, m_p, logs_p, x_mask = self.enc_p(
|
| 1038 |
+
x, x_lengths, tone, language, bert, style_vec, g=g
|
| 1039 |
+
)
|
| 1040 |
+
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
|
| 1041 |
+
z_p = self.flow(z, y_mask, g=g)
|
| 1042 |
+
|
| 1043 |
+
with torch.no_grad():
|
| 1044 |
+
# negative cross-entropy
|
| 1045 |
+
s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
|
| 1046 |
+
neg_cent1 = torch.sum(
|
| 1047 |
+
-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True
|
| 1048 |
+
) # [b, 1, t_s]
|
| 1049 |
+
neg_cent2 = torch.matmul(
|
| 1050 |
+
-0.5 * (z_p**2).transpose(1, 2), s_p_sq_r
|
| 1051 |
+
) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
| 1052 |
+
neg_cent3 = torch.matmul(
|
| 1053 |
+
z_p.transpose(1, 2), (m_p * s_p_sq_r)
|
| 1054 |
+
) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
|
| 1055 |
+
neg_cent4 = torch.sum(
|
| 1056 |
+
-0.5 * (m_p**2) * s_p_sq_r, [1], keepdim=True
|
| 1057 |
+
) # [b, 1, t_s]
|
| 1058 |
+
neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
|
| 1059 |
+
if self.use_noise_scaled_mas:
|
| 1060 |
+
epsilon = (
|
| 1061 |
+
torch.std(neg_cent)
|
| 1062 |
+
* torch.randn_like(neg_cent)
|
| 1063 |
+
* self.current_mas_noise_scale
|
| 1064 |
+
)
|
| 1065 |
+
neg_cent = neg_cent + epsilon
|
| 1066 |
+
|
| 1067 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
| 1068 |
+
attn = (
|
| 1069 |
+
monotonic_alignment.maximum_path(neg_cent, attn_mask.squeeze(1))
|
| 1070 |
+
.unsqueeze(1)
|
| 1071 |
+
.detach()
|
| 1072 |
+
)
|
| 1073 |
+
|
| 1074 |
+
w = attn.sum(2)
|
| 1075 |
+
|
| 1076 |
+
l_length_sdp = self.sdp(x, x_mask, w, g=g)
|
| 1077 |
+
l_length_sdp = l_length_sdp / torch.sum(x_mask)
|
| 1078 |
+
|
| 1079 |
+
logw_ = torch.log(w + 1e-6) * x_mask
|
| 1080 |
+
logw = self.dp(x, x_mask, g=g)
|
| 1081 |
+
# logw_sdp = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=1.0)
|
| 1082 |
+
l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(
|
| 1083 |
+
x_mask
|
| 1084 |
+
) # for averaging
|
| 1085 |
+
# l_length_sdp += torch.sum((logw_sdp - logw_) ** 2, [1, 2]) / torch.sum(x_mask)
|
| 1086 |
+
|
| 1087 |
+
l_length = l_length_dp + l_length_sdp
|
| 1088 |
+
|
| 1089 |
+
# expand prior
|
| 1090 |
+
m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
|
| 1091 |
+
logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
|
| 1092 |
+
|
| 1093 |
+
z_slice, ids_slice = commons.rand_slice_segments(
|
| 1094 |
+
z, y_lengths, self.segment_size
|
| 1095 |
+
)
|
| 1096 |
+
o = self.dec(z_slice, g=g)
|
| 1097 |
+
return (
|
| 1098 |
+
o,
|
| 1099 |
+
l_length,
|
| 1100 |
+
attn,
|
| 1101 |
+
ids_slice,
|
| 1102 |
+
x_mask,
|
| 1103 |
+
y_mask,
|
| 1104 |
+
(z, z_p, m_p, logs_p, m_q, logs_q), # type: ignore
|
| 1105 |
+
(x, logw, logw_), # , logw_sdp),
|
| 1106 |
+
g,
|
| 1107 |
+
)
|
| 1108 |
+
|
| 1109 |
+
def infer(
|
| 1110 |
+
self,
|
| 1111 |
+
x: torch.Tensor,
|
| 1112 |
+
x_lengths: torch.Tensor,
|
| 1113 |
+
sid: torch.Tensor,
|
| 1114 |
+
tone: torch.Tensor,
|
| 1115 |
+
language: torch.Tensor,
|
| 1116 |
+
bert: torch.Tensor,
|
| 1117 |
+
style_vec: torch.Tensor,
|
| 1118 |
+
noise_scale: float = 0.667,
|
| 1119 |
+
length_scale: float = 1.0,
|
| 1120 |
+
noise_scale_w: float = 0.8,
|
| 1121 |
+
max_len: Optional[int] = None,
|
| 1122 |
+
sdp_ratio: float = 0.0,
|
| 1123 |
+
y: Optional[torch.Tensor] = None,
|
| 1124 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor, ...]]:
|
| 1125 |
+
# x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
|
| 1126 |
+
# g = self.gst(y)
|
| 1127 |
+
if self.n_speakers > 0:
|
| 1128 |
+
g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
|
| 1129 |
+
else:
|
| 1130 |
+
assert y is not None
|
| 1131 |
+
g = self.ref_enc(y.transpose(1, 2)).unsqueeze(-1)
|
| 1132 |
+
x, m_p, logs_p, x_mask = self.enc_p(
|
| 1133 |
+
x, x_lengths, tone, language, bert, style_vec, g=g
|
| 1134 |
+
)
|
| 1135 |
+
logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (
|
| 1136 |
+
sdp_ratio
|
| 1137 |
+
) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
|
| 1138 |
+
w = torch.exp(logw) * x_mask * length_scale
|
| 1139 |
+
w_ceil = torch.ceil(w)
|
| 1140 |
+
y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
|
| 1141 |
+
y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(
|
| 1142 |
+
x_mask.dtype
|
| 1143 |
+
)
|
| 1144 |
+
attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
|
| 1145 |
+
attn = commons.generate_path(w_ceil, attn_mask)
|
| 1146 |
+
|
| 1147 |
+
m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(
|
| 1148 |
+
1, 2
|
| 1149 |
+
) # [b, t', t], [b, t, d] -> [b, d, t']
|
| 1150 |
+
logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(
|
| 1151 |
+
1, 2
|
| 1152 |
+
) # [b, t', t], [b, t, d] -> [b, d, t']
|
| 1153 |
+
|
| 1154 |
+
z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
|
| 1155 |
+
z = self.flow(z_p, y_mask, g=g, reverse=True)
|
| 1156 |
+
o = self.dec((z * y_mask)[:, :, :max_len], g=g)
|
| 1157 |
+
return o, attn, y_mask, (z, z_p, m_p, logs_p)
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/modules.py
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import Any, Optional, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.nn import Conv1d
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from torch.nn.utils import remove_weight_norm, weight_norm
|
| 9 |
+
|
| 10 |
+
from style_bert_vits2.models import commons
|
| 11 |
+
from style_bert_vits2.models.attentions import Encoder
|
| 12 |
+
from style_bert_vits2.models.transforms import piecewise_rational_quadratic_transform
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
LRELU_SLOPE = 0.1
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class LayerNorm(nn.Module):
|
| 19 |
+
def __init__(self, channels: int, eps: float = 1e-5) -> None:
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.channels = channels
|
| 22 |
+
self.eps = eps
|
| 23 |
+
|
| 24 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
| 25 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
| 26 |
+
|
| 27 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 28 |
+
x = x.transpose(1, -1)
|
| 29 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
| 30 |
+
return x.transpose(1, -1)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ConvReluNorm(nn.Module):
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
in_channels: int,
|
| 37 |
+
hidden_channels: int,
|
| 38 |
+
out_channels: int,
|
| 39 |
+
kernel_size: int,
|
| 40 |
+
n_layers: int,
|
| 41 |
+
p_dropout: float,
|
| 42 |
+
) -> None:
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.in_channels = in_channels
|
| 45 |
+
self.hidden_channels = hidden_channels
|
| 46 |
+
self.out_channels = out_channels
|
| 47 |
+
self.kernel_size = kernel_size
|
| 48 |
+
self.n_layers = n_layers
|
| 49 |
+
self.p_dropout = p_dropout
|
| 50 |
+
assert n_layers > 1, "Number of layers should be larger than 0."
|
| 51 |
+
|
| 52 |
+
self.conv_layers = nn.ModuleList()
|
| 53 |
+
self.norm_layers = nn.ModuleList()
|
| 54 |
+
self.conv_layers.append(
|
| 55 |
+
nn.Conv1d(
|
| 56 |
+
in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
|
| 57 |
+
)
|
| 58 |
+
)
|
| 59 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
| 60 |
+
self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
|
| 61 |
+
for _ in range(n_layers - 1):
|
| 62 |
+
self.conv_layers.append(
|
| 63 |
+
nn.Conv1d(
|
| 64 |
+
hidden_channels,
|
| 65 |
+
hidden_channels,
|
| 66 |
+
kernel_size,
|
| 67 |
+
padding=kernel_size // 2,
|
| 68 |
+
)
|
| 69 |
+
)
|
| 70 |
+
self.norm_layers.append(LayerNorm(hidden_channels))
|
| 71 |
+
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
| 72 |
+
self.proj.weight.data.zero_()
|
| 73 |
+
assert self.proj.bias is not None
|
| 74 |
+
self.proj.bias.data.zero_()
|
| 75 |
+
|
| 76 |
+
def forward(self, x: torch.Tensor, x_mask: torch.Tensor) -> torch.Tensor:
|
| 77 |
+
x_org = x
|
| 78 |
+
for i in range(self.n_layers):
|
| 79 |
+
x = self.conv_layers[i](x * x_mask)
|
| 80 |
+
x = self.norm_layers[i](x)
|
| 81 |
+
x = self.relu_drop(x)
|
| 82 |
+
x = x_org + self.proj(x)
|
| 83 |
+
return x * x_mask
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class DDSConv(nn.Module):
|
| 87 |
+
"""
|
| 88 |
+
Dialted and Depth-Separable Convolution
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self, channels: int, kernel_size: int, n_layers: int, p_dropout: float = 0.0
|
| 93 |
+
) -> None:
|
| 94 |
+
super().__init__()
|
| 95 |
+
self.channels = channels
|
| 96 |
+
self.kernel_size = kernel_size
|
| 97 |
+
self.n_layers = n_layers
|
| 98 |
+
self.p_dropout = p_dropout
|
| 99 |
+
|
| 100 |
+
self.drop = nn.Dropout(p_dropout)
|
| 101 |
+
self.convs_sep = nn.ModuleList()
|
| 102 |
+
self.convs_1x1 = nn.ModuleList()
|
| 103 |
+
self.norms_1 = nn.ModuleList()
|
| 104 |
+
self.norms_2 = nn.ModuleList()
|
| 105 |
+
for i in range(n_layers):
|
| 106 |
+
dilation = kernel_size**i
|
| 107 |
+
padding = (kernel_size * dilation - dilation) // 2
|
| 108 |
+
self.convs_sep.append(
|
| 109 |
+
nn.Conv1d(
|
| 110 |
+
channels,
|
| 111 |
+
channels,
|
| 112 |
+
kernel_size,
|
| 113 |
+
groups=channels,
|
| 114 |
+
dilation=dilation,
|
| 115 |
+
padding=padding,
|
| 116 |
+
)
|
| 117 |
+
)
|
| 118 |
+
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
|
| 119 |
+
self.norms_1.append(LayerNorm(channels))
|
| 120 |
+
self.norms_2.append(LayerNorm(channels))
|
| 121 |
+
|
| 122 |
+
def forward(
|
| 123 |
+
self, x: torch.Tensor, x_mask: torch.Tensor, g: Optional[torch.Tensor] = None
|
| 124 |
+
) -> torch.Tensor:
|
| 125 |
+
if g is not None:
|
| 126 |
+
x = x + g
|
| 127 |
+
for i in range(self.n_layers):
|
| 128 |
+
y = self.convs_sep[i](x * x_mask)
|
| 129 |
+
y = self.norms_1[i](y)
|
| 130 |
+
y = F.gelu(y)
|
| 131 |
+
y = self.convs_1x1[i](y)
|
| 132 |
+
y = self.norms_2[i](y)
|
| 133 |
+
y = F.gelu(y)
|
| 134 |
+
y = self.drop(y)
|
| 135 |
+
x = x + y
|
| 136 |
+
return x * x_mask
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class WN(torch.nn.Module):
|
| 140 |
+
def __init__(
|
| 141 |
+
self,
|
| 142 |
+
hidden_channels: int,
|
| 143 |
+
kernel_size: int,
|
| 144 |
+
dilation_rate: int,
|
| 145 |
+
n_layers: int,
|
| 146 |
+
gin_channels: int = 0,
|
| 147 |
+
p_dropout: float = 0,
|
| 148 |
+
) -> None:
|
| 149 |
+
super(WN, self).__init__()
|
| 150 |
+
assert kernel_size % 2 == 1
|
| 151 |
+
self.hidden_channels = hidden_channels
|
| 152 |
+
self.kernel_size = (kernel_size,)
|
| 153 |
+
self.dilation_rate = dilation_rate
|
| 154 |
+
self.n_layers = n_layers
|
| 155 |
+
self.gin_channels = gin_channels
|
| 156 |
+
self.p_dropout = p_dropout
|
| 157 |
+
|
| 158 |
+
self.in_layers = torch.nn.ModuleList()
|
| 159 |
+
self.res_skip_layers = torch.nn.ModuleList()
|
| 160 |
+
self.drop = nn.Dropout(p_dropout)
|
| 161 |
+
|
| 162 |
+
if gin_channels != 0:
|
| 163 |
+
cond_layer = torch.nn.Conv1d(
|
| 164 |
+
gin_channels, 2 * hidden_channels * n_layers, 1
|
| 165 |
+
)
|
| 166 |
+
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
|
| 167 |
+
|
| 168 |
+
for i in range(n_layers):
|
| 169 |
+
dilation = dilation_rate**i
|
| 170 |
+
padding = int((kernel_size * dilation - dilation) / 2)
|
| 171 |
+
in_layer = torch.nn.Conv1d(
|
| 172 |
+
hidden_channels,
|
| 173 |
+
2 * hidden_channels,
|
| 174 |
+
kernel_size,
|
| 175 |
+
dilation=dilation,
|
| 176 |
+
padding=padding,
|
| 177 |
+
)
|
| 178 |
+
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
|
| 179 |
+
self.in_layers.append(in_layer)
|
| 180 |
+
|
| 181 |
+
# last one is not necessary
|
| 182 |
+
if i < n_layers - 1:
|
| 183 |
+
res_skip_channels = 2 * hidden_channels
|
| 184 |
+
else:
|
| 185 |
+
res_skip_channels = hidden_channels
|
| 186 |
+
|
| 187 |
+
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
|
| 188 |
+
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
|
| 189 |
+
self.res_skip_layers.append(res_skip_layer)
|
| 190 |
+
|
| 191 |
+
def forward(
|
| 192 |
+
self,
|
| 193 |
+
x: torch.Tensor,
|
| 194 |
+
x_mask: torch.Tensor,
|
| 195 |
+
g: Optional[torch.Tensor] = None,
|
| 196 |
+
**kwargs: Any,
|
| 197 |
+
) -> torch.Tensor:
|
| 198 |
+
output = torch.zeros_like(x)
|
| 199 |
+
n_channels_tensor = torch.IntTensor([self.hidden_channels])
|
| 200 |
+
|
| 201 |
+
if g is not None:
|
| 202 |
+
g = self.cond_layer(g)
|
| 203 |
+
|
| 204 |
+
for i in range(self.n_layers):
|
| 205 |
+
x_in = self.in_layers[i](x)
|
| 206 |
+
if g is not None:
|
| 207 |
+
cond_offset = i * 2 * self.hidden_channels
|
| 208 |
+
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
|
| 209 |
+
else:
|
| 210 |
+
g_l = torch.zeros_like(x_in)
|
| 211 |
+
|
| 212 |
+
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
|
| 213 |
+
acts = self.drop(acts)
|
| 214 |
+
|
| 215 |
+
res_skip_acts = self.res_skip_layers[i](acts)
|
| 216 |
+
if i < self.n_layers - 1:
|
| 217 |
+
res_acts = res_skip_acts[:, : self.hidden_channels, :]
|
| 218 |
+
x = (x + res_acts) * x_mask
|
| 219 |
+
output = output + res_skip_acts[:, self.hidden_channels :, :]
|
| 220 |
+
else:
|
| 221 |
+
output = output + res_skip_acts
|
| 222 |
+
return output * x_mask
|
| 223 |
+
|
| 224 |
+
def remove_weight_norm(self) -> None:
|
| 225 |
+
if self.gin_channels != 0:
|
| 226 |
+
torch.nn.utils.remove_weight_norm(self.cond_layer)
|
| 227 |
+
for l in self.in_layers:
|
| 228 |
+
torch.nn.utils.remove_weight_norm(l)
|
| 229 |
+
for l in self.res_skip_layers:
|
| 230 |
+
torch.nn.utils.remove_weight_norm(l)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class ResBlock1(torch.nn.Module):
|
| 234 |
+
def __init__(
|
| 235 |
+
self,
|
| 236 |
+
channels: int,
|
| 237 |
+
kernel_size: int = 3,
|
| 238 |
+
dilation: tuple[int, int, int] = (1, 3, 5),
|
| 239 |
+
) -> None:
|
| 240 |
+
super(ResBlock1, self).__init__()
|
| 241 |
+
self.convs1 = nn.ModuleList(
|
| 242 |
+
[
|
| 243 |
+
weight_norm(
|
| 244 |
+
Conv1d(
|
| 245 |
+
channels,
|
| 246 |
+
channels,
|
| 247 |
+
kernel_size,
|
| 248 |
+
1,
|
| 249 |
+
dilation=dilation[0],
|
| 250 |
+
padding=commons.get_padding(kernel_size, dilation[0]),
|
| 251 |
+
)
|
| 252 |
+
),
|
| 253 |
+
weight_norm(
|
| 254 |
+
Conv1d(
|
| 255 |
+
channels,
|
| 256 |
+
channels,
|
| 257 |
+
kernel_size,
|
| 258 |
+
1,
|
| 259 |
+
dilation=dilation[1],
|
| 260 |
+
padding=commons.get_padding(kernel_size, dilation[1]),
|
| 261 |
+
)
|
| 262 |
+
),
|
| 263 |
+
weight_norm(
|
| 264 |
+
Conv1d(
|
| 265 |
+
channels,
|
| 266 |
+
channels,
|
| 267 |
+
kernel_size,
|
| 268 |
+
1,
|
| 269 |
+
dilation=dilation[2],
|
| 270 |
+
padding=commons.get_padding(kernel_size, dilation[2]),
|
| 271 |
+
)
|
| 272 |
+
),
|
| 273 |
+
]
|
| 274 |
+
)
|
| 275 |
+
self.convs1.apply(commons.init_weights)
|
| 276 |
+
|
| 277 |
+
self.convs2 = nn.ModuleList(
|
| 278 |
+
[
|
| 279 |
+
weight_norm(
|
| 280 |
+
Conv1d(
|
| 281 |
+
channels,
|
| 282 |
+
channels,
|
| 283 |
+
kernel_size,
|
| 284 |
+
1,
|
| 285 |
+
dilation=1,
|
| 286 |
+
padding=commons.get_padding(kernel_size, 1),
|
| 287 |
+
)
|
| 288 |
+
),
|
| 289 |
+
weight_norm(
|
| 290 |
+
Conv1d(
|
| 291 |
+
channels,
|
| 292 |
+
channels,
|
| 293 |
+
kernel_size,
|
| 294 |
+
1,
|
| 295 |
+
dilation=1,
|
| 296 |
+
padding=commons.get_padding(kernel_size, 1),
|
| 297 |
+
)
|
| 298 |
+
),
|
| 299 |
+
weight_norm(
|
| 300 |
+
Conv1d(
|
| 301 |
+
channels,
|
| 302 |
+
channels,
|
| 303 |
+
kernel_size,
|
| 304 |
+
1,
|
| 305 |
+
dilation=1,
|
| 306 |
+
padding=commons.get_padding(kernel_size, 1),
|
| 307 |
+
)
|
| 308 |
+
),
|
| 309 |
+
]
|
| 310 |
+
)
|
| 311 |
+
self.convs2.apply(commons.init_weights)
|
| 312 |
+
|
| 313 |
+
def forward(
|
| 314 |
+
self, x: torch.Tensor, x_mask: Optional[torch.Tensor] = None
|
| 315 |
+
) -> torch.Tensor:
|
| 316 |
+
for c1, c2 in zip(self.convs1, self.convs2):
|
| 317 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
| 318 |
+
if x_mask is not None:
|
| 319 |
+
xt = xt * x_mask
|
| 320 |
+
xt = c1(xt)
|
| 321 |
+
xt = F.leaky_relu(xt, LRELU_SLOPE)
|
| 322 |
+
if x_mask is not None:
|
| 323 |
+
xt = xt * x_mask
|
| 324 |
+
xt = c2(xt)
|
| 325 |
+
x = xt + x
|
| 326 |
+
if x_mask is not None:
|
| 327 |
+
x = x * x_mask
|
| 328 |
+
return x
|
| 329 |
+
|
| 330 |
+
def remove_weight_norm(self) -> None:
|
| 331 |
+
for l in self.convs1:
|
| 332 |
+
remove_weight_norm(l)
|
| 333 |
+
for l in self.convs2:
|
| 334 |
+
remove_weight_norm(l)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class ResBlock2(torch.nn.Module):
|
| 338 |
+
def __init__(
|
| 339 |
+
self, channels: int, kernel_size: int = 3, dilation: tuple[int, int] = (1, 3)
|
| 340 |
+
) -> None:
|
| 341 |
+
super(ResBlock2, self).__init__()
|
| 342 |
+
self.convs = nn.ModuleList(
|
| 343 |
+
[
|
| 344 |
+
weight_norm(
|
| 345 |
+
Conv1d(
|
| 346 |
+
channels,
|
| 347 |
+
channels,
|
| 348 |
+
kernel_size,
|
| 349 |
+
1,
|
| 350 |
+
dilation=dilation[0],
|
| 351 |
+
padding=commons.get_padding(kernel_size, dilation[0]),
|
| 352 |
+
)
|
| 353 |
+
),
|
| 354 |
+
weight_norm(
|
| 355 |
+
Conv1d(
|
| 356 |
+
channels,
|
| 357 |
+
channels,
|
| 358 |
+
kernel_size,
|
| 359 |
+
1,
|
| 360 |
+
dilation=dilation[1],
|
| 361 |
+
padding=commons.get_padding(kernel_size, dilation[1]),
|
| 362 |
+
)
|
| 363 |
+
),
|
| 364 |
+
]
|
| 365 |
+
)
|
| 366 |
+
self.convs.apply(commons.init_weights)
|
| 367 |
+
|
| 368 |
+
def forward(
|
| 369 |
+
self, x: torch.Tensor, x_mask: Optional[torch.Tensor] = None
|
| 370 |
+
) -> torch.Tensor:
|
| 371 |
+
for c in self.convs:
|
| 372 |
+
xt = F.leaky_relu(x, LRELU_SLOPE)
|
| 373 |
+
if x_mask is not None:
|
| 374 |
+
xt = xt * x_mask
|
| 375 |
+
xt = c(xt)
|
| 376 |
+
x = xt + x
|
| 377 |
+
if x_mask is not None:
|
| 378 |
+
x = x * x_mask
|
| 379 |
+
return x
|
| 380 |
+
|
| 381 |
+
def remove_weight_norm(self) -> None:
|
| 382 |
+
for l in self.convs:
|
| 383 |
+
remove_weight_norm(l)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class Log(nn.Module):
|
| 387 |
+
def forward(
|
| 388 |
+
self,
|
| 389 |
+
x: torch.Tensor,
|
| 390 |
+
x_mask: torch.Tensor,
|
| 391 |
+
reverse: bool = False,
|
| 392 |
+
**kwargs: Any,
|
| 393 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
|
| 394 |
+
if not reverse:
|
| 395 |
+
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
|
| 396 |
+
logdet = torch.sum(-y, [1, 2])
|
| 397 |
+
return y, logdet
|
| 398 |
+
else:
|
| 399 |
+
x = torch.exp(x) * x_mask
|
| 400 |
+
return x
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class Flip(nn.Module):
|
| 404 |
+
def forward(
|
| 405 |
+
self,
|
| 406 |
+
x: torch.Tensor,
|
| 407 |
+
*args: Any,
|
| 408 |
+
reverse: bool = False,
|
| 409 |
+
**kwargs: Any,
|
| 410 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
|
| 411 |
+
x = torch.flip(x, [1])
|
| 412 |
+
if not reverse:
|
| 413 |
+
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
|
| 414 |
+
return x, logdet
|
| 415 |
+
else:
|
| 416 |
+
return x
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class ElementwiseAffine(nn.Module):
|
| 420 |
+
def __init__(self, channels: int) -> None:
|
| 421 |
+
super().__init__()
|
| 422 |
+
self.channels = channels
|
| 423 |
+
self.m = nn.Parameter(torch.zeros(channels, 1))
|
| 424 |
+
self.logs = nn.Parameter(torch.zeros(channels, 1))
|
| 425 |
+
|
| 426 |
+
def forward(
|
| 427 |
+
self,
|
| 428 |
+
x: torch.Tensor,
|
| 429 |
+
x_mask: torch.Tensor,
|
| 430 |
+
reverse: bool = False,
|
| 431 |
+
**kwargs: Any,
|
| 432 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
|
| 433 |
+
if not reverse:
|
| 434 |
+
y = self.m + torch.exp(self.logs) * x
|
| 435 |
+
y = y * x_mask
|
| 436 |
+
logdet = torch.sum(self.logs * x_mask, [1, 2])
|
| 437 |
+
return y, logdet
|
| 438 |
+
else:
|
| 439 |
+
x = (x - self.m) * torch.exp(-self.logs) * x_mask
|
| 440 |
+
return x
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
class ResidualCouplingLayer(nn.Module):
|
| 444 |
+
def __init__(
|
| 445 |
+
self,
|
| 446 |
+
channels: int,
|
| 447 |
+
hidden_channels: int,
|
| 448 |
+
kernel_size: int,
|
| 449 |
+
dilation_rate: int,
|
| 450 |
+
n_layers: int,
|
| 451 |
+
p_dropout: float = 0,
|
| 452 |
+
gin_channels: int = 0,
|
| 453 |
+
mean_only: bool = False,
|
| 454 |
+
) -> None:
|
| 455 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
| 456 |
+
super().__init__()
|
| 457 |
+
self.channels = channels
|
| 458 |
+
self.hidden_channels = hidden_channels
|
| 459 |
+
self.kernel_size = kernel_size
|
| 460 |
+
self.dilation_rate = dilation_rate
|
| 461 |
+
self.n_layers = n_layers
|
| 462 |
+
self.half_channels = channels // 2
|
| 463 |
+
self.mean_only = mean_only
|
| 464 |
+
|
| 465 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
| 466 |
+
self.enc = WN(
|
| 467 |
+
hidden_channels,
|
| 468 |
+
kernel_size,
|
| 469 |
+
dilation_rate,
|
| 470 |
+
n_layers,
|
| 471 |
+
p_dropout=p_dropout,
|
| 472 |
+
gin_channels=gin_channels,
|
| 473 |
+
)
|
| 474 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
| 475 |
+
self.post.weight.data.zero_()
|
| 476 |
+
assert self.post.bias is not None
|
| 477 |
+
self.post.bias.data.zero_()
|
| 478 |
+
|
| 479 |
+
def forward(
|
| 480 |
+
self,
|
| 481 |
+
x: torch.Tensor,
|
| 482 |
+
x_mask: torch.Tensor,
|
| 483 |
+
g: Optional[torch.Tensor] = None,
|
| 484 |
+
reverse: bool = False,
|
| 485 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
|
| 486 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
| 487 |
+
h = self.pre(x0) * x_mask
|
| 488 |
+
h = self.enc(h, x_mask, g=g)
|
| 489 |
+
stats = self.post(h) * x_mask
|
| 490 |
+
if not self.mean_only:
|
| 491 |
+
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
|
| 492 |
+
else:
|
| 493 |
+
m = stats
|
| 494 |
+
logs = torch.zeros_like(m)
|
| 495 |
+
|
| 496 |
+
if not reverse:
|
| 497 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
| 498 |
+
x = torch.cat([x0, x1], 1)
|
| 499 |
+
logdet = torch.sum(logs, [1, 2])
|
| 500 |
+
return x, logdet
|
| 501 |
+
else:
|
| 502 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
| 503 |
+
x = torch.cat([x0, x1], 1)
|
| 504 |
+
return x
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
class ConvFlow(nn.Module):
|
| 508 |
+
def __init__(
|
| 509 |
+
self,
|
| 510 |
+
in_channels: int,
|
| 511 |
+
filter_channels: int,
|
| 512 |
+
kernel_size: int,
|
| 513 |
+
n_layers: int,
|
| 514 |
+
num_bins: int = 10,
|
| 515 |
+
tail_bound: float = 5.0,
|
| 516 |
+
) -> None:
|
| 517 |
+
super().__init__()
|
| 518 |
+
self.in_channels = in_channels
|
| 519 |
+
self.filter_channels = filter_channels
|
| 520 |
+
self.kernel_size = kernel_size
|
| 521 |
+
self.n_layers = n_layers
|
| 522 |
+
self.num_bins = num_bins
|
| 523 |
+
self.tail_bound = tail_bound
|
| 524 |
+
self.half_channels = in_channels // 2
|
| 525 |
+
|
| 526 |
+
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
|
| 527 |
+
self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
|
| 528 |
+
self.proj = nn.Conv1d(
|
| 529 |
+
filter_channels, self.half_channels * (num_bins * 3 - 1), 1
|
| 530 |
+
)
|
| 531 |
+
self.proj.weight.data.zero_()
|
| 532 |
+
assert self.proj.bias is not None
|
| 533 |
+
self.proj.bias.data.zero_()
|
| 534 |
+
|
| 535 |
+
def forward(
|
| 536 |
+
self,
|
| 537 |
+
x: torch.Tensor,
|
| 538 |
+
x_mask: torch.Tensor,
|
| 539 |
+
g: Optional[torch.Tensor] = None,
|
| 540 |
+
reverse: bool = False,
|
| 541 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
|
| 542 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
| 543 |
+
h = self.pre(x0)
|
| 544 |
+
h = self.convs(h, x_mask, g=g)
|
| 545 |
+
h = self.proj(h) * x_mask
|
| 546 |
+
|
| 547 |
+
b, c, t = x0.shape
|
| 548 |
+
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
|
| 549 |
+
|
| 550 |
+
unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
|
| 551 |
+
unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
|
| 552 |
+
self.filter_channels
|
| 553 |
+
)
|
| 554 |
+
unnormalized_derivatives = h[..., 2 * self.num_bins :]
|
| 555 |
+
|
| 556 |
+
x1, logabsdet = piecewise_rational_quadratic_transform(
|
| 557 |
+
x1,
|
| 558 |
+
unnormalized_widths,
|
| 559 |
+
unnormalized_heights,
|
| 560 |
+
unnormalized_derivatives,
|
| 561 |
+
inverse=reverse,
|
| 562 |
+
tails="linear",
|
| 563 |
+
tail_bound=self.tail_bound,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
x = torch.cat([x0, x1], 1) * x_mask
|
| 567 |
+
logdet = torch.sum(logabsdet * x_mask, [1, 2])
|
| 568 |
+
if not reverse:
|
| 569 |
+
return x, logdet
|
| 570 |
+
else:
|
| 571 |
+
return x
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
class TransformerCouplingLayer(nn.Module):
|
| 575 |
+
def __init__(
|
| 576 |
+
self,
|
| 577 |
+
channels: int,
|
| 578 |
+
hidden_channels: int,
|
| 579 |
+
kernel_size: int,
|
| 580 |
+
n_layers: int,
|
| 581 |
+
n_heads: int,
|
| 582 |
+
p_dropout: float = 0,
|
| 583 |
+
filter_channels: int = 0,
|
| 584 |
+
mean_only: bool = False,
|
| 585 |
+
wn_sharing_parameter: Optional[nn.Module] = None,
|
| 586 |
+
gin_channels: int = 0,
|
| 587 |
+
) -> None:
|
| 588 |
+
assert channels % 2 == 0, "channels should be divisible by 2"
|
| 589 |
+
super().__init__()
|
| 590 |
+
self.channels = channels
|
| 591 |
+
self.hidden_channels = hidden_channels
|
| 592 |
+
self.kernel_size = kernel_size
|
| 593 |
+
self.n_layers = n_layers
|
| 594 |
+
self.half_channels = channels // 2
|
| 595 |
+
self.mean_only = mean_only
|
| 596 |
+
|
| 597 |
+
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
| 598 |
+
self.enc = (
|
| 599 |
+
Encoder(
|
| 600 |
+
hidden_channels,
|
| 601 |
+
filter_channels,
|
| 602 |
+
n_heads,
|
| 603 |
+
n_layers,
|
| 604 |
+
kernel_size,
|
| 605 |
+
p_dropout,
|
| 606 |
+
isflow=True,
|
| 607 |
+
gin_channels=gin_channels,
|
| 608 |
+
)
|
| 609 |
+
if wn_sharing_parameter is None
|
| 610 |
+
else wn_sharing_parameter
|
| 611 |
+
)
|
| 612 |
+
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
| 613 |
+
self.post.weight.data.zero_()
|
| 614 |
+
assert self.post.bias is not None
|
| 615 |
+
self.post.bias.data.zero_()
|
| 616 |
+
|
| 617 |
+
def forward(
|
| 618 |
+
self,
|
| 619 |
+
x: torch.Tensor,
|
| 620 |
+
x_mask: torch.Tensor,
|
| 621 |
+
g: Optional[torch.Tensor] = None,
|
| 622 |
+
reverse: bool = False,
|
| 623 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
|
| 624 |
+
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
| 625 |
+
h = self.pre(x0) * x_mask
|
| 626 |
+
h = self.enc(h, x_mask, g=g)
|
| 627 |
+
stats = self.post(h) * x_mask
|
| 628 |
+
if not self.mean_only:
|
| 629 |
+
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
|
| 630 |
+
else:
|
| 631 |
+
m = stats
|
| 632 |
+
logs = torch.zeros_like(m)
|
| 633 |
+
|
| 634 |
+
if not reverse:
|
| 635 |
+
x1 = m + x1 * torch.exp(logs) * x_mask
|
| 636 |
+
x = torch.cat([x0, x1], 1)
|
| 637 |
+
logdet = torch.sum(logs, [1, 2])
|
| 638 |
+
return x, logdet
|
| 639 |
+
else:
|
| 640 |
+
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
| 641 |
+
x = torch.cat([x0, x1], 1)
|
| 642 |
+
return x
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/monotonic_alignment.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
以下に記述されている関数のコメントはリファクタリング時に GPT-4 に生成させたもので、
|
| 3 |
+
コードと完全に一致している保証はない。あくまで参考程度とすること。
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numba
|
| 9 |
+
import torch
|
| 10 |
+
from numpy import float32, int32, zeros
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def maximum_path(neg_cent: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
|
| 14 |
+
"""
|
| 15 |
+
与えられた負の中心とマスクを使用して最大パスを計算する
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
neg_cent (torch.Tensor): 負の中心を表すテンソル
|
| 19 |
+
mask (torch.Tensor): マスクを表すテンソル
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
Tensor: 計算された最大パスを表すテンソル
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
device = neg_cent.device
|
| 26 |
+
dtype = neg_cent.dtype
|
| 27 |
+
neg_cent = neg_cent.data.cpu().numpy().astype(float32)
|
| 28 |
+
path = zeros(neg_cent.shape, dtype=int32)
|
| 29 |
+
|
| 30 |
+
t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(int32)
|
| 31 |
+
t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(int32)
|
| 32 |
+
__maximum_path_jit(path, neg_cent, t_t_max, t_s_max)
|
| 33 |
+
|
| 34 |
+
return torch.from_numpy(path).to(device=device, dtype=dtype)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@numba.jit(
|
| 38 |
+
numba.void(
|
| 39 |
+
numba.int32[:, :, ::1],
|
| 40 |
+
numba.float32[:, :, ::1],
|
| 41 |
+
numba.int32[::1],
|
| 42 |
+
numba.int32[::1],
|
| 43 |
+
),
|
| 44 |
+
nopython=True,
|
| 45 |
+
nogil=True,
|
| 46 |
+
) # type: ignore
|
| 47 |
+
def __maximum_path_jit(paths: Any, values: Any, t_ys: Any, t_xs: Any) -> None:
|
| 48 |
+
"""
|
| 49 |
+
与えられたパス、値、およびターゲットの y と x 座標を使用して JIT で最大パスを計算する
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
paths: 計算されたパスを格納するための整数型の 3 次元配列
|
| 53 |
+
values: 値を格納するための浮動小数点型の 3 次元配列
|
| 54 |
+
t_ys: ターゲットの y 座標を格納するための整数型の 1 次元配列
|
| 55 |
+
t_xs: ターゲットの x 座標を格納するための整数型の 1 次元配列
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
b = paths.shape[0]
|
| 59 |
+
max_neg_val = -1e9
|
| 60 |
+
for i in range(int(b)):
|
| 61 |
+
path = paths[i]
|
| 62 |
+
value = values[i]
|
| 63 |
+
t_y = t_ys[i]
|
| 64 |
+
t_x = t_xs[i]
|
| 65 |
+
|
| 66 |
+
v_prev = v_cur = 0.0
|
| 67 |
+
index = t_x - 1
|
| 68 |
+
|
| 69 |
+
for y in range(t_y):
|
| 70 |
+
for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
|
| 71 |
+
if x == y:
|
| 72 |
+
v_cur = max_neg_val
|
| 73 |
+
else:
|
| 74 |
+
v_cur = value[y - 1, x]
|
| 75 |
+
if x == 0:
|
| 76 |
+
if y == 0:
|
| 77 |
+
v_prev = 0.0
|
| 78 |
+
else:
|
| 79 |
+
v_prev = max_neg_val
|
| 80 |
+
else:
|
| 81 |
+
v_prev = value[y - 1, x - 1]
|
| 82 |
+
value[y, x] += max(v_prev, v_cur)
|
| 83 |
+
|
| 84 |
+
for y in range(t_y - 1, -1, -1):
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
DEFAULT_MIN_BIN_WIDTH = 1e-3
|
| 9 |
+
DEFAULT_MIN_BIN_HEIGHT = 1e-3
|
| 10 |
+
DEFAULT_MIN_DERIVATIVE = 1e-3
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def piecewise_rational_quadratic_transform(
|
| 14 |
+
inputs: torch.Tensor,
|
| 15 |
+
unnormalized_widths: torch.Tensor,
|
| 16 |
+
unnormalized_heights: torch.Tensor,
|
| 17 |
+
unnormalized_derivatives: torch.Tensor,
|
| 18 |
+
inverse: bool = False,
|
| 19 |
+
tails: Optional[str] = None,
|
| 20 |
+
tail_bound: float = 1.0,
|
| 21 |
+
min_bin_width: float = DEFAULT_MIN_BIN_WIDTH,
|
| 22 |
+
min_bin_height: float = DEFAULT_MIN_BIN_HEIGHT,
|
| 23 |
+
min_derivative: float = DEFAULT_MIN_DERIVATIVE,
|
| 24 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 25 |
+
|
| 26 |
+
if tails is None:
|
| 27 |
+
spline_fn = rational_quadratic_spline
|
| 28 |
+
spline_kwargs = {}
|
| 29 |
+
else:
|
| 30 |
+
spline_fn = unconstrained_rational_quadratic_spline
|
| 31 |
+
spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
|
| 32 |
+
|
| 33 |
+
outputs, logabsdet = spline_fn(
|
| 34 |
+
inputs=inputs,
|
| 35 |
+
unnormalized_widths=unnormalized_widths,
|
| 36 |
+
unnormalized_heights=unnormalized_heights,
|
| 37 |
+
unnormalized_derivatives=unnormalized_derivatives,
|
| 38 |
+
inverse=inverse,
|
| 39 |
+
min_bin_width=min_bin_width,
|
| 40 |
+
min_bin_height=min_bin_height,
|
| 41 |
+
min_derivative=min_derivative,
|
| 42 |
+
**spline_kwargs, # type: ignore
|
| 43 |
+
)
|
| 44 |
+
return outputs, logabsdet
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def searchsorted(
|
| 48 |
+
bin_locations: torch.Tensor, inputs: torch.Tensor, eps: float = 1e-6
|
| 49 |
+
) -> torch.Tensor:
|
| 50 |
+
bin_locations[..., -1] += eps
|
| 51 |
+
return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def unconstrained_rational_quadratic_spline(
|
| 55 |
+
inputs: torch.Tensor,
|
| 56 |
+
unnormalized_widths: torch.Tensor,
|
| 57 |
+
unnormalized_heights: torch.Tensor,
|
| 58 |
+
unnormalized_derivatives: torch.Tensor,
|
| 59 |
+
inverse: bool = False,
|
| 60 |
+
tails: str = "linear",
|
| 61 |
+
tail_bound: float = 1.0,
|
| 62 |
+
min_bin_width: float = DEFAULT_MIN_BIN_WIDTH,
|
| 63 |
+
min_bin_height: float = DEFAULT_MIN_BIN_HEIGHT,
|
| 64 |
+
min_derivative: float = DEFAULT_MIN_DERIVATIVE,
|
| 65 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 66 |
+
|
| 67 |
+
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
|
| 68 |
+
outside_interval_mask = ~inside_interval_mask
|
| 69 |
+
|
| 70 |
+
outputs = torch.zeros_like(inputs)
|
| 71 |
+
logabsdet = torch.zeros_like(inputs)
|
| 72 |
+
|
| 73 |
+
if tails == "linear":
|
| 74 |
+
unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
|
| 75 |
+
constant = np.log(np.exp(1 - min_derivative) - 1)
|
| 76 |
+
unnormalized_derivatives[..., 0] = constant
|
| 77 |
+
unnormalized_derivatives[..., -1] = constant
|
| 78 |
+
|
| 79 |
+
outputs[outside_interval_mask] = inputs[outside_interval_mask]
|
| 80 |
+
logabsdet[outside_interval_mask] = 0
|
| 81 |
+
else:
|
| 82 |
+
raise RuntimeError(f"{tails} tails are not implemented.")
|
| 83 |
+
|
| 84 |
+
(
|
| 85 |
+
outputs[inside_interval_mask],
|
| 86 |
+
logabsdet[inside_interval_mask],
|
| 87 |
+
) = rational_quadratic_spline(
|
| 88 |
+
inputs=inputs[inside_interval_mask],
|
| 89 |
+
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
|
| 90 |
+
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
|
| 91 |
+
unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
|
| 92 |
+
inverse=inverse,
|
| 93 |
+
left=-tail_bound,
|
| 94 |
+
right=tail_bound,
|
| 95 |
+
bottom=-tail_bound,
|
| 96 |
+
top=tail_bound,
|
| 97 |
+
min_bin_width=min_bin_width,
|
| 98 |
+
min_bin_height=min_bin_height,
|
| 99 |
+
min_derivative=min_derivative,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
return outputs, logabsdet
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def rational_quadratic_spline(
|
| 106 |
+
inputs: torch.Tensor,
|
| 107 |
+
unnormalized_widths: torch.Tensor,
|
| 108 |
+
unnormalized_heights: torch.Tensor,
|
| 109 |
+
unnormalized_derivatives: torch.Tensor,
|
| 110 |
+
inverse: bool = False,
|
| 111 |
+
left: float = 0.0,
|
| 112 |
+
right: float = 1.0,
|
| 113 |
+
bottom: float = 0.0,
|
| 114 |
+
top: float = 1.0,
|
| 115 |
+
min_bin_width: float = DEFAULT_MIN_BIN_WIDTH,
|
| 116 |
+
min_bin_height: float = DEFAULT_MIN_BIN_HEIGHT,
|
| 117 |
+
min_derivative: float = DEFAULT_MIN_DERIVATIVE,
|
| 118 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 119 |
+
|
| 120 |
+
if torch.min(inputs) < left or torch.max(inputs) > right:
|
| 121 |
+
raise ValueError("Input to a transform is not within its domain")
|
| 122 |
+
|
| 123 |
+
num_bins = unnormalized_widths.shape[-1]
|
| 124 |
+
|
| 125 |
+
if min_bin_width * num_bins > 1.0:
|
| 126 |
+
raise ValueError("Minimal bin width too large for the number of bins")
|
| 127 |
+
if min_bin_height * num_bins > 1.0:
|
| 128 |
+
raise ValueError("Minimal bin height too large for the number of bins")
|
| 129 |
+
|
| 130 |
+
widths = F.softmax(unnormalized_widths, dim=-1)
|
| 131 |
+
widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
|
| 132 |
+
cumwidths = torch.cumsum(widths, dim=-1)
|
| 133 |
+
cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
|
| 134 |
+
cumwidths = (right - left) * cumwidths + left
|
| 135 |
+
cumwidths[..., 0] = left
|
| 136 |
+
cumwidths[..., -1] = right
|
| 137 |
+
widths = cumwidths[..., 1:] - cumwidths[..., :-1]
|
| 138 |
+
|
| 139 |
+
derivatives = min_derivative + F.softplus(unnormalized_derivatives)
|
| 140 |
+
|
| 141 |
+
heights = F.softmax(unnormalized_heights, dim=-1)
|
| 142 |
+
heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
|
| 143 |
+
cumheights = torch.cumsum(heights, dim=-1)
|
| 144 |
+
cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
|
| 145 |
+
cumheights = (top - bottom) * cumheights + bottom
|
| 146 |
+
cumheights[..., 0] = bottom
|
| 147 |
+
cumheights[..., -1] = top
|
| 148 |
+
heights = cumheights[..., 1:] - cumheights[..., :-1]
|
| 149 |
+
|
| 150 |
+
if inverse:
|
| 151 |
+
bin_idx = searchsorted(cumheights, inputs)[..., None]
|
| 152 |
+
else:
|
| 153 |
+
bin_idx = searchsorted(cumwidths, inputs)[..., None]
|
| 154 |
+
|
| 155 |
+
input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
|
| 156 |
+
input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
|
| 157 |
+
|
| 158 |
+
input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
|
| 159 |
+
delta = heights / widths
|
| 160 |
+
input_delta = delta.gather(-1, bin_idx)[..., 0]
|
| 161 |
+
|
| 162 |
+
input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
|
| 163 |
+
input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
|
| 164 |
+
|
| 165 |
+
input_heights = heights.gather(-1, bin_idx)[..., 0]
|
| 166 |
+
|
| 167 |
+
if inverse:
|
| 168 |
+
a = (inputs - input_cumheights) * (
|
| 169 |
+
input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
| 170 |
+
) + input_heights * (input_delta - input_derivatives)
|
| 171 |
+
b = input_heights * input_derivatives - (inputs - input_cumheights) * (
|
| 172 |
+
input_derivatives + input_derivatives_plus_one - 2 * input_delta
|
| 173 |
+
)
|
| 174 |
+
c = -input_delta * (inputs - input_cumheights)
|
| 175 |
+
|
| 176 |
+
discriminant = b.pow(2) - 4 * a * c
|
| 177 |
+
assert (discriminant >= 0).all()
|
| 178 |
+
|
| 179 |
+
root = (2 * c) / (-b - torch.sqrt(discriminant))
|
| 180 |
+
outputs = root * input_bin_widths + input_cumwidths
|
| 181 |
+
|
| 182 |
+
theta_one_minus_theta = root * (1 - root)
|
| 183 |
+
denominator = input_delta + (
|
| 184 |
+
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
| 185 |
+
* theta_one_minus_theta
|
| 186 |
+
)
|
| 187 |
+
derivative_numerator = input_delta.pow(2) * (
|
| 188 |
+
input_derivatives_plus_one * root.pow(2)
|
| 189 |
+
+ 2 * input_delta * theta_one_minus_theta
|
| 190 |
+
+ input_derivatives * (1 - root).pow(2)
|
| 191 |
+
)
|
| 192 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
| 193 |
+
|
| 194 |
+
return outputs, -logabsdet
|
| 195 |
+
else:
|
| 196 |
+
theta = (inputs - input_cumwidths) / input_bin_widths
|
| 197 |
+
theta_one_minus_theta = theta * (1 - theta)
|
| 198 |
+
|
| 199 |
+
numerator = input_heights * (
|
| 200 |
+
input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
|
| 201 |
+
)
|
| 202 |
+
denominator = input_delta + (
|
| 203 |
+
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
|
| 204 |
+
* theta_one_minus_theta
|
| 205 |
+
)
|
| 206 |
+
outputs = input_cumheights + numerator / denominator
|
| 207 |
+
|
| 208 |
+
derivative_numerator = input_delta.pow(2) * (
|
| 209 |
+
input_derivatives_plus_one * theta.pow(2)
|
| 210 |
+
+ 2 * input_delta * theta_one_minus_theta
|
| 211 |
+
+ input_derivatives * (1 - theta).pow(2)
|
| 212 |
+
)
|
| 213 |
+
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
|
| 214 |
+
|
| 215 |
+
return outputs, logabsdet
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/utils/__init__.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import subprocess
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Optional, Union
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from numpy.typing import NDArray
|
| 12 |
+
|
| 13 |
+
from style_bert_vits2.logging import logger
|
| 14 |
+
from style_bert_vits2.models.utils import checkpoints # type: ignore
|
| 15 |
+
from style_bert_vits2.models.utils import safetensors # type: ignore
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
# tensorboard はライブラリとしてインストールされている場合は依存関係に含まれないため、型チェック時のみインポートする
|
| 20 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__is_matplotlib_imported = False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def summarize(
|
| 27 |
+
writer: "SummaryWriter",
|
| 28 |
+
global_step: int,
|
| 29 |
+
scalars: dict[str, float] = {},
|
| 30 |
+
histograms: dict[str, Any] = {},
|
| 31 |
+
images: dict[str, Any] = {},
|
| 32 |
+
audios: dict[str, Any] = {},
|
| 33 |
+
audio_sampling_rate: int = 22050,
|
| 34 |
+
) -> None:
|
| 35 |
+
"""
|
| 36 |
+
指定されたデータを TensorBoard にまとめて追加する
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
writer (SummaryWriter): TensorBoard への書き込みを行うオブジェクト
|
| 40 |
+
global_step (int): グローバルステップ数
|
| 41 |
+
scalars (dict[str, float]): スカラー値の辞書
|
| 42 |
+
histograms (dict[str, Any]): ヒストグラムの辞書
|
| 43 |
+
images (dict[str, Any]): 画像データの辞書
|
| 44 |
+
audios (dict[str, Any]): 音声データの辞書
|
| 45 |
+
audio_sampling_rate (int): 音声データのサンプリングレート
|
| 46 |
+
"""
|
| 47 |
+
for k, v in scalars.items():
|
| 48 |
+
writer.add_scalar(k, v, global_step)
|
| 49 |
+
for k, v in histograms.items():
|
| 50 |
+
writer.add_histogram(k, v, global_step)
|
| 51 |
+
for k, v in images.items():
|
| 52 |
+
writer.add_image(k, v, global_step, dataformats="HWC")
|
| 53 |
+
for k, v in audios.items():
|
| 54 |
+
writer.add_audio(k, v, global_step, audio_sampling_rate)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def is_resuming(dir_path: Union[str, Path]) -> bool:
|
| 58 |
+
"""
|
| 59 |
+
指定されたディレクトリパスに再開可能なモデルが存在するかどうかを返す
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
dir_path: チェックするディレクトリのパス
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
bool: 再開可能なモデルが存在するかどうか
|
| 66 |
+
"""
|
| 67 |
+
# JP-ExtraバージョンではDURがなくWDがあったり変わるため、Gのみで判断する
|
| 68 |
+
g_list = glob.glob(os.path.join(dir_path, "G_*.pth"))
|
| 69 |
+
# d_list = glob.glob(os.path.join(dir_path, "D_*.pth"))
|
| 70 |
+
# dur_list = glob.glob(os.path.join(dir_path, "DUR_*.pth"))
|
| 71 |
+
return len(g_list) > 0
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def plot_spectrogram_to_numpy(spectrogram: NDArray[Any]) -> NDArray[Any]:
|
| 75 |
+
"""
|
| 76 |
+
指定されたスペクトログラムを画像データに変換する
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
spectrogram (NDArray[Any]): スペクトログラム
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
NDArray[Any]: 画像データ
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
global __is_matplotlib_imported
|
| 86 |
+
if not __is_matplotlib_imported:
|
| 87 |
+
import matplotlib
|
| 88 |
+
|
| 89 |
+
matplotlib.use("Agg")
|
| 90 |
+
__is_matplotlib_imported = True
|
| 91 |
+
mpl_logger = logging.getLogger("matplotlib")
|
| 92 |
+
mpl_logger.setLevel(logging.WARNING)
|
| 93 |
+
import matplotlib.pylab as plt
|
| 94 |
+
import numpy as np
|
| 95 |
+
|
| 96 |
+
fig, ax = plt.subplots(figsize=(10, 2))
|
| 97 |
+
im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
|
| 98 |
+
plt.colorbar(im, ax=ax)
|
| 99 |
+
plt.xlabel("Frames")
|
| 100 |
+
plt.ylabel("Channels")
|
| 101 |
+
plt.tight_layout()
|
| 102 |
+
|
| 103 |
+
fig.canvas.draw()
|
| 104 |
+
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="") # type: ignore
|
| 105 |
+
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
| 106 |
+
plt.close()
|
| 107 |
+
return data
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def plot_alignment_to_numpy(
|
| 111 |
+
alignment: NDArray[Any], info: Optional[str] = None
|
| 112 |
+
) -> NDArray[Any]:
|
| 113 |
+
"""
|
| 114 |
+
指定されたアライメントを画像データに変換する
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
alignment (NDArray[Any]): アライメント
|
| 118 |
+
info (Optional[str]): 画像に追加する情報
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
NDArray[Any]: 画像データ
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
global __is_matplotlib_imported
|
| 125 |
+
if not __is_matplotlib_imported:
|
| 126 |
+
import matplotlib
|
| 127 |
+
|
| 128 |
+
matplotlib.use("Agg")
|
| 129 |
+
__is_matplotlib_imported = True
|
| 130 |
+
mpl_logger = logging.getLogger("matplotlib")
|
| 131 |
+
mpl_logger.setLevel(logging.WARNING)
|
| 132 |
+
import matplotlib.pylab as plt
|
| 133 |
+
|
| 134 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
| 135 |
+
im = ax.imshow(
|
| 136 |
+
alignment.transpose(), aspect="auto", origin="lower", interpolation="none"
|
| 137 |
+
)
|
| 138 |
+
fig.colorbar(im, ax=ax)
|
| 139 |
+
xlabel = "Decoder timestep"
|
| 140 |
+
if info is not None:
|
| 141 |
+
xlabel += "\n\n" + info
|
| 142 |
+
plt.xlabel(xlabel)
|
| 143 |
+
plt.ylabel("Encoder timestep")
|
| 144 |
+
plt.tight_layout()
|
| 145 |
+
|
| 146 |
+
fig.canvas.draw()
|
| 147 |
+
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="") # type: ignore
|
| 148 |
+
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
| 149 |
+
plt.close()
|
| 150 |
+
return data
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def load_wav_to_torch(full_path: Union[str, Path]) -> tuple[torch.FloatTensor, int]:
|
| 154 |
+
"""
|
| 155 |
+
指定された音声ファイルを読み込み、PyTorch のテンソルに変換して返す
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
full_path (Union[str, Path]): 音声ファイルのパス
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
tuple[torch.FloatTensor, int]: 音声データのテンソルとサンプリングレート
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
# この関数は学習時以外使われないため、ライブラリとしての style_bert_vits2 が
|
| 165 |
+
# 重たい scipy に依存しないように遅延 import する
|
| 166 |
+
try:
|
| 167 |
+
from scipy.io.wavfile import read
|
| 168 |
+
except ImportError:
|
| 169 |
+
raise ImportError("scipy is required to load wav file")
|
| 170 |
+
|
| 171 |
+
sampling_rate, data = read(full_path)
|
| 172 |
+
return torch.FloatTensor(data.astype(np.float32)), sampling_rate
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def load_filepaths_and_text(
|
| 176 |
+
filename: Union[str, Path], split: str = "|"
|
| 177 |
+
) -> list[list[str]]:
|
| 178 |
+
"""
|
| 179 |
+
指定されたファイルからファイルパスとテキストを読み込む
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
filename (Union[str, Path]): ファイルのパス
|
| 183 |
+
split (str): ファイルの区切り文字 (デフォルト: "|")
|
| 184 |
+
|
| 185 |
+
Returns:
|
| 186 |
+
list[list[str]]: ファイルパスとテキストのリスト
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
with open(filename, encoding="utf-8") as f:
|
| 190 |
+
filepaths_and_text = [line.strip().split(split) for line in f]
|
| 191 |
+
return filepaths_and_text
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def get_logger(
|
| 195 |
+
model_dir_path: Union[str, Path], filename: str = "train.log"
|
| 196 |
+
) -> logging.Logger:
|
| 197 |
+
"""
|
| 198 |
+
ロガーを取得する
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
model_dir_path (Union[str, Path]): ログを保存するディレクトリのパス
|
| 202 |
+
filename (str): ログファイルの名前 (デフォルト: "train.log")
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
logging.Logger: ロガー
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
global logger
|
| 209 |
+
logger = logging.getLogger(os.path.basename(model_dir_path))
|
| 210 |
+
logger.setLevel(logging.DEBUG)
|
| 211 |
+
|
| 212 |
+
formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
|
| 213 |
+
if not os.path.exists(model_dir_path):
|
| 214 |
+
os.makedirs(model_dir_path)
|
| 215 |
+
h = logging.FileHandler(os.path.join(model_dir_path, filename))
|
| 216 |
+
h.setLevel(logging.DEBUG)
|
| 217 |
+
h.setFormatter(formatter)
|
| 218 |
+
logger.addHandler(h)
|
| 219 |
+
return logger
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def get_steps(model_path: Union[str, Path]) -> Optional[int]:
|
| 223 |
+
"""
|
| 224 |
+
モデルのパスからイテレーション回数を取得する
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
model_path (Union[str, Path]): モデルのパス
|
| 228 |
+
|
| 229 |
+
Returns:
|
| 230 |
+
Optional[int]: イテレーション回数
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
matches = re.findall(r"\d+", model_path) # type: ignore
|
| 234 |
+
return matches[-1] if matches else None
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def check_git_hash(model_dir_path: Union[str, Path]) -> None:
|
| 238 |
+
"""
|
| 239 |
+
モデルのディレクトリに .git ディレクトリが存在する場合、ハッシュ値を比較する
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
model_dir_path (Union[str, Path]): モデルのディレクトリのパス
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
source_dir = os.path.dirname(os.path.realpath(__file__))
|
| 246 |
+
if not os.path.exists(os.path.join(source_dir, ".git")):
|
| 247 |
+
logger.warning(
|
| 248 |
+
f"{source_dir} is not a git repository, therefore hash value comparison will be ignored."
|
| 249 |
+
)
|
| 250 |
+
return
|
| 251 |
+
|
| 252 |
+
cur_hash = subprocess.getoutput("git rev-parse HEAD")
|
| 253 |
+
|
| 254 |
+
path = os.path.join(model_dir_path, "githash")
|
| 255 |
+
if os.path.exists(path):
|
| 256 |
+
with open(path, encoding="utf-8") as f:
|
| 257 |
+
saved_hash = f.read()
|
| 258 |
+
if saved_hash != cur_hash:
|
| 259 |
+
logger.warning(
|
| 260 |
+
f"git hash values are different. {saved_hash[:8]}(saved) != {cur_hash[:8]}(current)"
|
| 261 |
+
)
|
| 262 |
+
else:
|
| 263 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 264 |
+
f.write(cur_hash)
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/utils/checkpoints.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any, Optional, Union
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from style_bert_vits2.logging import logger
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load_checkpoint(
|
| 13 |
+
checkpoint_path: Union[str, Path],
|
| 14 |
+
model: torch.nn.Module,
|
| 15 |
+
optimizer: Optional[torch.optim.Optimizer] = None,
|
| 16 |
+
skip_optimizer: bool = False,
|
| 17 |
+
for_infer: bool = False,
|
| 18 |
+
) -> tuple[torch.nn.Module, Optional[torch.optim.Optimizer], float, int]:
|
| 19 |
+
"""
|
| 20 |
+
指定されたパスからチェックポイントを読み込み、モデルとオプティマイザーを更新する。
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
checkpoint_path (Union[str, Path]): チェックポイントファイルのパス
|
| 24 |
+
model (torch.nn.Module): 更新するモデル
|
| 25 |
+
optimizer (Optional[torch.optim.Optimizer]): 更新するオプティマイザー。None の場合は更新しない
|
| 26 |
+
skip_optimizer (bool): オプティマイザーの更新をスキップするかどうかのフラグ
|
| 27 |
+
for_infer (bool): 推論用に読み込むかどうかのフラグ
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
tuple[torch.nn.Module, Optional[torch.optim.Optimizer], float, int]: 更新されたモデルとオプティマイザー、学習率、イテレーション回数
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
assert os.path.isfile(checkpoint_path)
|
| 34 |
+
checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
|
| 35 |
+
iteration = checkpoint_dict["iteration"]
|
| 36 |
+
learning_rate = checkpoint_dict["learning_rate"]
|
| 37 |
+
logger.info(
|
| 38 |
+
f"Loading model and optimizer at iteration {iteration} from {checkpoint_path}"
|
| 39 |
+
)
|
| 40 |
+
if (
|
| 41 |
+
optimizer is not None
|
| 42 |
+
and not skip_optimizer
|
| 43 |
+
and checkpoint_dict["optimizer"] is not None
|
| 44 |
+
):
|
| 45 |
+
optimizer.load_state_dict(checkpoint_dict["optimizer"])
|
| 46 |
+
elif optimizer is None and not skip_optimizer:
|
| 47 |
+
# else: Disable this line if Infer and resume checkpoint,then enable the line upper
|
| 48 |
+
new_opt_dict = optimizer.state_dict() # type: ignore
|
| 49 |
+
new_opt_dict_params = new_opt_dict["param_groups"][0]["params"]
|
| 50 |
+
new_opt_dict["param_groups"] = checkpoint_dict["optimizer"]["param_groups"]
|
| 51 |
+
new_opt_dict["param_groups"][0]["params"] = new_opt_dict_params
|
| 52 |
+
optimizer.load_state_dict(new_opt_dict) # type: ignore
|
| 53 |
+
|
| 54 |
+
saved_state_dict = checkpoint_dict["model"]
|
| 55 |
+
if hasattr(model, "module"):
|
| 56 |
+
state_dict = model.module.state_dict()
|
| 57 |
+
else:
|
| 58 |
+
state_dict = model.state_dict()
|
| 59 |
+
|
| 60 |
+
new_state_dict = {}
|
| 61 |
+
for k, v in state_dict.items():
|
| 62 |
+
try:
|
| 63 |
+
# assert "emb_g" not in k
|
| 64 |
+
new_state_dict[k] = saved_state_dict[k]
|
| 65 |
+
assert saved_state_dict[k].shape == v.shape, (
|
| 66 |
+
saved_state_dict[k].shape,
|
| 67 |
+
v.shape,
|
| 68 |
+
)
|
| 69 |
+
except:
|
| 70 |
+
# For upgrading from the old version
|
| 71 |
+
if "ja_bert_proj" in k:
|
| 72 |
+
v = torch.zeros_like(v)
|
| 73 |
+
logger.warning(
|
| 74 |
+
f"Seems you are using the old version of the model, the {k} is automatically set to zero for backward compatibility"
|
| 75 |
+
)
|
| 76 |
+
elif "enc_q" in k and for_infer:
|
| 77 |
+
continue
|
| 78 |
+
else:
|
| 79 |
+
logger.error(f"{k} is not in the checkpoint {checkpoint_path}")
|
| 80 |
+
|
| 81 |
+
new_state_dict[k] = v
|
| 82 |
+
|
| 83 |
+
if hasattr(model, "module"):
|
| 84 |
+
model.module.load_state_dict(new_state_dict, strict=False)
|
| 85 |
+
else:
|
| 86 |
+
model.load_state_dict(new_state_dict, strict=False)
|
| 87 |
+
|
| 88 |
+
logger.info(f"Loaded '{checkpoint_path}' (iteration {iteration})")
|
| 89 |
+
|
| 90 |
+
return model, optimizer, learning_rate, iteration
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def save_checkpoint(
|
| 94 |
+
model: torch.nn.Module,
|
| 95 |
+
optimizer: Union[torch.optim.Optimizer, torch.optim.AdamW],
|
| 96 |
+
learning_rate: float,
|
| 97 |
+
iteration: int,
|
| 98 |
+
checkpoint_path: Union[str, Path],
|
| 99 |
+
) -> None:
|
| 100 |
+
"""
|
| 101 |
+
モデルとオプティマイザーの状態を指定されたパスに保存する。
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
model (torch.nn.Module): 保存するモデル
|
| 105 |
+
optimizer (Union[torch.optim.Optimizer, torch.optim.AdamW]): 保存するオプティマイザー
|
| 106 |
+
learning_rate (float): 学習率
|
| 107 |
+
iteration (int): イテレーション回数
|
| 108 |
+
checkpoint_path (Union[str, Path]): 保存先のパス
|
| 109 |
+
"""
|
| 110 |
+
logger.info(
|
| 111 |
+
f"Saving model and optimizer state at iteration {iteration} to {checkpoint_path}"
|
| 112 |
+
)
|
| 113 |
+
if hasattr(model, "module"):
|
| 114 |
+
state_dict = model.module.state_dict()
|
| 115 |
+
else:
|
| 116 |
+
state_dict = model.state_dict()
|
| 117 |
+
torch.save(
|
| 118 |
+
{
|
| 119 |
+
"model": state_dict,
|
| 120 |
+
"iteration": iteration,
|
| 121 |
+
"optimizer": optimizer.state_dict(),
|
| 122 |
+
"learning_rate": learning_rate,
|
| 123 |
+
},
|
| 124 |
+
checkpoint_path,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def clean_checkpoints(
|
| 129 |
+
model_dir_path: Union[str, Path] = "logs/44k/",
|
| 130 |
+
n_ckpts_to_keep: int = 2,
|
| 131 |
+
sort_by_time: bool = True,
|
| 132 |
+
) -> None:
|
| 133 |
+
"""
|
| 134 |
+
指定されたディレクトリから古いチェックポイントを削除して空き容量を確保する
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
model_dir_path (Union[str, Path]): モデルが保存されているディレクトリのパス
|
| 138 |
+
n_ckpts_to_keep (int): 保持するチェックポイントの数(G_0.pth と D_0.pth を除く)
|
| 139 |
+
sort_by_time (bool): True の場合、時間順に削除。False の場合、名前順に削除
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
ckpts_files = [
|
| 143 |
+
f
|
| 144 |
+
for f in os.listdir(model_dir_path)
|
| 145 |
+
if os.path.isfile(os.path.join(model_dir_path, f))
|
| 146 |
+
]
|
| 147 |
+
|
| 148 |
+
def name_key(_f: str) -> int:
|
| 149 |
+
return int(re.compile("._(\\d+)\\.pth").match(_f).group(1)) # type: ignore
|
| 150 |
+
|
| 151 |
+
def time_key(_f: str) -> float:
|
| 152 |
+
return os.path.getmtime(os.path.join(model_dir_path, _f))
|
| 153 |
+
|
| 154 |
+
sort_key = time_key if sort_by_time else name_key
|
| 155 |
+
|
| 156 |
+
def x_sorted(_x: str) -> list[str]:
|
| 157 |
+
return sorted(
|
| 158 |
+
[f for f in ckpts_files if f.startswith(_x) and not f.endswith("_0.pth")],
|
| 159 |
+
key=sort_key,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
to_del = [
|
| 163 |
+
os.path.join(model_dir_path, fn)
|
| 164 |
+
for fn in (
|
| 165 |
+
x_sorted("G_")[:-n_ckpts_to_keep]
|
| 166 |
+
+ x_sorted("D_")[:-n_ckpts_to_keep]
|
| 167 |
+
+ x_sorted("WD_")[:-n_ckpts_to_keep]
|
| 168 |
+
+ x_sorted("DUR_")[:-n_ckpts_to_keep]
|
| 169 |
+
)
|
| 170 |
+
]
|
| 171 |
+
|
| 172 |
+
def del_info(fn: str) -> None:
|
| 173 |
+
return logger.info(f"Free up space by deleting ckpt {fn}")
|
| 174 |
+
|
| 175 |
+
def del_routine(x: str) -> list[Any]:
|
| 176 |
+
return [os.remove(x), del_info(x)]
|
| 177 |
+
|
| 178 |
+
[del_routine(fn) for fn in to_del]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def get_latest_checkpoint_path(
|
| 182 |
+
model_dir_path: Union[str, Path], regex: str = "G_*.pth"
|
| 183 |
+
) -> str:
|
| 184 |
+
"""
|
| 185 |
+
指定されたディレクトリから最新のチェックポイントのパスを取得する
|
| 186 |
+
|
| 187 |
+
Args:
|
| 188 |
+
model_dir_path (Union[str, Path]): モデルが保存されているディレクトリのパス
|
| 189 |
+
regex (str): チェックポイントのファイル名の正規表現
|
| 190 |
+
|
| 191 |
+
Returns:
|
| 192 |
+
str: 最新のチェックポイントのパス
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
f_list = glob.glob(os.path.join(str(model_dir_path), regex))
|
| 196 |
+
f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
|
| 197 |
+
try:
|
| 198 |
+
x = f_list[-1]
|
| 199 |
+
except IndexError:
|
| 200 |
+
raise ValueError(f"No checkpoint found in {model_dir_path} with regex {regex}")
|
| 201 |
+
|
| 202 |
+
return x
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/models/utils/safetensors.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Any, Optional, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from safetensors import safe_open
|
| 6 |
+
from safetensors.torch import save_file
|
| 7 |
+
|
| 8 |
+
from style_bert_vits2.logging import logger
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_safetensors(
|
| 12 |
+
checkpoint_path: Union[str, Path],
|
| 13 |
+
model: torch.nn.Module,
|
| 14 |
+
for_infer: bool = False,
|
| 15 |
+
) -> tuple[torch.nn.Module, Optional[int]]:
|
| 16 |
+
"""
|
| 17 |
+
指定されたパスから safetensors モデルを読み込み、モデルとイテレーションを返す。
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
checkpoint_path (Union[str, Path]): モデルのチェックポイントファイルのパス
|
| 21 |
+
model (torch.nn.Module): 読み込む対象のモデル
|
| 22 |
+
for_infer (bool): 推論用に読み込むかどうかのフラグ
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
tuple[torch.nn.Module, Optional[int]]: 読み込まれたモデルとイテレーション回数(存在する場合)
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
tensors: dict[str, Any] = {}
|
| 29 |
+
iteration: Optional[int] = None
|
| 30 |
+
with safe_open(str(checkpoint_path), framework="pt", device="cpu") as f: # type: ignore
|
| 31 |
+
for key in f.keys():
|
| 32 |
+
if key == "iteration":
|
| 33 |
+
iteration = f.get_tensor(key).item()
|
| 34 |
+
tensors[key] = f.get_tensor(key)
|
| 35 |
+
if hasattr(model, "module"):
|
| 36 |
+
result = model.module.load_state_dict(tensors, strict=False)
|
| 37 |
+
else:
|
| 38 |
+
result = model.load_state_dict(tensors, strict=False)
|
| 39 |
+
for key in result.missing_keys:
|
| 40 |
+
if key.startswith("enc_q") and for_infer:
|
| 41 |
+
continue
|
| 42 |
+
logger.warning(f"Missing key: {key}")
|
| 43 |
+
for key in result.unexpected_keys:
|
| 44 |
+
if key == "iteration":
|
| 45 |
+
continue
|
| 46 |
+
logger.warning(f"Unexpected key: {key}")
|
| 47 |
+
if iteration is None:
|
| 48 |
+
logger.info(f"Loaded '{checkpoint_path}'")
|
| 49 |
+
else:
|
| 50 |
+
logger.info(f"Loaded '{checkpoint_path}' (iteration {iteration})")
|
| 51 |
+
|
| 52 |
+
return model, iteration
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def save_safetensors(
|
| 56 |
+
model: torch.nn.Module,
|
| 57 |
+
iteration: int,
|
| 58 |
+
checkpoint_path: Union[str, Path],
|
| 59 |
+
is_half: bool = False,
|
| 60 |
+
for_infer: bool = False,
|
| 61 |
+
) -> None:
|
| 62 |
+
"""
|
| 63 |
+
モデルを safetensors 形式で保存する。
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
model (torch.nn.Module): 保存するモデル
|
| 67 |
+
iteration (int): イテレーション回数
|
| 68 |
+
checkpoint_path (Union[str, Path]): 保存先のパス
|
| 69 |
+
is_half (bool): モデルを半精度で保存するかどうかのフラグ
|
| 70 |
+
for_infer (bool): 推論用に保存するかどうかのフラグ
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
if hasattr(model, "module"):
|
| 74 |
+
state_dict = model.module.state_dict()
|
| 75 |
+
else:
|
| 76 |
+
state_dict = model.state_dict()
|
| 77 |
+
keys = []
|
| 78 |
+
for k in state_dict:
|
| 79 |
+
if "enc_q" in k and for_infer:
|
| 80 |
+
continue
|
| 81 |
+
keys.append(k)
|
| 82 |
+
|
| 83 |
+
new_dict = (
|
| 84 |
+
{k: state_dict[k].half() for k in keys}
|
| 85 |
+
if is_half
|
| 86 |
+
else {k: state_dict[k] for k in keys}
|
| 87 |
+
)
|
| 88 |
+
new_dict["iteration"] = torch.LongTensor([iteration])
|
| 89 |
+
logger.info(f"Saved safetensors to {checkpoint_path}")
|
| 90 |
+
|
| 91 |
+
save_file(new_dict, checkpoint_path)
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/__init__.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Optional
|
| 2 |
+
|
| 3 |
+
from style_bert_vits2.constants import Languages
|
| 4 |
+
from style_bert_vits2.nlp.symbols import (
|
| 5 |
+
LANGUAGE_ID_MAP,
|
| 6 |
+
LANGUAGE_TONE_START_MAP,
|
| 7 |
+
SYMBOLS,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# __init__.py は配下のモジュールをインポートした時点で実行される
|
| 12 |
+
# PyTorch のインポートは重いので、型チェック時以外はインポートしない
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
__symbol_to_id = {s: i for i, s in enumerate(SYMBOLS)}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def extract_bert_feature(
|
| 21 |
+
text: str,
|
| 22 |
+
word2ph: list[int],
|
| 23 |
+
language: Languages,
|
| 24 |
+
device: str,
|
| 25 |
+
assist_text: Optional[str] = None,
|
| 26 |
+
assist_text_weight: float = 0.7,
|
| 27 |
+
) -> "torch.Tensor":
|
| 28 |
+
"""
|
| 29 |
+
テキストから BERT の特徴量を抽出する
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
text (str): テキスト
|
| 33 |
+
word2ph (list[int]): 元のテキストの各文字に音素が何個割り当てられるかを表すリスト
|
| 34 |
+
language (Languages): テキストの言語
|
| 35 |
+
device (str): 推論に利用するデバイス
|
| 36 |
+
assist_text (Optional[str], optional): 補助テキスト (デフォルト: None)
|
| 37 |
+
assist_text_weight (float, optional): 補助テキストの重み (デフォルト: 0.7)
|
| 38 |
+
|
| 39 |
+
Returns:
|
| 40 |
+
torch.Tensor: BERT の特徴量
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
if language == Languages.JP:
|
| 44 |
+
from style_bert_vits2.nlp.japanese.bert_feature import extract_bert_feature
|
| 45 |
+
elif language == Languages.EN:
|
| 46 |
+
from style_bert_vits2.nlp.english.bert_feature import extract_bert_feature
|
| 47 |
+
elif language == Languages.ZH:
|
| 48 |
+
from style_bert_vits2.nlp.chinese.bert_feature import extract_bert_feature
|
| 49 |
+
else:
|
| 50 |
+
raise ValueError(f"Language {language} not supported")
|
| 51 |
+
|
| 52 |
+
return extract_bert_feature(text, word2ph, device, assist_text, assist_text_weight)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def clean_text(
|
| 56 |
+
text: str,
|
| 57 |
+
language: Languages,
|
| 58 |
+
use_jp_extra: bool = True,
|
| 59 |
+
raise_yomi_error: bool = False,
|
| 60 |
+
) -> tuple[str, list[str], list[int], list[int]]:
|
| 61 |
+
"""
|
| 62 |
+
テキストをクリーニングし、音素に変換する
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
text (str): クリーニングするテキスト
|
| 66 |
+
language (Languages): テキストの言語
|
| 67 |
+
use_jp_extra (bool, optional): テキストが日本語の場合に JP-Extra モデルを利用するかどうか。Defaults to True.
|
| 68 |
+
raise_yomi_error (bool, optional): False の場合、読めない文字が消えたような扱いとして処理される。Defaults to False.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
tuple[str, list[str], list[int], list[int]]: クリーニングされたテキストと、音素・アクセント・元のテキストの各文字に音素が何個割り当てられるかのリスト
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
# Changed to import inside if condition to avoid unnecessary import
|
| 75 |
+
if language == Languages.JP:
|
| 76 |
+
from style_bert_vits2.nlp.japanese.g2p import g2p
|
| 77 |
+
from style_bert_vits2.nlp.japanese.normalizer import normalize_text
|
| 78 |
+
|
| 79 |
+
norm_text = normalize_text(text)
|
| 80 |
+
phones, tones, word2ph = g2p(norm_text, use_jp_extra, raise_yomi_error)
|
| 81 |
+
elif language == Languages.EN:
|
| 82 |
+
from style_bert_vits2.nlp.english.g2p import g2p
|
| 83 |
+
from style_bert_vits2.nlp.english.normalizer import normalize_text
|
| 84 |
+
|
| 85 |
+
norm_text = normalize_text(text)
|
| 86 |
+
phones, tones, word2ph = g2p(norm_text)
|
| 87 |
+
elif language == Languages.ZH:
|
| 88 |
+
from style_bert_vits2.nlp.chinese.g2p import g2p
|
| 89 |
+
from style_bert_vits2.nlp.chinese.normalizer import normalize_text
|
| 90 |
+
|
| 91 |
+
norm_text = normalize_text(text)
|
| 92 |
+
phones, tones, word2ph = g2p(norm_text)
|
| 93 |
+
else:
|
| 94 |
+
raise ValueError(f"Language {language} not supported")
|
| 95 |
+
|
| 96 |
+
return norm_text, phones, tones, word2ph
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def cleaned_text_to_sequence(
|
| 100 |
+
cleaned_phones: list[str], tones: list[int], language: Languages
|
| 101 |
+
) -> tuple[list[int], list[int], list[int]]:
|
| 102 |
+
"""
|
| 103 |
+
音素リスト・アクセントリスト・言語を、テキスト内の対応する ID に変換する
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
cleaned_phones (list[str]): clean_text() でクリーニングされた音素のリスト
|
| 107 |
+
tones (list[int]): 各音素のアクセント
|
| 108 |
+
language (Languages): テキストの言語
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
tuple[list[int], list[int], list[int]]: List of integers corresponding to the symbols in the text
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
phones = [__symbol_to_id[symbol] for symbol in cleaned_phones]
|
| 115 |
+
tone_start = LANGUAGE_TONE_START_MAP[language]
|
| 116 |
+
tones = [i + tone_start for i in tones]
|
| 117 |
+
lang_id = LANGUAGE_ID_MAP[language]
|
| 118 |
+
lang_ids = [lang_id for i in phones]
|
| 119 |
+
|
| 120 |
+
return phones, tones, lang_ids
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/bert_models.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Style-Bert-VITS2 の学習・推論に必要な各言語ごとの BERT モデルをロード/取得するためのモジュール。
|
| 3 |
+
|
| 4 |
+
オリジナルの Bert-VITS2 では各言語ごとの BERT モデルが初回インポート時にハードコードされたパスから「暗黙的に」ロードされているが、
|
| 5 |
+
場合によっては多重にロードされて非効率なほか、BERT モデルのロード元のパスがハードコードされているためライブラリ化ができない。
|
| 6 |
+
|
| 7 |
+
そこで、ライブラリの利用前に、音声合成に利用する言語の BERT モデルだけを「明示的に」ロードできるようにした。
|
| 8 |
+
一度 load_model/tokenizer() で当該言語の BERT モデルがロードされていれば、ライブラリ内部のどこからでもロード済みのモデル/トークナイザーを取得できる。
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import gc
|
| 12 |
+
from typing import Optional, Union, cast
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from transformers import (
|
| 16 |
+
AutoModelForMaskedLM,
|
| 17 |
+
AutoTokenizer,
|
| 18 |
+
DebertaV2Model,
|
| 19 |
+
DebertaV2Tokenizer,
|
| 20 |
+
PreTrainedModel,
|
| 21 |
+
PreTrainedTokenizer,
|
| 22 |
+
PreTrainedTokenizerFast,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
from style_bert_vits2.constants import DEFAULT_BERT_TOKENIZER_PATHS, Languages
|
| 26 |
+
from style_bert_vits2.logging import logger
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# 各言語ごとのロード済みの BERT モデルを格納する辞書
|
| 30 |
+
__loaded_models: dict[Languages, Union[PreTrainedModel, DebertaV2Model]] = {}
|
| 31 |
+
|
| 32 |
+
# 各言語ごとのロード済みの BERT トークナイザーを格納する辞書
|
| 33 |
+
__loaded_tokenizers: dict[
|
| 34 |
+
Languages, Union[PreTrainedTokenizer, PreTrainedTokenizerFast, DebertaV2Tokenizer]
|
| 35 |
+
] = {}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def load_model(
|
| 39 |
+
language: Languages,
|
| 40 |
+
pretrained_model_name_or_path: Optional[str] = None,
|
| 41 |
+
cache_dir: Optional[str] = None,
|
| 42 |
+
revision: str = "main",
|
| 43 |
+
) -> Union[PreTrainedModel, DebertaV2Model]:
|
| 44 |
+
"""
|
| 45 |
+
指定された言語の BERT モデルをロードし、ロード済みの BERT モデルを返す。
|
| 46 |
+
一度ロードされていれば、ロード済みの BERT モデルを即座に返す。
|
| 47 |
+
ライブラリ利用時は常に必ず pretrain_model_name_or_path (Hugging Face のリポジトリ名 or ローカルのファイルパス) を指定する必要がある。
|
| 48 |
+
ロードにはそれなりに時間がかかるため、ライブラリ利用前に明示的に pretrained_model_name_or_path を指定してロードしておくべき。
|
| 49 |
+
cache_dir と revision は pretrain_model_name_or_path がリポジトリ名の場合のみ有効。
|
| 50 |
+
|
| 51 |
+
Style-Bert-VITS2 では、BERT モデルに下記の 3 つが利用されている。
|
| 52 |
+
これ以外の BERT モデルを指定した場合は正常に動作しない可能性が高い。
|
| 53 |
+
- 日本語: ku-nlp/deberta-v2-large-japanese-char-wwm
|
| 54 |
+
- 英語: microsoft/deberta-v3-large
|
| 55 |
+
- 中国語: hfl/chinese-roberta-wwm-ext-large
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
language (Languages): ロードする学習済みモデルの対象言語
|
| 59 |
+
pretrained_model_name_or_path (Optional[str]): ロードする学習済みモデルの名前またはパス。指定しない場合はデフォルトのパスが利用される (デフォルト: None)
|
| 60 |
+
cache_dir (Optional[str]): モデルのキャッシュディレクトリ。指定しない場合はデフォルトのキャッシュディレクトリが利用される (デフォルト: None)
|
| 61 |
+
revision (str): モデルの Hugging Face 上の Git リビジョン。指定しない場合は最新の main ブランチの内容が利用される (デフォルト: None)
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
Union[PreTrainedModel, DebertaV2Model]: ロード済みの BERT モデル
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
# すでにロード済みの場合はそのまま返す
|
| 68 |
+
if language in __loaded_models:
|
| 69 |
+
return __loaded_models[language]
|
| 70 |
+
|
| 71 |
+
# pretrained_model_name_or_path が指定されていない場合はデフォルトのパスを利用
|
| 72 |
+
if pretrained_model_name_or_path is None:
|
| 73 |
+
assert DEFAULT_BERT_TOKENIZER_PATHS[
|
| 74 |
+
language
|
| 75 |
+
].exists(), f"The default {language} BERT model does not exist on the file system. Please specify the path to the pre-trained model."
|
| 76 |
+
pretrained_model_name_or_path = str(DEFAULT_BERT_TOKENIZER_PATHS[language])
|
| 77 |
+
|
| 78 |
+
# BERT モデルをロードし、辞書に格納して返す
|
| 79 |
+
## 英語のみ DebertaV2Model でロードする必要がある
|
| 80 |
+
if language == Languages.EN:
|
| 81 |
+
model = cast(
|
| 82 |
+
DebertaV2Model,
|
| 83 |
+
DebertaV2Model.from_pretrained(
|
| 84 |
+
pretrained_model_name_or_path, cache_dir=cache_dir, revision=revision
|
| 85 |
+
),
|
| 86 |
+
)
|
| 87 |
+
else:
|
| 88 |
+
model = AutoModelForMaskedLM.from_pretrained(
|
| 89 |
+
pretrained_model_name_or_path, cache_dir=cache_dir, revision=revision
|
| 90 |
+
)
|
| 91 |
+
__loaded_models[language] = model
|
| 92 |
+
logger.info(
|
| 93 |
+
f"Loaded the {language} BERT model from {pretrained_model_name_or_path}"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
return model
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def load_tokenizer(
|
| 100 |
+
language: Languages,
|
| 101 |
+
pretrained_model_name_or_path: Optional[str] = None,
|
| 102 |
+
cache_dir: Optional[str] = None,
|
| 103 |
+
revision: str = "main",
|
| 104 |
+
) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast, DebertaV2Tokenizer]:
|
| 105 |
+
"""
|
| 106 |
+
指定された言語の BERT モデルをロードし、ロード済みの BERT トークナイザーを返す。
|
| 107 |
+
一度ロードされていれば、ロード済みの BERT トークナイザーを即座に返す。
|
| 108 |
+
ライブラリ利用時は常に必ず pretrain_model_name_or_path (Hugging Face のリポジトリ名 or ローカルのファイルパス) を指定する必要がある。
|
| 109 |
+
ロードにはそれなりに時間がかかるため、ライブラリ利用前に明示的に pretrained_model_name_or_path を指定してロードしておくべき。
|
| 110 |
+
cache_dir と revision は pretrain_model_name_or_path がリポジトリ名の場合のみ有効。
|
| 111 |
+
|
| 112 |
+
Style-Bert-VITS2 では、BERT モデルに下記の 3 つが利用されている。
|
| 113 |
+
これ以外の BERT モデルを指定した場合は正常に動作しない可能性が高い。
|
| 114 |
+
- 日本語: ku-nlp/deberta-v2-large-japanese-char-wwm
|
| 115 |
+
- 英語: microsoft/deberta-v3-large
|
| 116 |
+
- 中国語: hfl/chinese-roberta-wwm-ext-large
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
language (Languages): ロードする学習済みモデルの対象言語
|
| 120 |
+
pretrained_model_name_or_path (Optional[str]): ロードする学習済みモデルの名前またはパス。指定しない場合はデフォルトのパスが利用される (デフォルト: None)
|
| 121 |
+
cache_dir (Optional[str]): モデルのキャッシュディレクトリ。指定しない場合はデフォルトのキャッシュディレクトリが利用される (デフォルト: None)
|
| 122 |
+
revision (str): モデルの Hugging Face 上の Git リビジョン。指定しない場合は最新の main ブランチの内容が利用される (デフォルト: None)
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
Union[PreTrainedTokenizer, PreTrainedTokenizerFast, DebertaV2Tokenizer]: ロード済みの BERT トークナイザー
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
# すでにロード済みの場合はそのまま返す
|
| 129 |
+
if language in __loaded_tokenizers:
|
| 130 |
+
return __loaded_tokenizers[language]
|
| 131 |
+
|
| 132 |
+
# pretrained_model_name_or_path が指定されていない場合はデフォルトのパスを利用
|
| 133 |
+
if pretrained_model_name_or_path is None:
|
| 134 |
+
assert DEFAULT_BERT_TOKENIZER_PATHS[
|
| 135 |
+
language
|
| 136 |
+
].exists(), f"The default {language} BERT tokenizer does not exist on the file system. Please specify the path to the pre-trained model."
|
| 137 |
+
pretrained_model_name_or_path = str(DEFAULT_BERT_TOKENIZER_PATHS[language])
|
| 138 |
+
|
| 139 |
+
# BERT トークナイザーをロードし、辞書に格納して返す
|
| 140 |
+
## 英語のみ DebertaV2Tokenizer でロードする必要がある
|
| 141 |
+
if language == Languages.EN:
|
| 142 |
+
tokenizer = DebertaV2Tokenizer.from_pretrained(
|
| 143 |
+
pretrained_model_name_or_path,
|
| 144 |
+
cache_dir=cache_dir,
|
| 145 |
+
revision=revision,
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 149 |
+
pretrained_model_name_or_path,
|
| 150 |
+
cache_dir=cache_dir,
|
| 151 |
+
revision=revision,
|
| 152 |
+
)
|
| 153 |
+
__loaded_tokenizers[language] = tokenizer
|
| 154 |
+
logger.info(
|
| 155 |
+
f"Loaded the {language} BERT tokenizer from {pretrained_model_name_or_path}"
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
return tokenizer
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def unload_model(language: Languages) -> None:
|
| 162 |
+
"""
|
| 163 |
+
指定された言語の BERT モデルをアンロードする。
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
language (Languages): アンロードする BERT モデルの言語
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
if language in __loaded_models:
|
| 170 |
+
del __loaded_models[language]
|
| 171 |
+
gc.collect()
|
| 172 |
+
if torch.cuda.is_available():
|
| 173 |
+
torch.cuda.empty_cache()
|
| 174 |
+
logger.info(f"Unloaded the {language} BERT model")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def unload_tokenizer(language: Languages) -> None:
|
| 178 |
+
"""
|
| 179 |
+
指定された言語の BERT トークナイザーをアンロードする。
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
language (Languages): アンロードする BERT トークナイザーの言語
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
if language in __loaded_tokenizers:
|
| 186 |
+
del __loaded_tokenizers[language]
|
| 187 |
+
gc.collect()
|
| 188 |
+
if torch.cuda.is_available():
|
| 189 |
+
torch.cuda.empty_cache()
|
| 190 |
+
logger.info(f"Unloaded the {language} BERT tokenizer")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def unload_all_models() -> None:
|
| 194 |
+
"""
|
| 195 |
+
すべての BERT モデルをアンロードする。
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
for language in list(__loaded_models.keys()):
|
| 199 |
+
unload_model(language)
|
| 200 |
+
logger.info("Unloaded all BERT models")
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def unload_all_tokenizers() -> None:
|
| 204 |
+
"""
|
| 205 |
+
すべての BERT トークナイザーをアンロードする。
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
for language in list(__loaded_tokenizers.keys()):
|
| 209 |
+
unload_tokenizer(language)
|
| 210 |
+
logger.info("Unloaded all BERT tokenizers")
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/__init__.py
ADDED
|
File without changes
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/bert_feature.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from style_bert_vits2.constants import Languages
|
| 6 |
+
from style_bert_vits2.nlp import bert_models
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def extract_bert_feature(
|
| 10 |
+
text: str,
|
| 11 |
+
word2ph: list[int],
|
| 12 |
+
device: str,
|
| 13 |
+
assist_text: Optional[str] = None,
|
| 14 |
+
assist_text_weight: float = 0.7,
|
| 15 |
+
) -> torch.Tensor:
|
| 16 |
+
"""
|
| 17 |
+
中国語のテキストから BERT の特徴量を抽出する
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
text (str): 中国語のテキスト
|
| 21 |
+
word2ph (list[int]): 元のテキストの各文字に音素が何個割り当てられるかを表すリスト
|
| 22 |
+
device (str): 推論に利用するデバイス
|
| 23 |
+
assist_text (Optional[str], optional): 補助テキスト (デフォルト: None)
|
| 24 |
+
assist_text_weight (float, optional): 補助テキストの重み (デフォルト: 0.7)
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
torch.Tensor: BERT の特徴量
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
if device == "cuda" and not torch.cuda.is_available():
|
| 31 |
+
device = "cpu"
|
| 32 |
+
model = bert_models.load_model(Languages.ZH).to(device) # type: ignore
|
| 33 |
+
|
| 34 |
+
style_res_mean = None
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
tokenizer = bert_models.load_tokenizer(Languages.ZH)
|
| 37 |
+
inputs = tokenizer(text, return_tensors="pt")
|
| 38 |
+
for i in inputs:
|
| 39 |
+
inputs[i] = inputs[i].to(device) # type: ignore
|
| 40 |
+
res = model(**inputs, output_hidden_states=True)
|
| 41 |
+
res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()
|
| 42 |
+
if assist_text:
|
| 43 |
+
style_inputs = tokenizer(assist_text, return_tensors="pt")
|
| 44 |
+
for i in style_inputs:
|
| 45 |
+
style_inputs[i] = style_inputs[i].to(device) # type: ignore
|
| 46 |
+
style_res = model(**style_inputs, output_hidden_states=True)
|
| 47 |
+
style_res = torch.cat(style_res["hidden_states"][-3:-2], -1)[0].cpu()
|
| 48 |
+
style_res_mean = style_res.mean(0)
|
| 49 |
+
|
| 50 |
+
assert len(word2ph) == len(text) + 2
|
| 51 |
+
word2phone = word2ph
|
| 52 |
+
phone_level_feature = []
|
| 53 |
+
for i in range(len(word2phone)):
|
| 54 |
+
if assist_text:
|
| 55 |
+
assert style_res_mean is not None
|
| 56 |
+
repeat_feature = (
|
| 57 |
+
res[i].repeat(word2phone[i], 1) * (1 - assist_text_weight)
|
| 58 |
+
+ style_res_mean.repeat(word2phone[i], 1) * assist_text_weight
|
| 59 |
+
)
|
| 60 |
+
else:
|
| 61 |
+
repeat_feature = res[i].repeat(word2phone[i], 1)
|
| 62 |
+
phone_level_feature.append(repeat_feature)
|
| 63 |
+
|
| 64 |
+
phone_level_feature = torch.cat(phone_level_feature, dim=0)
|
| 65 |
+
|
| 66 |
+
return phone_level_feature.T
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
if __name__ == "__main__":
|
| 70 |
+
word_level_feature = torch.rand(38, 1024) # 12个词,每个词1024维特征
|
| 71 |
+
word2phone = [
|
| 72 |
+
1,
|
| 73 |
+
2,
|
| 74 |
+
1,
|
| 75 |
+
2,
|
| 76 |
+
2,
|
| 77 |
+
1,
|
| 78 |
+
2,
|
| 79 |
+
2,
|
| 80 |
+
1,
|
| 81 |
+
2,
|
| 82 |
+
2,
|
| 83 |
+
1,
|
| 84 |
+
2,
|
| 85 |
+
2,
|
| 86 |
+
2,
|
| 87 |
+
2,
|
| 88 |
+
2,
|
| 89 |
+
1,
|
| 90 |
+
1,
|
| 91 |
+
2,
|
| 92 |
+
2,
|
| 93 |
+
1,
|
| 94 |
+
2,
|
| 95 |
+
2,
|
| 96 |
+
2,
|
| 97 |
+
2,
|
| 98 |
+
1,
|
| 99 |
+
2,
|
| 100 |
+
2,
|
| 101 |
+
2,
|
| 102 |
+
2,
|
| 103 |
+
2,
|
| 104 |
+
1,
|
| 105 |
+
2,
|
| 106 |
+
2,
|
| 107 |
+
2,
|
| 108 |
+
2,
|
| 109 |
+
1,
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
# 计算总帧数
|
| 113 |
+
total_frames = sum(word2phone)
|
| 114 |
+
print(word_level_feature.shape)
|
| 115 |
+
print(word2phone)
|
| 116 |
+
phone_level_feature = []
|
| 117 |
+
for i in range(len(word2phone)):
|
| 118 |
+
print(word_level_feature[i].shape)
|
| 119 |
+
|
| 120 |
+
# 对每个词重复word2phone[i]次
|
| 121 |
+
repeat_feature = word_level_feature[i].repeat(word2phone[i], 1)
|
| 122 |
+
phone_level_feature.append(repeat_feature)
|
| 123 |
+
|
| 124 |
+
phone_level_feature = torch.cat(phone_level_feature, dim=0)
|
| 125 |
+
print(phone_level_feature.shape) # torch.Size([36, 1024])
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/g2p.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import jieba.posseg as psg
|
| 5 |
+
from pypinyin import Style, lazy_pinyin
|
| 6 |
+
|
| 7 |
+
from style_bert_vits2.nlp.chinese.tone_sandhi import ToneSandhi
|
| 8 |
+
from style_bert_vits2.nlp.symbols import PUNCTUATIONS
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
with open(Path(__file__).parent / "opencpop-strict.txt", encoding="utf-8") as f:
|
| 12 |
+
__PINYIN_TO_SYMBOL_MAP = {
|
| 13 |
+
line.split("\t")[0]: line.strip().split("\t")[1] for line in f.readlines()
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def g2p(text: str) -> tuple[list[str], list[int], list[int]]:
|
| 18 |
+
pattern = r"(?<=[{0}])\s*".format("".join(PUNCTUATIONS))
|
| 19 |
+
sentences = [i for i in re.split(pattern, text) if i.strip() != ""]
|
| 20 |
+
phones, tones, word2ph = __g2p(sentences)
|
| 21 |
+
assert sum(word2ph) == len(phones)
|
| 22 |
+
assert len(word2ph) == len(text) # Sometimes it will crash,you can add a try-catch.
|
| 23 |
+
phones = ["_"] + phones + ["_"]
|
| 24 |
+
tones = [0] + tones + [0]
|
| 25 |
+
word2ph = [1] + word2ph + [1]
|
| 26 |
+
return phones, tones, word2ph
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def __g2p(segments: list[str]) -> tuple[list[str], list[int], list[int]]:
|
| 30 |
+
phones_list = []
|
| 31 |
+
tones_list = []
|
| 32 |
+
word2ph = []
|
| 33 |
+
tone_modifier = ToneSandhi()
|
| 34 |
+
for seg in segments:
|
| 35 |
+
# Replace all English words in the sentence
|
| 36 |
+
seg = re.sub("[a-zA-Z]+", "", seg)
|
| 37 |
+
seg_cut = psg.lcut(seg)
|
| 38 |
+
initials = []
|
| 39 |
+
finals = []
|
| 40 |
+
seg_cut = tone_modifier.pre_merge_for_modify(seg_cut) # type: ignore
|
| 41 |
+
for word, pos in seg_cut:
|
| 42 |
+
if pos == "eng":
|
| 43 |
+
continue
|
| 44 |
+
sub_initials, sub_finals = __get_initials_finals(word)
|
| 45 |
+
sub_finals = tone_modifier.modified_tone(word, pos, sub_finals)
|
| 46 |
+
initials.append(sub_initials)
|
| 47 |
+
finals.append(sub_finals)
|
| 48 |
+
|
| 49 |
+
# assert len(sub_initials) == len(sub_finals) == len(word)
|
| 50 |
+
initials = sum(initials, [])
|
| 51 |
+
finals = sum(finals, [])
|
| 52 |
+
#
|
| 53 |
+
for c, v in zip(initials, finals):
|
| 54 |
+
raw_pinyin = c + v
|
| 55 |
+
# NOTE: post process for pypinyin outputs
|
| 56 |
+
# we discriminate i, ii and iii
|
| 57 |
+
if c == v:
|
| 58 |
+
assert c in PUNCTUATIONS
|
| 59 |
+
phone = [c]
|
| 60 |
+
tone = "0"
|
| 61 |
+
word2ph.append(1)
|
| 62 |
+
else:
|
| 63 |
+
v_without_tone = v[:-1]
|
| 64 |
+
tone = v[-1]
|
| 65 |
+
|
| 66 |
+
pinyin = c + v_without_tone
|
| 67 |
+
assert tone in "12345"
|
| 68 |
+
|
| 69 |
+
if c:
|
| 70 |
+
# 多音节
|
| 71 |
+
v_rep_map = {
|
| 72 |
+
"uei": "ui",
|
| 73 |
+
"iou": "iu",
|
| 74 |
+
"uen": "un",
|
| 75 |
+
}
|
| 76 |
+
if v_without_tone in v_rep_map:
|
| 77 |
+
pinyin = c + v_rep_map[v_without_tone]
|
| 78 |
+
else:
|
| 79 |
+
# 单音节
|
| 80 |
+
pinyin_rep_map = {
|
| 81 |
+
"ing": "ying",
|
| 82 |
+
"i": "yi",
|
| 83 |
+
"in": "yin",
|
| 84 |
+
"u": "wu",
|
| 85 |
+
}
|
| 86 |
+
if pinyin in pinyin_rep_map:
|
| 87 |
+
pinyin = pinyin_rep_map[pinyin]
|
| 88 |
+
else:
|
| 89 |
+
single_rep_map = {
|
| 90 |
+
"v": "yu",
|
| 91 |
+
"e": "e",
|
| 92 |
+
"i": "y",
|
| 93 |
+
"u": "w",
|
| 94 |
+
}
|
| 95 |
+
if pinyin[0] in single_rep_map:
|
| 96 |
+
pinyin = single_rep_map[pinyin[0]] + pinyin[1:]
|
| 97 |
+
|
| 98 |
+
assert pinyin in __PINYIN_TO_SYMBOL_MAP, (
|
| 99 |
+
pinyin,
|
| 100 |
+
seg,
|
| 101 |
+
raw_pinyin,
|
| 102 |
+
)
|
| 103 |
+
phone = __PINYIN_TO_SYMBOL_MAP[pinyin].split(" ")
|
| 104 |
+
word2ph.append(len(phone))
|
| 105 |
+
|
| 106 |
+
phones_list += phone
|
| 107 |
+
tones_list += [int(tone)] * len(phone)
|
| 108 |
+
return phones_list, tones_list, word2ph
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def __get_initials_finals(word: str) -> tuple[list[str], list[str]]:
|
| 112 |
+
initials = []
|
| 113 |
+
finals = []
|
| 114 |
+
orig_initials = lazy_pinyin(word, neutral_tone_with_five=True, style=Style.INITIALS)
|
| 115 |
+
orig_finals = lazy_pinyin(
|
| 116 |
+
word, neutral_tone_with_five=True, style=Style.FINALS_TONE3
|
| 117 |
+
)
|
| 118 |
+
for c, v in zip(orig_initials, orig_finals):
|
| 119 |
+
initials.append(c)
|
| 120 |
+
finals.append(v)
|
| 121 |
+
return initials, finals
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
from style_bert_vits2.nlp.chinese.bert_feature import extract_bert_feature
|
| 126 |
+
from style_bert_vits2.nlp.chinese.normalizer import normalize_text
|
| 127 |
+
|
| 128 |
+
text = "啊!但是《原神》是由,米哈游自主, [研发]的一款全.新开放世界.冒险游戏"
|
| 129 |
+
text = normalize_text(text)
|
| 130 |
+
print(text)
|
| 131 |
+
phones, tones, word2ph = g2p(text)
|
| 132 |
+
bert = extract_bert_feature(text, word2ph, "cuda")
|
| 133 |
+
|
| 134 |
+
print(phones, tones, word2ph, bert.shape)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# 示例用法
|
| 138 |
+
# text = "这是一个示例文本:,你好!这是一个测试...."
|
| 139 |
+
# print(g2p_paddle(text)) # 输出: 这是一个示例文本你好这是一个测试
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/normalizer.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import cn2an
|
| 4 |
+
|
| 5 |
+
from style_bert_vits2.nlp.symbols import PUNCTUATIONS
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__REPLACE_MAP = {
|
| 9 |
+
":": ",",
|
| 10 |
+
";": ",",
|
| 11 |
+
",": ",",
|
| 12 |
+
"。": ".",
|
| 13 |
+
"!": "!",
|
| 14 |
+
"?": "?",
|
| 15 |
+
"\n": ".",
|
| 16 |
+
"·": ",",
|
| 17 |
+
"、": ",",
|
| 18 |
+
"...": "…",
|
| 19 |
+
"$": ".",
|
| 20 |
+
"“": "'",
|
| 21 |
+
"”": "'",
|
| 22 |
+
'"': "'",
|
| 23 |
+
"‘": "'",
|
| 24 |
+
"’": "'",
|
| 25 |
+
"(": "'",
|
| 26 |
+
")": "'",
|
| 27 |
+
"(": "'",
|
| 28 |
+
")": "'",
|
| 29 |
+
"《": "'",
|
| 30 |
+
"》": "'",
|
| 31 |
+
"【": "'",
|
| 32 |
+
"】": "'",
|
| 33 |
+
"[": "'",
|
| 34 |
+
"]": "'",
|
| 35 |
+
"—": "-",
|
| 36 |
+
"~": "-",
|
| 37 |
+
"~": "-",
|
| 38 |
+
"「": "'",
|
| 39 |
+
"」": "'",
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def normalize_text(text: str) -> str:
|
| 44 |
+
numbers = re.findall(r"\d+(?:\.?\d+)?", text)
|
| 45 |
+
for number in numbers:
|
| 46 |
+
text = text.replace(number, cn2an.an2cn(number), 1)
|
| 47 |
+
text = replace_punctuation(text)
|
| 48 |
+
return text
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def replace_punctuation(text: str) -> str:
|
| 52 |
+
|
| 53 |
+
text = text.replace("嗯", "恩").replace("呣", "母")
|
| 54 |
+
pattern = re.compile("|".join(re.escape(p) for p in __REPLACE_MAP))
|
| 55 |
+
|
| 56 |
+
replaced_text = pattern.sub(lambda x: __REPLACE_MAP[x.group()], text)
|
| 57 |
+
|
| 58 |
+
replaced_text = re.sub(
|
| 59 |
+
r"[^\u4e00-\u9fa5" + "".join(PUNCTUATIONS) + r"]+", "", replaced_text
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
return replaced_text
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/chinese/opencpop-strict.txt
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
a AA a
|
| 2 |
+
ai AA ai
|
| 3 |
+
an AA an
|
| 4 |
+
ang AA ang
|
| 5 |
+
ao AA ao
|
| 6 |
+
ba b a
|
| 7 |
+
bai b ai
|
| 8 |
+
ban b an
|
| 9 |
+
bang b ang
|
| 10 |
+
bao b ao
|
| 11 |
+
bei b ei
|
| 12 |
+
ben b en
|
| 13 |
+
beng b eng
|
| 14 |
+
bi b i
|
| 15 |
+
bian b ian
|
| 16 |
+
biao b iao
|
| 17 |
+
bie b ie
|
| 18 |
+
bin b in
|
| 19 |
+
bing b ing
|
| 20 |
+
bo b o
|
| 21 |
+
bu b u
|
| 22 |
+
ca c a
|
| 23 |
+
cai c ai
|
| 24 |
+
can c an
|
| 25 |
+
cang c ang
|
| 26 |
+
cao c ao
|
| 27 |
+
ce c e
|
| 28 |
+
cei c ei
|
| 29 |
+
cen c en
|
| 30 |
+
ceng c eng
|
| 31 |
+
cha ch a
|
| 32 |
+
chai ch ai
|
| 33 |
+
chan ch an
|
| 34 |
+
chang ch ang
|
| 35 |
+
chao ch ao
|
| 36 |
+
che ch e
|
| 37 |
+
chen ch en
|
| 38 |
+
cheng ch eng
|
| 39 |
+
chi ch ir
|
| 40 |
+
chong ch ong
|
| 41 |
+
chou ch ou
|
| 42 |
+
chu ch u
|
| 43 |
+
chua ch ua
|
| 44 |
+
chuai ch uai
|
| 45 |
+
chuan ch uan
|
| 46 |
+
chuang ch uang
|
| 47 |
+
chui ch ui
|
| 48 |
+
chun ch un
|
| 49 |
+
chuo ch uo
|
| 50 |
+
ci c i0
|
| 51 |
+
cong c ong
|
| 52 |
+
cou c ou
|
| 53 |
+
cu c u
|
| 54 |
+
cuan c uan
|
| 55 |
+
cui c ui
|
| 56 |
+
cun c un
|
| 57 |
+
cuo c uo
|
| 58 |
+
da d a
|
| 59 |
+
dai d ai
|
| 60 |
+
dan d an
|
| 61 |
+
dang d ang
|
| 62 |
+
dao d ao
|
| 63 |
+
de d e
|
| 64 |
+
dei d ei
|
| 65 |
+
den d en
|
| 66 |
+
deng d eng
|
| 67 |
+
di d i
|
| 68 |
+
dia d ia
|
| 69 |
+
dian d ian
|
| 70 |
+
diao d iao
|
| 71 |
+
die d ie
|
| 72 |
+
ding d ing
|
| 73 |
+
diu d iu
|
| 74 |
+
dong d ong
|
| 75 |
+
dou d ou
|
| 76 |
+
du d u
|
| 77 |
+
duan d uan
|
| 78 |
+
dui d ui
|
| 79 |
+
dun d un
|
| 80 |
+
duo d uo
|
| 81 |
+
e EE e
|
| 82 |
+
ei EE ei
|
| 83 |
+
en EE en
|
| 84 |
+
eng EE eng
|
| 85 |
+
er EE er
|
| 86 |
+
fa f a
|
| 87 |
+
fan f an
|
| 88 |
+
fang f ang
|
| 89 |
+
fei f ei
|
| 90 |
+
fen f en
|
| 91 |
+
feng f eng
|
| 92 |
+
fo f o
|
| 93 |
+
fou f ou
|
| 94 |
+
fu f u
|
| 95 |
+
ga g a
|
| 96 |
+
gai g ai
|
| 97 |
+
gan g an
|
| 98 |
+
gang g ang
|
| 99 |
+
gao g ao
|
| 100 |
+
ge g e
|
| 101 |
+
gei g ei
|
| 102 |
+
gen g en
|
| 103 |
+
geng g eng
|
| 104 |
+
gong g ong
|
| 105 |
+
gou g ou
|
| 106 |
+
gu g u
|
| 107 |
+
gua g ua
|
| 108 |
+
guai g uai
|
| 109 |
+
guan g uan
|
| 110 |
+
guang g uang
|
| 111 |
+
gui g ui
|
| 112 |
+
gun g un
|
| 113 |
+
guo g uo
|
| 114 |
+
ha h a
|
| 115 |
+
hai h ai
|
| 116 |
+
han h an
|
| 117 |
+
hang h ang
|
| 118 |
+
hao h ao
|
| 119 |
+
he h e
|
| 120 |
+
hei h ei
|
| 121 |
+
hen h en
|
| 122 |
+
heng h eng
|
| 123 |
+
hong h ong
|
| 124 |
+
hou h ou
|
| 125 |
+
hu h u
|
| 126 |
+
hua h ua
|
| 127 |
+
huai h uai
|
| 128 |
+
huan h uan
|
| 129 |
+
huang h uang
|
| 130 |
+
hui h ui
|
| 131 |
+
hun h un
|
| 132 |
+
huo h uo
|
| 133 |
+
ji j i
|
| 134 |
+
jia j ia
|
| 135 |
+
jian j ian
|
| 136 |
+
jiang j iang
|
| 137 |
+
jiao j iao
|
| 138 |
+
jie j ie
|
| 139 |
+
jin j in
|
| 140 |
+
jing j ing
|
| 141 |
+
jiong j iong
|
| 142 |
+
jiu j iu
|
| 143 |
+
ju j v
|
| 144 |
+
jv j v
|
| 145 |
+
juan j van
|
| 146 |
+
jvan j van
|
| 147 |
+
jue j ve
|
| 148 |
+
jve j ve
|
| 149 |
+
jun j vn
|
| 150 |
+
jvn j vn
|
| 151 |
+
ka k a
|
| 152 |
+
kai k ai
|
| 153 |
+
kan k an
|
| 154 |
+
kang k ang
|
| 155 |
+
kao k ao
|
| 156 |
+
ke k e
|
| 157 |
+
kei k ei
|
| 158 |
+
ken k en
|
| 159 |
+
keng k eng
|
| 160 |
+
kong k ong
|
| 161 |
+
kou k ou
|
| 162 |
+
ku k u
|
| 163 |
+
kua k ua
|
| 164 |
+
kuai k uai
|
| 165 |
+
kuan k uan
|
| 166 |
+
kuang k uang
|
| 167 |
+
kui k ui
|
| 168 |
+
kun k un
|
| 169 |
+
kuo k uo
|
| 170 |
+
la l a
|
| 171 |
+
lai l ai
|
| 172 |
+
lan l an
|
| 173 |
+
lang l ang
|
| 174 |
+
lao l ao
|
| 175 |
+
le l e
|
| 176 |
+
lei l ei
|
| 177 |
+
leng l eng
|
| 178 |
+
li l i
|
| 179 |
+
lia l ia
|
| 180 |
+
lian l ian
|
| 181 |
+
liang l iang
|
| 182 |
+
liao l iao
|
| 183 |
+
lie l ie
|
| 184 |
+
lin l in
|
| 185 |
+
ling l ing
|
| 186 |
+
liu l iu
|
| 187 |
+
lo l o
|
| 188 |
+
long l ong
|
| 189 |
+
lou l ou
|
| 190 |
+
lu l u
|
| 191 |
+
luan l uan
|
| 192 |
+
lun l un
|
| 193 |
+
luo l uo
|
| 194 |
+
lv l v
|
| 195 |
+
lve l ve
|
| 196 |
+
ma m a
|
| 197 |
+
mai m ai
|
| 198 |
+
man m an
|
| 199 |
+
mang m ang
|
| 200 |
+
mao m ao
|
| 201 |
+
me m e
|
| 202 |
+
mei m ei
|
| 203 |
+
men m en
|
| 204 |
+
meng m eng
|
| 205 |
+
mi m i
|
| 206 |
+
mian m ian
|
| 207 |
+
miao m iao
|
| 208 |
+
mie m ie
|
| 209 |
+
min m in
|
| 210 |
+
ming m ing
|
| 211 |
+
miu m iu
|
| 212 |
+
mo m o
|
| 213 |
+
mou m ou
|
| 214 |
+
mu m u
|
| 215 |
+
na n a
|
| 216 |
+
nai n ai
|
| 217 |
+
nan n an
|
| 218 |
+
nang n ang
|
| 219 |
+
nao n ao
|
| 220 |
+
ne n e
|
| 221 |
+
nei n ei
|
| 222 |
+
nen n en
|
| 223 |
+
neng n eng
|
| 224 |
+
ni n i
|
| 225 |
+
nian n ian
|
| 226 |
+
niang n iang
|
| 227 |
+
niao n iao
|
| 228 |
+
nie n ie
|
| 229 |
+
nin n in
|
| 230 |
+
ning n ing
|
| 231 |
+
niu n iu
|
| 232 |
+
nong n ong
|
| 233 |
+
nou n ou
|
| 234 |
+
nu n u
|
| 235 |
+
nuan n uan
|
| 236 |
+
nun n un
|
| 237 |
+
nuo n uo
|
| 238 |
+
nv n v
|
| 239 |
+
nve n ve
|
| 240 |
+
o OO o
|
| 241 |
+
ou OO ou
|
| 242 |
+
pa p a
|
| 243 |
+
pai p ai
|
| 244 |
+
pan p an
|
| 245 |
+
pang p ang
|
| 246 |
+
pao p ao
|
| 247 |
+
pei p ei
|
| 248 |
+
pen p en
|
| 249 |
+
peng p eng
|
| 250 |
+
pi p i
|
| 251 |
+
pian p ian
|
| 252 |
+
piao p iao
|
| 253 |
+
pie p ie
|
| 254 |
+
pin p in
|
| 255 |
+
ping p ing
|
| 256 |
+
po p o
|
| 257 |
+
pou p ou
|
| 258 |
+
pu p u
|
| 259 |
+
qi q i
|
| 260 |
+
qia q ia
|
| 261 |
+
qian q ian
|
| 262 |
+
qiang q iang
|
| 263 |
+
qiao q iao
|
| 264 |
+
qie q ie
|
| 265 |
+
qin q in
|
| 266 |
+
qing q ing
|
| 267 |
+
qiong q iong
|
| 268 |
+
qiu q iu
|
| 269 |
+
qu q v
|
| 270 |
+
qv q v
|
| 271 |
+
quan q van
|
| 272 |
+
qvan q van
|
| 273 |
+
que q ve
|
| 274 |
+
qve q ve
|
| 275 |
+
qun q vn
|
| 276 |
+
qvn q vn
|
| 277 |
+
ran r an
|
| 278 |
+
rang r ang
|
| 279 |
+
rao r ao
|
| 280 |
+
re r e
|
| 281 |
+
ren r en
|
| 282 |
+
reng r eng
|
| 283 |
+
ri r ir
|
| 284 |
+
rong r ong
|
| 285 |
+
rou r ou
|
| 286 |
+
ru r u
|
| 287 |
+
rua r ua
|
| 288 |
+
ruan r uan
|
| 289 |
+
rui r ui
|
| 290 |
+
run r un
|
| 291 |
+
ruo r uo
|
| 292 |
+
sa s a
|
| 293 |
+
sai s ai
|
| 294 |
+
san s an
|
| 295 |
+
sang s ang
|
| 296 |
+
sao s ao
|
| 297 |
+
se s e
|
| 298 |
+
sen s en
|
| 299 |
+
seng s eng
|
| 300 |
+
sha sh a
|
| 301 |
+
shai sh ai
|
| 302 |
+
shan sh an
|
| 303 |
+
shang sh ang
|
| 304 |
+
shao sh ao
|
| 305 |
+
she sh e
|
| 306 |
+
shei sh ei
|
| 307 |
+
shen sh en
|
| 308 |
+
sheng sh eng
|
| 309 |
+
shi sh ir
|
| 310 |
+
shou sh ou
|
| 311 |
+
shu sh u
|
| 312 |
+
shua sh ua
|
| 313 |
+
shuai sh uai
|
| 314 |
+
shuan sh uan
|
| 315 |
+
shuang sh uang
|
| 316 |
+
shui sh ui
|
| 317 |
+
shun sh un
|
| 318 |
+
shuo sh uo
|
| 319 |
+
si s i0
|
| 320 |
+
song s ong
|
| 321 |
+
sou s ou
|
| 322 |
+
su s u
|
| 323 |
+
suan s uan
|
| 324 |
+
sui s ui
|
| 325 |
+
sun s un
|
| 326 |
+
suo s uo
|
| 327 |
+
ta t a
|
| 328 |
+
tai t ai
|
| 329 |
+
tan t an
|
| 330 |
+
tang t ang
|
| 331 |
+
tao t ao
|
| 332 |
+
te t e
|
| 333 |
+
tei t ei
|
| 334 |
+
teng t eng
|
| 335 |
+
ti t i
|
| 336 |
+
tian t ian
|
| 337 |
+
tiao t iao
|
| 338 |
+
tie t ie
|
| 339 |
+
ting t ing
|
| 340 |
+
tong t ong
|
| 341 |
+
tou t ou
|
| 342 |
+
tu t u
|
| 343 |
+
tuan t uan
|
| 344 |
+
tui t ui
|
| 345 |
+
tun t un
|
| 346 |
+
tuo t uo
|
| 347 |
+
wa w a
|
| 348 |
+
wai w ai
|
| 349 |
+
wan w an
|
| 350 |
+
wang w ang
|
| 351 |
+
wei w ei
|
| 352 |
+
wen w en
|
| 353 |
+
weng w eng
|
| 354 |
+
wo w o
|
| 355 |
+
wu w u
|
| 356 |
+
xi x i
|
| 357 |
+
xia x ia
|
| 358 |
+
xian x ian
|
| 359 |
+
xiang x iang
|
| 360 |
+
xiao x iao
|
| 361 |
+
xie x ie
|
| 362 |
+
xin x in
|
| 363 |
+
xing x ing
|
| 364 |
+
xiong x iong
|
| 365 |
+
xiu x iu
|
| 366 |
+
xu x v
|
| 367 |
+
xv x v
|
| 368 |
+
xuan x van
|
| 369 |
+
xvan x van
|
| 370 |
+
xue x ve
|
| 371 |
+
xve x ve
|
| 372 |
+
xun x vn
|
| 373 |
+
xvn x vn
|
| 374 |
+
ya y a
|
| 375 |
+
yan y En
|
| 376 |
+
yang y ang
|
| 377 |
+
yao y ao
|
| 378 |
+
ye y E
|
| 379 |
+
yi y i
|
| 380 |
+
yin y in
|
| 381 |
+
ying y ing
|
| 382 |
+
yo y o
|
| 383 |
+
yong y ong
|
| 384 |
+
you y ou
|
| 385 |
+
yu y v
|
| 386 |
+
yv y v
|
| 387 |
+
yuan y van
|
| 388 |
+
yvan y van
|
| 389 |
+
yue y ve
|
| 390 |
+
yve y ve
|
| 391 |
+
yun y vn
|
| 392 |
+
yvn y vn
|
| 393 |
+
za z a
|
| 394 |
+
zai z ai
|
| 395 |
+
zan z an
|
| 396 |
+
zang z ang
|
| 397 |
+
zao z ao
|
| 398 |
+
ze z e
|
| 399 |
+
zei z ei
|
| 400 |
+
zen z en
|
| 401 |
+
zeng z eng
|
| 402 |
+
zha zh a
|
| 403 |
+
zhai zh ai
|
| 404 |
+
zhan zh an
|
| 405 |
+
zhang zh ang
|
| 406 |
+
zhao zh ao
|
| 407 |
+
zhe zh e
|
| 408 |
+
zhei zh ei
|
| 409 |
+
zhen zh en
|
| 410 |
+
zheng zh eng
|
| 411 |
+
zhi zh ir
|
| 412 |
+
zhong zh ong
|
| 413 |
+
zhou zh ou
|
| 414 |
+
zhu zh u
|
| 415 |
+
zhua zh ua
|
| 416 |
+
zhuai zh uai
|
| 417 |
+
zhuan zh uan
|
| 418 |
+
zhuang zh uang
|
| 419 |
+
zhui zh ui
|
| 420 |
+
zhun zh un
|
| 421 |
+
zhuo zh uo
|
| 422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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import jieba
|
| 16 |
+
from pypinyin import Style, lazy_pinyin
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ToneSandhi:
|
| 20 |
+
def __init__(self):
|
| 21 |
+
self.must_neural_tone_words = {
|
| 22 |
+
"麻烦",
|
| 23 |
+
"麻利",
|
| 24 |
+
"鸳鸯",
|
| 25 |
+
"高粱",
|
| 26 |
+
"骨头",
|
| 27 |
+
"骆驼",
|
| 28 |
+
"马虎",
|
| 29 |
+
"首饰",
|
| 30 |
+
"馒头",
|
| 31 |
+
"馄饨",
|
| 32 |
+
"风筝",
|
| 33 |
+
"难为",
|
| 34 |
+
"队伍",
|
| 35 |
+
"阔气",
|
| 36 |
+
"闺女",
|
| 37 |
+
"门道",
|
| 38 |
+
"锄头",
|
| 39 |
+
"铺盖",
|
| 40 |
+
"铃铛",
|
| 41 |
+
"铁匠",
|
| 42 |
+
"钥匙",
|
| 43 |
+
"里脊",
|
| 44 |
+
"里头",
|
| 45 |
+
"部分",
|
| 46 |
+
"那么",
|
| 47 |
+
"道士",
|
| 48 |
+
"造化",
|
| 49 |
+
"迷糊",
|
| 50 |
+
"连累",
|
| 51 |
+
"这么",
|
| 52 |
+
"这个",
|
| 53 |
+
"运气",
|
| 54 |
+
"过去",
|
| 55 |
+
"软和",
|
| 56 |
+
"转悠",
|
| 57 |
+
"踏实",
|
| 58 |
+
"跳蚤",
|
| 59 |
+
"跟头",
|
| 60 |
+
"趔趄",
|
| 61 |
+
"财主",
|
| 62 |
+
"豆腐",
|
| 63 |
+
"讲究",
|
| 64 |
+
"记性",
|
| 65 |
+
"记号",
|
| 66 |
+
"认识",
|
| 67 |
+
"规矩",
|
| 68 |
+
"见识",
|
| 69 |
+
"裁缝",
|
| 70 |
+
"补丁",
|
| 71 |
+
"衣裳",
|
| 72 |
+
"衣服",
|
| 73 |
+
"衙门",
|
| 74 |
+
"街坊",
|
| 75 |
+
"行李",
|
| 76 |
+
"行当",
|
| 77 |
+
"蛤蟆",
|
| 78 |
+
"蘑菇",
|
| 79 |
+
"薄荷",
|
| 80 |
+
"葫芦",
|
| 81 |
+
"葡萄",
|
| 82 |
+
"萝卜",
|
| 83 |
+
"荸荠",
|
| 84 |
+
"苗条",
|
| 85 |
+
"苗头",
|
| 86 |
+
"苍蝇",
|
| 87 |
+
"芝麻",
|
| 88 |
+
"舒服",
|
| 89 |
+
"舒坦",
|
| 90 |
+
"舌头",
|
| 91 |
+
"自在",
|
| 92 |
+
"膏药",
|
| 93 |
+
"脾气",
|
| 94 |
+
"脑袋",
|
| 95 |
+
"脊梁",
|
| 96 |
+
"能耐",
|
| 97 |
+
"胳膊",
|
| 98 |
+
"胭脂",
|
| 99 |
+
"胡萝",
|
| 100 |
+
"胡琴",
|
| 101 |
+
"胡同",
|
| 102 |
+
"聪明",
|
| 103 |
+
"耽误",
|
| 104 |
+
"耽搁",
|
| 105 |
+
"耷拉",
|
| 106 |
+
"耳朵",
|
| 107 |
+
"老爷",
|
| 108 |
+
"老实",
|
| 109 |
+
"老婆",
|
| 110 |
+
"老头",
|
| 111 |
+
"老太",
|
| 112 |
+
"翻腾",
|
| 113 |
+
"罗嗦",
|
| 114 |
+
"罐头",
|
| 115 |
+
"编辑",
|
| 116 |
+
"结实",
|
| 117 |
+
"红火",
|
| 118 |
+
"累赘",
|
| 119 |
+
"糨糊",
|
| 120 |
+
"糊涂",
|
| 121 |
+
"精神",
|
| 122 |
+
"粮食",
|
| 123 |
+
"簸箕",
|
| 124 |
+
"篱笆",
|
| 125 |
+
"算计",
|
| 126 |
+
"算盘",
|
| 127 |
+
"答应",
|
| 128 |
+
"笤帚",
|
| 129 |
+
"笑语",
|
| 130 |
+
"笑话",
|
| 131 |
+
"窟窿",
|
| 132 |
+
"窝囊",
|
| 133 |
+
"窗户",
|
| 134 |
+
"稳当",
|
| 135 |
+
"稀罕",
|
| 136 |
+
"称呼",
|
| 137 |
+
"秧歌",
|
| 138 |
+
"秀气",
|
| 139 |
+
"秀才",
|
| 140 |
+
"福气",
|
| 141 |
+
"祖宗",
|
| 142 |
+
"砚台",
|
| 143 |
+
"码头",
|
| 144 |
+
"石榴",
|
| 145 |
+
"石头",
|
| 146 |
+
"石匠",
|
| 147 |
+
"知识",
|
| 148 |
+
"眼睛",
|
| 149 |
+
"眯缝",
|
| 150 |
+
"眨巴",
|
| 151 |
+
"眉毛",
|
| 152 |
+
"相声",
|
| 153 |
+
"盘算",
|
| 154 |
+
"白净",
|
| 155 |
+
"痢疾",
|
| 156 |
+
"痛快",
|
| 157 |
+
"疟疾",
|
| 158 |
+
"疙瘩",
|
| 159 |
+
"疏忽",
|
| 160 |
+
"畜生",
|
| 161 |
+
"生意",
|
| 162 |
+
"甘蔗",
|
| 163 |
+
"琵琶",
|
| 164 |
+
"琢磨",
|
| 165 |
+
"琉璃",
|
| 166 |
+
"玻璃",
|
| 167 |
+
"玫瑰",
|
| 168 |
+
"玄乎",
|
| 169 |
+
"狐狸",
|
| 170 |
+
"状元",
|
| 171 |
+
"特务",
|
| 172 |
+
"牲口",
|
| 173 |
+
"牙碜",
|
| 174 |
+
"牌楼",
|
| 175 |
+
"爽快",
|
| 176 |
+
"爱人",
|
| 177 |
+
"热闹",
|
| 178 |
+
"烧饼",
|
| 179 |
+
"烟筒",
|
| 180 |
+
"烂糊",
|
| 181 |
+
"点心",
|
| 182 |
+
"炊帚",
|
| 183 |
+
"灯笼",
|
| 184 |
+
"火候",
|
| 185 |
+
"漂亮",
|
| 186 |
+
"滑溜",
|
| 187 |
+
"溜达",
|
| 188 |
+
"温和",
|
| 189 |
+
"清楚",
|
| 190 |
+
"消息",
|
| 191 |
+
"浪头",
|
| 192 |
+
"活泼",
|
| 193 |
+
"比方",
|
| 194 |
+
"正经",
|
| 195 |
+
"欺负",
|
| 196 |
+
"模糊",
|
| 197 |
+
"槟榔",
|
| 198 |
+
"棺材",
|
| 199 |
+
"棒槌",
|
| 200 |
+
"棉花",
|
| 201 |
+
"核桃",
|
| 202 |
+
"栅栏",
|
| 203 |
+
"柴火",
|
| 204 |
+
"架势",
|
| 205 |
+
"枕头",
|
| 206 |
+
"枇杷",
|
| 207 |
+
"机灵",
|
| 208 |
+
"本事",
|
| 209 |
+
"木头",
|
| 210 |
+
"木匠",
|
| 211 |
+
"朋友",
|
| 212 |
+
"月饼",
|
| 213 |
+
"月亮",
|
| 214 |
+
"暖和",
|
| 215 |
+
"明白",
|
| 216 |
+
"时候",
|
| 217 |
+
"新鲜",
|
| 218 |
+
"故事",
|
| 219 |
+
"收拾",
|
| 220 |
+
"收成",
|
| 221 |
+
"提防",
|
| 222 |
+
"挖苦",
|
| 223 |
+
"挑剔",
|
| 224 |
+
"指甲",
|
| 225 |
+
"指头",
|
| 226 |
+
"拾掇",
|
| 227 |
+
"拳头",
|
| 228 |
+
"拨弄",
|
| 229 |
+
"招牌",
|
| 230 |
+
"招呼",
|
| 231 |
+
"抬举",
|
| 232 |
+
"护士",
|
| 233 |
+
"折腾",
|
| 234 |
+
"扫帚",
|
| 235 |
+
"打量",
|
| 236 |
+
"打算",
|
| 237 |
+
"打点",
|
| 238 |
+
"打扮",
|
| 239 |
+
"打听",
|
| 240 |
+
"打发",
|
| 241 |
+
"扎实",
|
| 242 |
+
"扁担",
|
| 243 |
+
"戒指",
|
| 244 |
+
"懒得",
|
| 245 |
+
"意识",
|
| 246 |
+
"意思",
|
| 247 |
+
"情形",
|
| 248 |
+
"悟性",
|
| 249 |
+
"怪物",
|
| 250 |
+
"思量",
|
| 251 |
+
"怎么",
|
| 252 |
+
"念头",
|
| 253 |
+
"念叨",
|
| 254 |
+
"快活",
|
| 255 |
+
"忙活",
|
| 256 |
+
"志气",
|
| 257 |
+
"心思",
|
| 258 |
+
"得罪",
|
| 259 |
+
"张罗",
|
| 260 |
+
"弟兄",
|
| 261 |
+
"开通",
|
| 262 |
+
"应酬",
|
| 263 |
+
"庄稼",
|
| 264 |
+
"干事",
|
| 265 |
+
"帮手",
|
| 266 |
+
"帐篷",
|
| 267 |
+
"希罕",
|
| 268 |
+
"师父",
|
| 269 |
+
"师傅",
|
| 270 |
+
"巴结",
|
| 271 |
+
"巴掌",
|
| 272 |
+
"差事",
|
| 273 |
+
"工夫",
|
| 274 |
+
"岁数",
|
| 275 |
+
"屁股",
|
| 276 |
+
"尾巴",
|
| 277 |
+
"少爷",
|
| 278 |
+
"小气",
|
| 279 |
+
"小伙",
|
| 280 |
+
"将就",
|
| 281 |
+
"对头",
|
| 282 |
+
"对付",
|
| 283 |
+
"寡妇",
|
| 284 |
+
"家伙",
|
| 285 |
+
"客气",
|
| 286 |
+
"实在",
|
| 287 |
+
"官司",
|
| 288 |
+
"学问",
|
| 289 |
+
"学生",
|
| 290 |
+
"字号",
|
| 291 |
+
"嫁妆",
|
| 292 |
+
"媳妇",
|
| 293 |
+
"媒人",
|
| 294 |
+
"婆家",
|
| 295 |
+
"娘家",
|
| 296 |
+
"委屈",
|
| 297 |
+
"姑娘",
|
| 298 |
+
"姐夫",
|
| 299 |
+
"妯娌",
|
| 300 |
+
"妥当",
|
| 301 |
+
"妖精",
|
| 302 |
+
"奴才",
|
| 303 |
+
"女婿",
|
| 304 |
+
"头发",
|
| 305 |
+
"太阳",
|
| 306 |
+
"大爷",
|
| 307 |
+
"大方",
|
| 308 |
+
"大意",
|
| 309 |
+
"大夫",
|
| 310 |
+
"多少",
|
| 311 |
+
"多么",
|
| 312 |
+
"外甥",
|
| 313 |
+
"壮实",
|
| 314 |
+
"地道",
|
| 315 |
+
"地方",
|
| 316 |
+
"在乎",
|
| 317 |
+
"困难",
|
| 318 |
+
"嘴巴",
|
| 319 |
+
"嘱咐",
|
| 320 |
+
"嘟囔",
|
| 321 |
+
"嘀咕",
|
| 322 |
+
"喜欢",
|
| 323 |
+
"喇嘛",
|
| 324 |
+
"喇叭",
|
| 325 |
+
"商量",
|
| 326 |
+
"唾沫",
|
| 327 |
+
"哑巴",
|
| 328 |
+
"哈欠",
|
| 329 |
+
"哆嗦",
|
| 330 |
+
"咳嗽",
|
| 331 |
+
"和尚",
|
| 332 |
+
"告诉",
|
| 333 |
+
"告示",
|
| 334 |
+
"含糊",
|
| 335 |
+
"吓唬",
|
| 336 |
+
"后头",
|
| 337 |
+
"名字",
|
| 338 |
+
"名堂",
|
| 339 |
+
"合同",
|
| 340 |
+
"吆喝",
|
| 341 |
+
"叫唤",
|
| 342 |
+
"口袋",
|
| 343 |
+
"厚道",
|
| 344 |
+
"厉害",
|
| 345 |
+
"千斤",
|
| 346 |
+
"包袱",
|
| 347 |
+
"包涵",
|
| 348 |
+
"匀称",
|
| 349 |
+
"勤快",
|
| 350 |
+
"动静",
|
| 351 |
+
"动弹",
|
| 352 |
+
"功夫",
|
| 353 |
+
"力气",
|
| 354 |
+
"前头",
|
| 355 |
+
"刺猬",
|
| 356 |
+
"刺激",
|
| 357 |
+
"别扭",
|
| 358 |
+
"利落",
|
| 359 |
+
"利索",
|
| 360 |
+
"利害",
|
| 361 |
+
"分析",
|
| 362 |
+
"出息",
|
| 363 |
+
"凑合",
|
| 364 |
+
"凉快",
|
| 365 |
+
"冷战",
|
| 366 |
+
"冤枉",
|
| 367 |
+
"冒失",
|
| 368 |
+
"养活",
|
| 369 |
+
"关系",
|
| 370 |
+
"先生",
|
| 371 |
+
"兄弟",
|
| 372 |
+
"便宜",
|
| 373 |
+
"使唤",
|
| 374 |
+
"佩服",
|
| 375 |
+
"作坊",
|
| 376 |
+
"体面",
|
| 377 |
+
"位置",
|
| 378 |
+
"似的",
|
| 379 |
+
"伙计",
|
| 380 |
+
"休息",
|
| 381 |
+
"什么",
|
| 382 |
+
"人家",
|
| 383 |
+
"亲戚",
|
| 384 |
+
"亲家",
|
| 385 |
+
"交情",
|
| 386 |
+
"云彩",
|
| 387 |
+
"事情",
|
| 388 |
+
"买卖",
|
| 389 |
+
"主意",
|
| 390 |
+
"丫头",
|
| 391 |
+
"丧气",
|
| 392 |
+
"两口",
|
| 393 |
+
"东西",
|
| 394 |
+
"东家",
|
| 395 |
+
"世故",
|
| 396 |
+
"不由",
|
| 397 |
+
"不在",
|
| 398 |
+
"下水",
|
| 399 |
+
"下巴",
|
| 400 |
+
"上头",
|
| 401 |
+
"上司",
|
| 402 |
+
"丈夫",
|
| 403 |
+
"丈人",
|
| 404 |
+
"一辈",
|
| 405 |
+
"那个",
|
| 406 |
+
"菩萨",
|
| 407 |
+
"父亲",
|
| 408 |
+
"母亲",
|
| 409 |
+
"咕噜",
|
| 410 |
+
"邋遢",
|
| 411 |
+
"费用",
|
| 412 |
+
"冤家",
|
| 413 |
+
"甜头",
|
| 414 |
+
"介绍",
|
| 415 |
+
"荒唐",
|
| 416 |
+
"大人",
|
| 417 |
+
"泥鳅",
|
| 418 |
+
"幸福",
|
| 419 |
+
"熟悉",
|
| 420 |
+
"计划",
|
| 421 |
+
"扑腾",
|
| 422 |
+
"蜡烛",
|
| 423 |
+
"姥爷",
|
| 424 |
+
"照顾",
|
| 425 |
+
"喉咙",
|
| 426 |
+
"吉他",
|
| 427 |
+
"弄堂",
|
| 428 |
+
"蚂蚱",
|
| 429 |
+
"凤凰",
|
| 430 |
+
"拖沓",
|
| 431 |
+
"寒碜",
|
| 432 |
+
"糟蹋",
|
| 433 |
+
"倒腾",
|
| 434 |
+
"报复",
|
| 435 |
+
"逻辑",
|
| 436 |
+
"盘缠",
|
| 437 |
+
"喽啰",
|
| 438 |
+
"牢骚",
|
| 439 |
+
"咖喱",
|
| 440 |
+
"扫把",
|
| 441 |
+
"惦记",
|
| 442 |
+
}
|
| 443 |
+
self.must_not_neural_tone_words = {
|
| 444 |
+
"男子",
|
| 445 |
+
"女子",
|
| 446 |
+
"分子",
|
| 447 |
+
"原子",
|
| 448 |
+
"量子",
|
| 449 |
+
"莲子",
|
| 450 |
+
"石子",
|
| 451 |
+
"瓜子",
|
| 452 |
+
"电子",
|
| 453 |
+
"人人",
|
| 454 |
+
"虎虎",
|
| 455 |
+
}
|
| 456 |
+
self.punc = ":,;。?!“”‘’':,;.?!"
|
| 457 |
+
|
| 458 |
+
# the meaning of jieba pos tag: https://blog.csdn.net/weixin_44174352/article/details/113731041
|
| 459 |
+
# e.g.
|
| 460 |
+
# word: "家里"
|
| 461 |
+
# pos: "s"
|
| 462 |
+
# finals: ['ia1', 'i3']
|
| 463 |
+
def _neural_sandhi(self, word: str, pos: str, finals: list[str]) -> list[str]:
|
| 464 |
+
# reduplication words for n. and v. e.g. 奶奶, 试试, 旺旺
|
| 465 |
+
for j, item in enumerate(word):
|
| 466 |
+
if (
|
| 467 |
+
j - 1 >= 0
|
| 468 |
+
and item == word[j - 1]
|
| 469 |
+
and pos[0] in {"n", "v", "a"}
|
| 470 |
+
and word not in self.must_not_neural_tone_words
|
| 471 |
+
):
|
| 472 |
+
finals[j] = finals[j][:-1] + "5"
|
| 473 |
+
ge_idx = word.find("个")
|
| 474 |
+
if (
|
| 475 |
+
len(word) >= 1
|
| 476 |
+
and word[-1] in "吧呢啊呐噻嘛吖嗨呐哦哒额滴哩哟喽啰耶喔诶"
|
| 477 |
+
or len(word) >= 1
|
| 478 |
+
and word[-1] in "的地得"
|
| 479 |
+
or (
|
| 480 |
+
(
|
| 481 |
+
len(word) > 1
|
| 482 |
+
and word[-1] in "们子"
|
| 483 |
+
and pos in {"r", "n"}
|
| 484 |
+
and word not in self.must_not_neural_tone_words
|
| 485 |
+
)
|
| 486 |
+
or len(word) > 1
|
| 487 |
+
and word[-1] in "上下里"
|
| 488 |
+
and pos in {"s", "l", "f"}
|
| 489 |
+
)
|
| 490 |
+
or len(word) > 1
|
| 491 |
+
and word[-1] in "来去"
|
| 492 |
+
and word[-2] in "上下进出回过起开"
|
| 493 |
+
):
|
| 494 |
+
finals[-1] = finals[-1][:-1] + "5"
|
| 495 |
+
# 个做量词
|
| 496 |
+
elif (
|
| 497 |
+
ge_idx >= 1
|
| 498 |
+
and (
|
| 499 |
+
word[ge_idx - 1].isnumeric()
|
| 500 |
+
or word[ge_idx - 1] in "几有两半多各整每做是"
|
| 501 |
+
)
|
| 502 |
+
) or word == "个":
|
| 503 |
+
finals[ge_idx] = finals[ge_idx][:-1] + "5"
|
| 504 |
+
elif (
|
| 505 |
+
word in self.must_neural_tone_words
|
| 506 |
+
or word[-2:] in self.must_neural_tone_words
|
| 507 |
+
):
|
| 508 |
+
finals[-1] = finals[-1][:-1] + "5"
|
| 509 |
+
|
| 510 |
+
word_list = self._split_word(word)
|
| 511 |
+
finals_list = [finals[: len(word_list[0])], finals[len(word_list[0]) :]]
|
| 512 |
+
for i, word in enumerate(word_list):
|
| 513 |
+
# conventional neural in Chinese
|
| 514 |
+
if (
|
| 515 |
+
word in self.must_neural_tone_words
|
| 516 |
+
or word[-2:] in self.must_neural_tone_words
|
| 517 |
+
):
|
| 518 |
+
finals_list[i][-1] = finals_list[i][-1][:-1] + "5"
|
| 519 |
+
finals = sum(finals_list, [])
|
| 520 |
+
return finals
|
| 521 |
+
|
| 522 |
+
def _bu_sandhi(self, word: str, finals: list[str]) -> list[str]:
|
| 523 |
+
# e.g. 看不懂
|
| 524 |
+
if len(word) == 3 and word[1] == "不":
|
| 525 |
+
finals[1] = finals[1][:-1] + "5"
|
| 526 |
+
else:
|
| 527 |
+
for i, char in enumerate(word):
|
| 528 |
+
# "不" before tone4 should be bu2, e.g. 不怕
|
| 529 |
+
if char == "不" and i + 1 < len(word) and finals[i + 1][-1] == "4":
|
| 530 |
+
finals[i] = finals[i][:-1] + "2"
|
| 531 |
+
return finals
|
| 532 |
+
|
| 533 |
+
def _yi_sandhi(self, word: str, finals: list[str]) -> list[str]:
|
| 534 |
+
# "一" in number sequences, e.g. 一零零, 二一零
|
| 535 |
+
if word.find("一") != -1 and all(
|
| 536 |
+
[item.isnumeric() for item in word if item != "一"]
|
| 537 |
+
):
|
| 538 |
+
return finals
|
| 539 |
+
# "一" between reduplication words should be yi5, e.g. 看一看
|
| 540 |
+
elif len(word) == 3 and word[1] == "一" and word[0] == word[-1]:
|
| 541 |
+
finals[1] = finals[1][:-1] + "5"
|
| 542 |
+
# when "一" is ordinal word, it should be yi1
|
| 543 |
+
elif word.startswith("第一"):
|
| 544 |
+
finals[1] = finals[1][:-1] + "1"
|
| 545 |
+
else:
|
| 546 |
+
for i, char in enumerate(word):
|
| 547 |
+
if char == "一" and i + 1 < len(word):
|
| 548 |
+
# "一" before tone4 should be yi2, e.g. 一段
|
| 549 |
+
if finals[i + 1][-1] == "4":
|
| 550 |
+
finals[i] = finals[i][:-1] + "2"
|
| 551 |
+
# "一" before non-tone4 should be yi4, e.g. 一天
|
| 552 |
+
elif word[i + 1] not in self.punc:
|
| 553 |
+
finals[i] = finals[i][:-1] + "4"
|
| 554 |
+
return finals
|
| 555 |
+
|
| 556 |
+
def _split_word(self, word: str) -> list[str]:
|
| 557 |
+
word_list = jieba.cut_for_search(word)
|
| 558 |
+
word_list = sorted(word_list, key=lambda i: len(i), reverse=False) # type: ignore
|
| 559 |
+
first_subword = word_list[0]
|
| 560 |
+
first_begin_idx = word.find(first_subword)
|
| 561 |
+
if first_begin_idx == 0:
|
| 562 |
+
second_subword = word[len(first_subword) :]
|
| 563 |
+
new_word_list = [first_subword, second_subword]
|
| 564 |
+
else:
|
| 565 |
+
second_subword = word[: -len(first_subword)]
|
| 566 |
+
new_word_list = [second_subword, first_subword]
|
| 567 |
+
return new_word_list
|
| 568 |
+
|
| 569 |
+
def _three_sandhi(self, word: str, finals: list[str]) -> list[str]:
|
| 570 |
+
if len(word) == 2 and self._all_tone_three(finals):
|
| 571 |
+
finals[0] = finals[0][:-1] + "2"
|
| 572 |
+
elif len(word) == 3:
|
| 573 |
+
word_list = self._split_word(word)
|
| 574 |
+
if self._all_tone_three(finals):
|
| 575 |
+
# disyllabic + monosyllabic, e.g. 蒙古/包
|
| 576 |
+
if len(word_list[0]) == 2:
|
| 577 |
+
finals[0] = finals[0][:-1] + "2"
|
| 578 |
+
finals[1] = finals[1][:-1] + "2"
|
| 579 |
+
# monosyllabic + disyllabic, e.g. 纸/老虎
|
| 580 |
+
elif len(word_list[0]) == 1:
|
| 581 |
+
finals[1] = finals[1][:-1] + "2"
|
| 582 |
+
else:
|
| 583 |
+
finals_list = [finals[: len(word_list[0])], finals[len(word_list[0]) :]]
|
| 584 |
+
if len(finals_list) == 2:
|
| 585 |
+
for i, sub in enumerate(finals_list):
|
| 586 |
+
# e.g. 所有/人
|
| 587 |
+
if self._all_tone_three(sub) and len(sub) == 2:
|
| 588 |
+
finals_list[i][0] = finals_list[i][0][:-1] + "2"
|
| 589 |
+
# e.g. 好/喜欢
|
| 590 |
+
elif (
|
| 591 |
+
i == 1
|
| 592 |
+
and not self._all_tone_three(sub)
|
| 593 |
+
and finals_list[i][0][-1] == "3"
|
| 594 |
+
and finals_list[0][-1][-1] == "3"
|
| 595 |
+
):
|
| 596 |
+
finals_list[0][-1] = finals_list[0][-1][:-1] + "2"
|
| 597 |
+
finals = sum(finals_list, [])
|
| 598 |
+
# split idiom into two words who's length is 2
|
| 599 |
+
elif len(word) == 4:
|
| 600 |
+
finals_list = [finals[:2], finals[2:]]
|
| 601 |
+
finals = []
|
| 602 |
+
for sub in finals_list:
|
| 603 |
+
if self._all_tone_three(sub):
|
| 604 |
+
sub[0] = sub[0][:-1] + "2"
|
| 605 |
+
finals += sub
|
| 606 |
+
|
| 607 |
+
return finals
|
| 608 |
+
|
| 609 |
+
def _all_tone_three(self, finals: list[str]) -> bool:
|
| 610 |
+
return all(x[-1] == "3" for x in finals)
|
| 611 |
+
|
| 612 |
+
# merge "不" and the word behind it
|
| 613 |
+
# if don't merge, "不" sometimes appears alone according to jieba, which may occur sandhi error
|
| 614 |
+
def _merge_bu(self, seg: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
| 615 |
+
new_seg = []
|
| 616 |
+
last_word = ""
|
| 617 |
+
for word, pos in seg:
|
| 618 |
+
if last_word == "不":
|
| 619 |
+
word = last_word + word
|
| 620 |
+
if word != "不":
|
| 621 |
+
new_seg.append((word, pos))
|
| 622 |
+
last_word = word[:]
|
| 623 |
+
if last_word == "不":
|
| 624 |
+
new_seg.append((last_word, "d"))
|
| 625 |
+
last_word = ""
|
| 626 |
+
return new_seg
|
| 627 |
+
|
| 628 |
+
# function 1: merge "一" and reduplication words in it's left and right, e.g. "听","一","听" ->"听一听"
|
| 629 |
+
# function 2: merge single "一" and the word behind it
|
| 630 |
+
# if don't merge, "一" sometimes appears alone according to jieba, which may occur sandhi error
|
| 631 |
+
# e.g.
|
| 632 |
+
# input seg: [('听', 'v'), ('一', 'm'), ('听', 'v')]
|
| 633 |
+
# output seg: [['听一听', 'v']]
|
| 634 |
+
def _merge_yi(self, seg: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
| 635 |
+
new_seg = [] * len(seg)
|
| 636 |
+
# function 1
|
| 637 |
+
i = 0
|
| 638 |
+
while i < len(seg):
|
| 639 |
+
word, pos = seg[i]
|
| 640 |
+
if (
|
| 641 |
+
i - 1 >= 0
|
| 642 |
+
and word == "一"
|
| 643 |
+
and i + 1 < len(seg)
|
| 644 |
+
and seg[i - 1][0] == seg[i + 1][0]
|
| 645 |
+
and seg[i - 1][1] == "v"
|
| 646 |
+
):
|
| 647 |
+
new_seg[i - 1][0] = new_seg[i - 1][0] + "一" + new_seg[i - 1][0]
|
| 648 |
+
i += 2
|
| 649 |
+
else:
|
| 650 |
+
if (
|
| 651 |
+
i - 2 >= 0
|
| 652 |
+
and seg[i - 1][0] == "一"
|
| 653 |
+
and seg[i - 2][0] == word
|
| 654 |
+
and pos == "v"
|
| 655 |
+
):
|
| 656 |
+
continue
|
| 657 |
+
else:
|
| 658 |
+
new_seg.append([word, pos])
|
| 659 |
+
i += 1
|
| 660 |
+
seg = [i for i in new_seg if len(i) > 0]
|
| 661 |
+
new_seg = []
|
| 662 |
+
# function 2
|
| 663 |
+
for i, (word, pos) in enumerate(seg):
|
| 664 |
+
if new_seg and new_seg[-1][0] == "一":
|
| 665 |
+
new_seg[-1][0] = new_seg[-1][0] + word
|
| 666 |
+
else:
|
| 667 |
+
new_seg.append([word, pos])
|
| 668 |
+
return new_seg
|
| 669 |
+
|
| 670 |
+
# the first and the second words are all_tone_three
|
| 671 |
+
def _merge_continuous_three_tones(
|
| 672 |
+
self, seg: list[tuple[str, str]]
|
| 673 |
+
) -> list[tuple[str, str]]:
|
| 674 |
+
new_seg = []
|
| 675 |
+
sub_finals_list = [
|
| 676 |
+
lazy_pinyin(word, neutral_tone_with_five=True, style=Style.FINALS_TONE3)
|
| 677 |
+
for (word, pos) in seg
|
| 678 |
+
]
|
| 679 |
+
assert len(sub_finals_list) == len(seg)
|
| 680 |
+
merge_last = [False] * len(seg)
|
| 681 |
+
for i, (word, pos) in enumerate(seg):
|
| 682 |
+
if (
|
| 683 |
+
i - 1 >= 0
|
| 684 |
+
and self._all_tone_three(sub_finals_list[i - 1])
|
| 685 |
+
and self._all_tone_three(sub_finals_list[i])
|
| 686 |
+
and not merge_last[i - 1]
|
| 687 |
+
):
|
| 688 |
+
# if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi
|
| 689 |
+
if (
|
| 690 |
+
not self._is_reduplication(seg[i - 1][0])
|
| 691 |
+
and len(seg[i - 1][0]) + len(seg[i][0]) <= 3
|
| 692 |
+
):
|
| 693 |
+
new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
|
| 694 |
+
merge_last[i] = True
|
| 695 |
+
else:
|
| 696 |
+
new_seg.append([word, pos])
|
| 697 |
+
else:
|
| 698 |
+
new_seg.append([word, pos])
|
| 699 |
+
|
| 700 |
+
return new_seg
|
| 701 |
+
|
| 702 |
+
def _is_reduplication(self, word: str) -> bool:
|
| 703 |
+
return len(word) == 2 and word[0] == word[1]
|
| 704 |
+
|
| 705 |
+
# the last char of first word and the first char of second word is tone_three
|
| 706 |
+
def _merge_continuous_three_tones_2(
|
| 707 |
+
self, seg: list[tuple[str, str]]
|
| 708 |
+
) -> list[tuple[str, str]]:
|
| 709 |
+
new_seg = []
|
| 710 |
+
sub_finals_list = [
|
| 711 |
+
lazy_pinyin(word, neutral_tone_with_five=True, style=Style.FINALS_TONE3)
|
| 712 |
+
for (word, pos) in seg
|
| 713 |
+
]
|
| 714 |
+
assert len(sub_finals_list) == len(seg)
|
| 715 |
+
merge_last = [False] * len(seg)
|
| 716 |
+
for i, (word, pos) in enumerate(seg):
|
| 717 |
+
if (
|
| 718 |
+
i - 1 >= 0
|
| 719 |
+
and sub_finals_list[i - 1][-1][-1] == "3"
|
| 720 |
+
and sub_finals_list[i][0][-1] == "3"
|
| 721 |
+
and not merge_last[i - 1]
|
| 722 |
+
):
|
| 723 |
+
# if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi
|
| 724 |
+
if (
|
| 725 |
+
not self._is_reduplication(seg[i - 1][0])
|
| 726 |
+
and len(seg[i - 1][0]) + len(seg[i][0]) <= 3
|
| 727 |
+
):
|
| 728 |
+
new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
|
| 729 |
+
merge_last[i] = True
|
| 730 |
+
else:
|
| 731 |
+
new_seg.append([word, pos])
|
| 732 |
+
else:
|
| 733 |
+
new_seg.append([word, pos])
|
| 734 |
+
return new_seg
|
| 735 |
+
|
| 736 |
+
def _merge_er(self, seg: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
| 737 |
+
new_seg = []
|
| 738 |
+
for i, (word, pos) in enumerate(seg):
|
| 739 |
+
if i - 1 >= 0 and word == "儿" and seg[i - 1][0] != "#":
|
| 740 |
+
new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
|
| 741 |
+
else:
|
| 742 |
+
new_seg.append([word, pos])
|
| 743 |
+
return new_seg
|
| 744 |
+
|
| 745 |
+
def _merge_reduplication(self, seg: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
| 746 |
+
new_seg = []
|
| 747 |
+
for i, (word, pos) in enumerate(seg):
|
| 748 |
+
if new_seg and word == new_seg[-1][0]:
|
| 749 |
+
new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
|
| 750 |
+
else:
|
| 751 |
+
new_seg.append([word, pos])
|
| 752 |
+
return new_seg
|
| 753 |
+
|
| 754 |
+
def pre_merge_for_modify(self, seg: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
| 755 |
+
seg = self._merge_bu(seg)
|
| 756 |
+
try:
|
| 757 |
+
seg = self._merge_yi(seg)
|
| 758 |
+
except:
|
| 759 |
+
print("_merge_yi failed")
|
| 760 |
+
seg = self._merge_reduplication(seg)
|
| 761 |
+
seg = self._merge_continuous_three_tones(seg)
|
| 762 |
+
seg = self._merge_continuous_three_tones_2(seg)
|
| 763 |
+
seg = self._merge_er(seg)
|
| 764 |
+
return seg
|
| 765 |
+
|
| 766 |
+
def modified_tone(self, word: str, pos: str, finals: list[str]) -> list[str]:
|
| 767 |
+
finals = self._bu_sandhi(word, finals)
|
| 768 |
+
finals = self._yi_sandhi(word, finals)
|
| 769 |
+
finals = self._neural_sandhi(word, pos, finals)
|
| 770 |
+
finals = self._three_sandhi(word, finals)
|
| 771 |
+
return finals
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/__init__.py
ADDED
|
File without changes
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/bert_feature.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from style_bert_vits2.constants import Languages
|
| 6 |
+
from style_bert_vits2.nlp import bert_models
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def extract_bert_feature(
|
| 10 |
+
text: str,
|
| 11 |
+
word2ph: list[int],
|
| 12 |
+
device: str,
|
| 13 |
+
assist_text: Optional[str] = None,
|
| 14 |
+
assist_text_weight: float = 0.7,
|
| 15 |
+
) -> torch.Tensor:
|
| 16 |
+
"""
|
| 17 |
+
英語のテキストから BERT の特徴量を抽出する
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
text (str): 英語のテキスト
|
| 21 |
+
word2ph (list[int]): 元のテキストの各文字に音素が何個割り当てられるかを表すリスト
|
| 22 |
+
device (str): 推論に利用するデバイス
|
| 23 |
+
assist_text (Optional[str], optional): 補助テキスト (デフォルト: None)
|
| 24 |
+
assist_text_weight (float, optional): 補助テキストの重み (デフォルト: 0.7)
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
torch.Tensor: BERT の特徴量
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
if device == "cuda" and not torch.cuda.is_available():
|
| 31 |
+
device = "cpu"
|
| 32 |
+
model = bert_models.load_model(Languages.EN).to(device) # type: ignore
|
| 33 |
+
|
| 34 |
+
style_res_mean = None
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
tokenizer = bert_models.load_tokenizer(Languages.EN)
|
| 37 |
+
inputs = tokenizer(text, return_tensors="pt")
|
| 38 |
+
for i in inputs:
|
| 39 |
+
inputs[i] = inputs[i].to(device) # type: ignore
|
| 40 |
+
res = model(**inputs, output_hidden_states=True)
|
| 41 |
+
res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()
|
| 42 |
+
if assist_text:
|
| 43 |
+
style_inputs = tokenizer(assist_text, return_tensors="pt")
|
| 44 |
+
for i in style_inputs:
|
| 45 |
+
style_inputs[i] = style_inputs[i].to(device) # type: ignore
|
| 46 |
+
style_res = model(**style_inputs, output_hidden_states=True)
|
| 47 |
+
style_res = torch.cat(style_res["hidden_states"][-3:-2], -1)[0].cpu()
|
| 48 |
+
style_res_mean = style_res.mean(0)
|
| 49 |
+
|
| 50 |
+
assert len(word2ph) == res.shape[0], (text, res.shape[0], len(word2ph))
|
| 51 |
+
word2phone = word2ph
|
| 52 |
+
phone_level_feature = []
|
| 53 |
+
for i in range(len(word2phone)):
|
| 54 |
+
if assist_text:
|
| 55 |
+
assert style_res_mean is not None
|
| 56 |
+
repeat_feature = (
|
| 57 |
+
res[i].repeat(word2phone[i], 1) * (1 - assist_text_weight)
|
| 58 |
+
+ style_res_mean.repeat(word2phone[i], 1) * assist_text_weight
|
| 59 |
+
)
|
| 60 |
+
else:
|
| 61 |
+
repeat_feature = res[i].repeat(word2phone[i], 1)
|
| 62 |
+
phone_level_feature.append(repeat_feature)
|
| 63 |
+
|
| 64 |
+
phone_level_feature = torch.cat(phone_level_feature, dim=0)
|
| 65 |
+
|
| 66 |
+
return phone_level_feature.T
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/cmudict.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
CMU_DICT_PATH = Path(__file__).parent / "cmudict.rep"
|
| 6 |
+
CACHE_PATH = Path(__file__).parent / "cmudict_cache.pickle"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_dict() -> dict[str, list[list[str]]]:
|
| 10 |
+
if CACHE_PATH.exists():
|
| 11 |
+
with open(CACHE_PATH, "rb") as pickle_file:
|
| 12 |
+
g2p_dict = pickle.load(pickle_file)
|
| 13 |
+
else:
|
| 14 |
+
g2p_dict = read_dict()
|
| 15 |
+
cache_dict(g2p_dict, CACHE_PATH)
|
| 16 |
+
|
| 17 |
+
return g2p_dict
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def read_dict() -> dict[str, list[list[str]]]:
|
| 21 |
+
g2p_dict = {}
|
| 22 |
+
start_line = 49
|
| 23 |
+
with open(CMU_DICT_PATH, encoding="utf-8") as f:
|
| 24 |
+
line = f.readline()
|
| 25 |
+
line_index = 1
|
| 26 |
+
while line:
|
| 27 |
+
if line_index >= start_line:
|
| 28 |
+
line = line.strip()
|
| 29 |
+
word_split = line.split(" ")
|
| 30 |
+
word = word_split[0]
|
| 31 |
+
|
| 32 |
+
syllable_split = word_split[1].split(" - ")
|
| 33 |
+
g2p_dict[word] = []
|
| 34 |
+
for syllable in syllable_split:
|
| 35 |
+
phone_split = syllable.split(" ")
|
| 36 |
+
g2p_dict[word].append(phone_split)
|
| 37 |
+
|
| 38 |
+
line_index = line_index + 1
|
| 39 |
+
line = f.readline()
|
| 40 |
+
|
| 41 |
+
return g2p_dict
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def cache_dict(g2p_dict: dict[str, list[list[str]]], file_path: Path) -> None:
|
| 45 |
+
with open(file_path, "wb") as pickle_file:
|
| 46 |
+
pickle.dump(g2p_dict, pickle_file)
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/cmudict.rep
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/cmudict_cache.pickle
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
from g2p_en import G2p
|
| 4 |
+
|
| 5 |
+
from style_bert_vits2.constants import Languages
|
| 6 |
+
from style_bert_vits2.nlp import bert_models
|
| 7 |
+
from style_bert_vits2.nlp.english.cmudict import get_dict
|
| 8 |
+
from style_bert_vits2.nlp.symbols import PUNCTUATIONS, SYMBOLS
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Initialize global variables once
|
| 12 |
+
ARPA = {
|
| 13 |
+
"AH0",
|
| 14 |
+
"S",
|
| 15 |
+
"AH1",
|
| 16 |
+
"EY2",
|
| 17 |
+
"AE2",
|
| 18 |
+
"EH0",
|
| 19 |
+
"OW2",
|
| 20 |
+
"UH0",
|
| 21 |
+
"NG",
|
| 22 |
+
"B",
|
| 23 |
+
"G",
|
| 24 |
+
"AY0",
|
| 25 |
+
"M",
|
| 26 |
+
"AA0",
|
| 27 |
+
"F",
|
| 28 |
+
"AO0",
|
| 29 |
+
"ER2",
|
| 30 |
+
"UH1",
|
| 31 |
+
"IY1",
|
| 32 |
+
"AH2",
|
| 33 |
+
"DH",
|
| 34 |
+
"IY0",
|
| 35 |
+
"EY1",
|
| 36 |
+
"IH0",
|
| 37 |
+
"K",
|
| 38 |
+
"N",
|
| 39 |
+
"W",
|
| 40 |
+
"IY2",
|
| 41 |
+
"T",
|
| 42 |
+
"AA1",
|
| 43 |
+
"ER1",
|
| 44 |
+
"EH2",
|
| 45 |
+
"OY0",
|
| 46 |
+
"UH2",
|
| 47 |
+
"UW1",
|
| 48 |
+
"Z",
|
| 49 |
+
"AW2",
|
| 50 |
+
"AW1",
|
| 51 |
+
"V",
|
| 52 |
+
"UW2",
|
| 53 |
+
"AA2",
|
| 54 |
+
"ER",
|
| 55 |
+
"AW0",
|
| 56 |
+
"UW0",
|
| 57 |
+
"R",
|
| 58 |
+
"OW1",
|
| 59 |
+
"EH1",
|
| 60 |
+
"ZH",
|
| 61 |
+
"AE0",
|
| 62 |
+
"IH2",
|
| 63 |
+
"IH",
|
| 64 |
+
"Y",
|
| 65 |
+
"JH",
|
| 66 |
+
"P",
|
| 67 |
+
"AY1",
|
| 68 |
+
"EY0",
|
| 69 |
+
"OY2",
|
| 70 |
+
"TH",
|
| 71 |
+
"HH",
|
| 72 |
+
"D",
|
| 73 |
+
"ER0",
|
| 74 |
+
"CH",
|
| 75 |
+
"AO1",
|
| 76 |
+
"AE1",
|
| 77 |
+
"AO2",
|
| 78 |
+
"OY1",
|
| 79 |
+
"AY2",
|
| 80 |
+
"IH1",
|
| 81 |
+
"OW0",
|
| 82 |
+
"L",
|
| 83 |
+
"SH",
|
| 84 |
+
}
|
| 85 |
+
_g2p = G2p()
|
| 86 |
+
eng_dict = get_dict()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def g2p(text: str) -> tuple[list[str], list[int], list[int]]:
|
| 90 |
+
phones = []
|
| 91 |
+
tones = []
|
| 92 |
+
phone_len = []
|
| 93 |
+
words = __text_to_words(text)
|
| 94 |
+
|
| 95 |
+
for word in words:
|
| 96 |
+
temp_phones, temp_tones = [], []
|
| 97 |
+
if len(word) > 1 and "'" in word:
|
| 98 |
+
word = ["".join(word)]
|
| 99 |
+
|
| 100 |
+
for w in word:
|
| 101 |
+
if w in PUNCTUATIONS:
|
| 102 |
+
temp_phones.append(w)
|
| 103 |
+
temp_tones.append(0)
|
| 104 |
+
continue
|
| 105 |
+
if w.upper() in eng_dict:
|
| 106 |
+
phns, tns = __refine_syllables(eng_dict[w.upper()])
|
| 107 |
+
temp_phones += [__post_replace_ph(i) for i in phns]
|
| 108 |
+
temp_tones += tns
|
| 109 |
+
else:
|
| 110 |
+
phone_list = list(filter(lambda p: p != " ", _g2p(w)))
|
| 111 |
+
phns, tns = [], []
|
| 112 |
+
for ph in phone_list:
|
| 113 |
+
if ph in ARPA:
|
| 114 |
+
ph, tn = __refine_ph(ph)
|
| 115 |
+
phns.append(ph)
|
| 116 |
+
tns.append(tn)
|
| 117 |
+
else:
|
| 118 |
+
phns.append(ph)
|
| 119 |
+
tns.append(0)
|
| 120 |
+
temp_phones += [__post_replace_ph(i) for i in phns]
|
| 121 |
+
temp_tones += tns
|
| 122 |
+
|
| 123 |
+
phones += temp_phones
|
| 124 |
+
tones += temp_tones
|
| 125 |
+
phone_len.append(len(temp_phones))
|
| 126 |
+
|
| 127 |
+
word2ph = []
|
| 128 |
+
for token, pl in zip(words, phone_len):
|
| 129 |
+
word_len = len(token)
|
| 130 |
+
word2ph += __distribute_phone(pl, word_len)
|
| 131 |
+
|
| 132 |
+
phones = ["_"] + phones + ["_"]
|
| 133 |
+
tones = [0] + tones + [0]
|
| 134 |
+
word2ph = [1] + word2ph + [1]
|
| 135 |
+
assert len(phones) == len(tones), text
|
| 136 |
+
assert len(phones) == sum(word2ph), text
|
| 137 |
+
|
| 138 |
+
return phones, tones, word2ph
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def __post_replace_ph(ph: str) -> str:
|
| 142 |
+
REPLACE_MAP = {
|
| 143 |
+
":": ",",
|
| 144 |
+
";": ",",
|
| 145 |
+
",": ",",
|
| 146 |
+
"。": ".",
|
| 147 |
+
"!": "!",
|
| 148 |
+
"?": "?",
|
| 149 |
+
"\n": ".",
|
| 150 |
+
"·": ",",
|
| 151 |
+
"、": ",",
|
| 152 |
+
"…": "...",
|
| 153 |
+
"···": "...",
|
| 154 |
+
"・・・": "...",
|
| 155 |
+
"v": "V",
|
| 156 |
+
}
|
| 157 |
+
if ph in REPLACE_MAP:
|
| 158 |
+
ph = REPLACE_MAP[ph]
|
| 159 |
+
if ph in SYMBOLS:
|
| 160 |
+
return ph
|
| 161 |
+
return "UNK"
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def __refine_ph(phn: str) -> tuple[str, int]:
|
| 165 |
+
tone = 0
|
| 166 |
+
if re.search(r"\d$", phn):
|
| 167 |
+
tone = int(phn[-1]) + 1
|
| 168 |
+
phn = phn[:-1]
|
| 169 |
+
else:
|
| 170 |
+
tone = 3
|
| 171 |
+
return phn.lower(), tone
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def __refine_syllables(syllables: list[list[str]]) -> tuple[list[str], list[int]]:
|
| 175 |
+
tones = []
|
| 176 |
+
phonemes = []
|
| 177 |
+
for phn_list in syllables:
|
| 178 |
+
for phn in phn_list:
|
| 179 |
+
phn, tone = __refine_ph(phn)
|
| 180 |
+
phonemes.append(phn)
|
| 181 |
+
tones.append(tone)
|
| 182 |
+
return phonemes, tones
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def __distribute_phone(n_phone: int, n_word: int) -> list[int]:
|
| 186 |
+
phones_per_word = [0] * n_word
|
| 187 |
+
for task in range(n_phone):
|
| 188 |
+
min_tasks = min(phones_per_word)
|
| 189 |
+
min_index = phones_per_word.index(min_tasks)
|
| 190 |
+
phones_per_word[min_index] += 1
|
| 191 |
+
return phones_per_word
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def __text_to_words(text: str) -> list[list[str]]:
|
| 195 |
+
tokenizer = bert_models.load_tokenizer(Languages.EN)
|
| 196 |
+
tokens = tokenizer.tokenize(text)
|
| 197 |
+
words = []
|
| 198 |
+
for idx, t in enumerate(tokens):
|
| 199 |
+
if t.startswith("▁"):
|
| 200 |
+
words.append([t[1:]])
|
| 201 |
+
elif t in PUNCTUATIONS:
|
| 202 |
+
if idx == len(tokens) - 1:
|
| 203 |
+
words.append([f"{t}"])
|
| 204 |
+
elif (
|
| 205 |
+
not tokens[idx + 1].startswith("▁")
|
| 206 |
+
and tokens[idx + 1] not in PUNCTUATIONS
|
| 207 |
+
):
|
| 208 |
+
if idx == 0:
|
| 209 |
+
words.append([])
|
| 210 |
+
words[-1].append(f"{t}")
|
| 211 |
+
else:
|
| 212 |
+
words.append([f"{t}"])
|
| 213 |
+
else:
|
| 214 |
+
if idx == 0:
|
| 215 |
+
words.append([])
|
| 216 |
+
words[-1].append(f"{t}")
|
| 217 |
+
return words
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
if __name__ == "__main__":
|
| 221 |
+
# print(get_dict())
|
| 222 |
+
# print(eng_word_to_phoneme("hello"))
|
| 223 |
+
print(g2p("In this paper, we propose 1 DSPGAN, a GAN-based universal vocoder."))
|
| 224 |
+
# all_phones = set()
|
| 225 |
+
# eng_dict = get_dict()
|
| 226 |
+
# for k, syllables in eng_dict.items():
|
| 227 |
+
# for group in syllables:
|
| 228 |
+
# for ph in group:
|
| 229 |
+
# all_phones.add(ph)
|
| 230 |
+
# print(all_phones)
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/english/normalizer.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import inflect
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
__INFLECT = inflect.engine()
|
| 7 |
+
__COMMA_NUMBER_PATTERN = re.compile(r"([0-9][0-9\,]+[0-9])")
|
| 8 |
+
__DECIMAL_NUMBER_PATTERN = re.compile(r"([0-9]+\.[0-9]+)")
|
| 9 |
+
__POUNDS_PATTERN = re.compile(r"£([0-9\,]*[0-9]+)")
|
| 10 |
+
__DOLLARS_PATTERN = re.compile(r"\$([0-9\.\,]*[0-9]+)")
|
| 11 |
+
__ORDINAL_PATTERN = re.compile(r"[0-9]+(st|nd|rd|th)")
|
| 12 |
+
__NUMBER_PATTERN = re.compile(r"[0-9]+")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def normalize_text(text: str) -> str:
|
| 16 |
+
text = __normalize_numbers(text)
|
| 17 |
+
text = replace_punctuation(text)
|
| 18 |
+
text = re.sub(r"([,;.\?\!])([\w])", r"\1 \2", text)
|
| 19 |
+
return text
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def replace_punctuation(text: str) -> str:
|
| 23 |
+
REPLACE_MAP = {
|
| 24 |
+
":": ",",
|
| 25 |
+
";": ",",
|
| 26 |
+
",": ",",
|
| 27 |
+
"。": ".",
|
| 28 |
+
"!": "!",
|
| 29 |
+
"?": "?",
|
| 30 |
+
"\n": ".",
|
| 31 |
+
".": ".",
|
| 32 |
+
"…": "...",
|
| 33 |
+
"···": "...",
|
| 34 |
+
"・・・": "...",
|
| 35 |
+
"·": ",",
|
| 36 |
+
"・": ",",
|
| 37 |
+
"、": ",",
|
| 38 |
+
"$": ".",
|
| 39 |
+
"“": "'",
|
| 40 |
+
"”": "'",
|
| 41 |
+
'"': "'",
|
| 42 |
+
"‘": "'",
|
| 43 |
+
"’": "'",
|
| 44 |
+
"(": "'",
|
| 45 |
+
")": "'",
|
| 46 |
+
"(": "'",
|
| 47 |
+
")": "'",
|
| 48 |
+
"《": "'",
|
| 49 |
+
"》": "'",
|
| 50 |
+
"【": "'",
|
| 51 |
+
"】": "'",
|
| 52 |
+
"[": "'",
|
| 53 |
+
"]": "'",
|
| 54 |
+
"—": "-",
|
| 55 |
+
"−": "-",
|
| 56 |
+
"~": "-",
|
| 57 |
+
"~": "-",
|
| 58 |
+
"「": "'",
|
| 59 |
+
"」": "'",
|
| 60 |
+
}
|
| 61 |
+
pattern = re.compile("|".join(re.escape(p) for p in REPLACE_MAP))
|
| 62 |
+
replaced_text = pattern.sub(lambda x: REPLACE_MAP[x.group()], text)
|
| 63 |
+
# replaced_text = re.sub(
|
| 64 |
+
# r"[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u3400-\u4DBF\u3005"
|
| 65 |
+
# + "".join(punctuation)
|
| 66 |
+
# + r"]+",
|
| 67 |
+
# "",
|
| 68 |
+
# replaced_text,
|
| 69 |
+
# )
|
| 70 |
+
return replaced_text
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def __normalize_numbers(text: str) -> str:
|
| 74 |
+
text = re.sub(__COMMA_NUMBER_PATTERN, __remove_commas, text)
|
| 75 |
+
text = re.sub(__POUNDS_PATTERN, r"\1 pounds", text)
|
| 76 |
+
text = re.sub(__DOLLARS_PATTERN, __expand_dollars, text)
|
| 77 |
+
text = re.sub(__DECIMAL_NUMBER_PATTERN, __expand_decimal_point, text)
|
| 78 |
+
text = re.sub(__ORDINAL_PATTERN, __expand_ordinal, text)
|
| 79 |
+
text = re.sub(__NUMBER_PATTERN, __expand_number, text)
|
| 80 |
+
return text
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def __expand_dollars(m: re.Match[str]) -> str:
|
| 84 |
+
match = m.group(1)
|
| 85 |
+
parts = match.split(".")
|
| 86 |
+
if len(parts) > 2:
|
| 87 |
+
return match + " dollars" # Unexpected format
|
| 88 |
+
dollars = int(parts[0]) if parts[0] else 0
|
| 89 |
+
cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
|
| 90 |
+
if dollars and cents:
|
| 91 |
+
dollar_unit = "dollar" if dollars == 1 else "dollars"
|
| 92 |
+
cent_unit = "cent" if cents == 1 else "cents"
|
| 93 |
+
return "%s %s, %s %s" % (dollars, dollar_unit, cents, cent_unit)
|
| 94 |
+
elif dollars:
|
| 95 |
+
dollar_unit = "dollar" if dollars == 1 else "dollars"
|
| 96 |
+
return "%s %s" % (dollars, dollar_unit)
|
| 97 |
+
elif cents:
|
| 98 |
+
cent_unit = "cent" if cents == 1 else "cents"
|
| 99 |
+
return "%s %s" % (cents, cent_unit)
|
| 100 |
+
else:
|
| 101 |
+
return "zero dollars"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def __remove_commas(m: re.Match[str]) -> str:
|
| 105 |
+
return m.group(1).replace(",", "")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def __expand_ordinal(m: re.Match[str]) -> str:
|
| 109 |
+
return __INFLECT.number_to_words(m.group(0)) # type: ignore
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def __expand_number(m: re.Match[str]) -> str:
|
| 113 |
+
num = int(m.group(0))
|
| 114 |
+
if num > 1000 and num < 3000:
|
| 115 |
+
if num == 2000:
|
| 116 |
+
return "two thousand"
|
| 117 |
+
elif num > 2000 and num < 2010:
|
| 118 |
+
return "two thousand " + __INFLECT.number_to_words(num % 100) # type: ignore
|
| 119 |
+
elif num % 100 == 0:
|
| 120 |
+
return __INFLECT.number_to_words(num // 100) + " hundred" # type: ignore
|
| 121 |
+
else:
|
| 122 |
+
return __INFLECT.number_to_words(
|
| 123 |
+
num, andword="", zero="oh", group=2 # type: ignore
|
| 124 |
+
).replace(
|
| 125 |
+
", ", " "
|
| 126 |
+
) # type: ignore
|
| 127 |
+
else:
|
| 128 |
+
return __INFLECT.number_to_words(num, andword="") # type: ignore
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def __expand_decimal_point(m: re.Match[str]) -> str:
|
| 132 |
+
return m.group(1).replace(".", " point ")
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/__init__.py
ADDED
|
File without changes
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/bert_feature.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from style_bert_vits2.constants import Languages
|
| 6 |
+
from style_bert_vits2.nlp import bert_models
|
| 7 |
+
from style_bert_vits2.nlp.japanese.g2p import text_to_sep_kata
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def extract_bert_feature(
|
| 11 |
+
text: str,
|
| 12 |
+
word2ph: list[int],
|
| 13 |
+
device: str,
|
| 14 |
+
assist_text: Optional[str] = None,
|
| 15 |
+
assist_text_weight: float = 0.7,
|
| 16 |
+
) -> torch.Tensor:
|
| 17 |
+
"""
|
| 18 |
+
日本語のテキストから BERT の特徴量を抽出する
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
text (str): 日本語のテキスト
|
| 22 |
+
word2ph (list[int]): 元のテキストの各文字に音素が何個割り当てられるかを表すリスト
|
| 23 |
+
device (str): 推論に利用するデバイス
|
| 24 |
+
assist_text (Optional[str], optional): 補助テキスト (デフォルト: None)
|
| 25 |
+
assist_text_weight (float, optional): 補助テキストの重み (デフォルト: 0.7)
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
torch.Tensor: BERT の特徴量
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
# 各単語が何文字かを作る `word2ph` を使う必要があるので、読めない文字は必ず無視する
|
| 32 |
+
# でないと `word2ph` の結果とテキストの文字数結果が整合性が取れない
|
| 33 |
+
text = "".join(text_to_sep_kata(text, raise_yomi_error=False)[0])
|
| 34 |
+
if assist_text:
|
| 35 |
+
assist_text = "".join(text_to_sep_kata(assist_text, raise_yomi_error=False)[0])
|
| 36 |
+
|
| 37 |
+
if device == "cuda" and not torch.cuda.is_available():
|
| 38 |
+
device = "cpu"
|
| 39 |
+
model = bert_models.load_model(Languages.JP).to(device) # type: ignore
|
| 40 |
+
|
| 41 |
+
style_res_mean = None
|
| 42 |
+
with torch.no_grad():
|
| 43 |
+
tokenizer = bert_models.load_tokenizer(Languages.JP)
|
| 44 |
+
inputs = tokenizer(text, return_tensors="pt")
|
| 45 |
+
for i in inputs:
|
| 46 |
+
inputs[i] = inputs[i].to(device) # type: ignore
|
| 47 |
+
res = model(**inputs, output_hidden_states=True)
|
| 48 |
+
res = torch.cat(res["hidden_states"][-3:-2], -1)[0].cpu()
|
| 49 |
+
if assist_text:
|
| 50 |
+
style_inputs = tokenizer(assist_text, return_tensors="pt")
|
| 51 |
+
for i in style_inputs:
|
| 52 |
+
style_inputs[i] = style_inputs[i].to(device) # type: ignore
|
| 53 |
+
style_res = model(**style_inputs, output_hidden_states=True)
|
| 54 |
+
style_res = torch.cat(style_res["hidden_states"][-3:-2], -1)[0].cpu()
|
| 55 |
+
style_res_mean = style_res.mean(0)
|
| 56 |
+
|
| 57 |
+
assert len(word2ph) == len(text) + 2, text
|
| 58 |
+
word2phone = word2ph
|
| 59 |
+
phone_level_feature = []
|
| 60 |
+
for i in range(len(word2phone)):
|
| 61 |
+
if assist_text:
|
| 62 |
+
assert style_res_mean is not None
|
| 63 |
+
repeat_feature = (
|
| 64 |
+
res[i].repeat(word2phone[i], 1) * (1 - assist_text_weight)
|
| 65 |
+
+ style_res_mean.repeat(word2phone[i], 1) * assist_text_weight
|
| 66 |
+
)
|
| 67 |
+
else:
|
| 68 |
+
repeat_feature = res[i].repeat(word2phone[i], 1)
|
| 69 |
+
phone_level_feature.append(repeat_feature)
|
| 70 |
+
|
| 71 |
+
phone_level_feature = torch.cat(phone_level_feature, dim=0)
|
| 72 |
+
|
| 73 |
+
return phone_level_feature.T
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/g2p.py
ADDED
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from typing import TypedDict
|
| 3 |
+
|
| 4 |
+
from style_bert_vits2.constants import Languages
|
| 5 |
+
from style_bert_vits2.logging import logger
|
| 6 |
+
from style_bert_vits2.nlp import bert_models
|
| 7 |
+
from style_bert_vits2.nlp.japanese import pyopenjtalk_worker as pyopenjtalk
|
| 8 |
+
from style_bert_vits2.nlp.japanese.mora_list import MORA_KATA_TO_MORA_PHONEMES, VOWELS
|
| 9 |
+
from style_bert_vits2.nlp.japanese.normalizer import replace_punctuation
|
| 10 |
+
from style_bert_vits2.nlp.symbols import PUNCTUATIONS
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def g2p(
|
| 14 |
+
norm_text: str, use_jp_extra: bool = True, raise_yomi_error: bool = False
|
| 15 |
+
) -> tuple[list[str], list[int], list[int]]:
|
| 16 |
+
"""
|
| 17 |
+
他で使われるメインの関数。`normalize_text()` で正規化された `norm_text` を受け取り、
|
| 18 |
+
- phones: 音素のリスト(ただし `!` や `,` や `.` など punctuation が含まれうる)
|
| 19 |
+
- tones: アクセントのリスト、0(低)と1(高)からなり、phones と同じ長さ
|
| 20 |
+
- word2ph: 元のテキストの各文字に音素が何個割り当てられるかを表すリスト
|
| 21 |
+
のタプルを返す。
|
| 22 |
+
ただし `phones` と `tones` の最初と終わりに `_` が入り、応じて `word2ph` の最初と最後に 1 が追加される。
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
norm_text (str): 正規化されたテキスト
|
| 26 |
+
use_jp_extra (bool, optional): False の場合、「ん」の音素を「N」ではなく「n」とする。Defaults to True.
|
| 27 |
+
raise_yomi_error (bool, optional): False の場合、読めない文字が「'」として発音される。Defaults to False.
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
tuple[list[str], list[int], list[int]]: 音素のリスト、アクセントのリスト、word2ph のリスト
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
# pyopenjtalk のフルコンテキストラベルを使ってアクセントを取り出すと、punctuation の位置が消えてしまい情報が失われてしまう:
|
| 34 |
+
# 「こんにちは、世界。」と「こんにちは!世界。」と「こんにちは!!!???世界……。」は全て同じになる。
|
| 35 |
+
# よって、まず punctuation 無しの音素とアクセントのリストを作り、
|
| 36 |
+
# それとは別に pyopenjtalk.run_frontend() で得られる音素リスト(こちらは punctuation が保持される)を使い、
|
| 37 |
+
# アクセント割当をしなおすことによって punctuation を含めた音素とアクセントのリストを作る。
|
| 38 |
+
|
| 39 |
+
# punctuation がすべて消えた、音素とアクセントのタプルのリスト(「ん」は「N」)
|
| 40 |
+
phone_tone_list_wo_punct = __g2phone_tone_wo_punct(norm_text)
|
| 41 |
+
|
| 42 |
+
# sep_text: 単語単位の単語のリスト
|
| 43 |
+
# sep_kata: 単語単位の単語のカタカナ読みのリスト、読めない文字は raise_yomi_error=True なら例外、False なら読めない文字を「'」として返ってくる
|
| 44 |
+
sep_text, sep_kata = text_to_sep_kata(norm_text, raise_yomi_error=raise_yomi_error)
|
| 45 |
+
|
| 46 |
+
# sep_phonemes: 各単語ごとの音素のリストのリスト
|
| 47 |
+
sep_phonemes = __handle_long([__kata_to_phoneme_list(i) for i in sep_kata])
|
| 48 |
+
|
| 49 |
+
# phone_w_punct: sep_phonemes を結合した、punctuation を元のまま保持した音素列
|
| 50 |
+
phone_w_punct: list[str] = []
|
| 51 |
+
for i in sep_phonemes:
|
| 52 |
+
phone_w_punct += i
|
| 53 |
+
|
| 54 |
+
# punctuation 無しのアクセント情報を使って、punctuation を含めたアクセント情報を作る
|
| 55 |
+
phone_tone_list = __align_tones(phone_w_punct, phone_tone_list_wo_punct)
|
| 56 |
+
# logger.debug(f"phone_tone_list:\n{phone_tone_list}")
|
| 57 |
+
|
| 58 |
+
# word2ph は厳密な解答は不可能なので(「今日」「眼鏡」等の熟字訓が存在)、
|
| 59 |
+
# Bert-VITS2 では、単語単位の分割を使って、単語の文字ごとにだいたい均等に音素を分配する
|
| 60 |
+
|
| 61 |
+
# sep_text から、各単語を1文字1文字分割して、文字のリスト(のリスト)を作る
|
| 62 |
+
sep_tokenized: list[list[str]] = []
|
| 63 |
+
for i in sep_text:
|
| 64 |
+
if i not in PUNCTUATIONS:
|
| 65 |
+
sep_tokenized.append(
|
| 66 |
+
bert_models.load_tokenizer(Languages.JP).tokenize(i)
|
| 67 |
+
) # ここでおそらく`i`が文字単位に分割される
|
| 68 |
+
else:
|
| 69 |
+
sep_tokenized.append([i])
|
| 70 |
+
|
| 71 |
+
# 各単語について、音素の数と文字の数を比較して、均等っぽく分配する
|
| 72 |
+
word2ph = []
|
| 73 |
+
for token, phoneme in zip(sep_tokenized, sep_phonemes):
|
| 74 |
+
phone_len = len(phoneme)
|
| 75 |
+
word_len = len(token)
|
| 76 |
+
word2ph += __distribute_phone(phone_len, word_len)
|
| 77 |
+
|
| 78 |
+
# 最初と最後に `_` 記号を追加、アクセントは 0(低)、word2ph もそれに合わせて追加
|
| 79 |
+
phone_tone_list = [("_", 0)] + phone_tone_list + [("_", 0)]
|
| 80 |
+
word2ph = [1] + word2ph + [1]
|
| 81 |
+
|
| 82 |
+
phones = [phone for phone, _ in phone_tone_list]
|
| 83 |
+
tones = [tone for _, tone in phone_tone_list]
|
| 84 |
+
|
| 85 |
+
assert len(phones) == sum(word2ph), f"{len(phones)} != {sum(word2ph)}"
|
| 86 |
+
|
| 87 |
+
# use_jp_extra でない場合は「N」を「n」に変換
|
| 88 |
+
if not use_jp_extra:
|
| 89 |
+
phones = [phone if phone != "N" else "n" for phone in phones]
|
| 90 |
+
|
| 91 |
+
return phones, tones, word2ph
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def text_to_sep_kata(
|
| 95 |
+
norm_text: str, raise_yomi_error: bool = False
|
| 96 |
+
) -> tuple[list[str], list[str]]:
|
| 97 |
+
"""
|
| 98 |
+
`normalize_text` で正規化済みの `norm_text` を受け取り、それを単語分割し、
|
| 99 |
+
分割された単語リストとその読み(カタカナ or 記号1文字)のリストのタプルを返す。
|
| 100 |
+
単語分割結果は、`g2p()` の `word2ph` で1文字あたりに割り振る音素記号の数を決めるために使う。
|
| 101 |
+
例:
|
| 102 |
+
`私はそう思う!って感じ?` →
|
| 103 |
+
["私", "は", "そう", "思う", "!", "って", "感じ", "?"], ["ワタシ", "ワ", "ソー", "オモウ", "!", "ッテ", "カンジ", "?"]
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
norm_text (str): 正規化されたテキスト
|
| 107 |
+
raise_yomi_error (bool, optional): False の場合、読めない文字が「'」として発音される。Defaults to False.
|
| 108 |
+
|
| 109 |
+
Returns:
|
| 110 |
+
tuple[list[str], list[str]]: 分割された単語リストと、その読み(カタカナ or 記号1文字)のリスト
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
# parsed: OpenJTalkの解析結果
|
| 114 |
+
parsed = pyopenjtalk.run_frontend(norm_text)
|
| 115 |
+
sep_text: list[str] = []
|
| 116 |
+
sep_kata: list[str] = []
|
| 117 |
+
|
| 118 |
+
for parts in parsed:
|
| 119 |
+
# word: 実際の単語の文字列
|
| 120 |
+
# yomi: その読み、但し無声化サインの`’`は除去
|
| 121 |
+
word, yomi = replace_punctuation(parts["string"]), parts["pron"].replace(
|
| 122 |
+
"’", ""
|
| 123 |
+
)
|
| 124 |
+
"""
|
| 125 |
+
ここで `yomi` の取りうる値は以下の通りのはず。
|
| 126 |
+
- `word` が通常単語 → 通常の読み(カタカナ)
|
| 127 |
+
(カタカナからなり、長音記号も含みうる、`アー` 等)
|
| 128 |
+
- `word` が `ー` から始まる → `ーラー` や `ーーー` など
|
| 129 |
+
- `word` が句読点や空白等 → `、`
|
| 130 |
+
- `word` が punctuation の繰り返し → 全角にしたもの
|
| 131 |
+
基本的に punctuation は1文字ずつ分かれるが、何故かある程度連続すると1つにまとまる。
|
| 132 |
+
他にも `word` が読めないキリル文字アラビア文字等が来ると `、` になるが、正規化でこの場合は起きないはず。
|
| 133 |
+
また元のコードでは `yomi` が空白の場合の処理があったが、これは起きないはず。
|
| 134 |
+
処理すべきは `yomi` が `、` の場合のみのはず。
|
| 135 |
+
"""
|
| 136 |
+
assert yomi != "", f"Empty yomi: {word}"
|
| 137 |
+
if yomi == "、":
|
| 138 |
+
# word は正規化されているので、`.`, `,`, `!`, `'`, `-`, `--` のいずれか
|
| 139 |
+
if not set(word).issubset(set(PUNCTUATIONS)): # 記号繰り返しか判定
|
| 140 |
+
# ここは pyopenjtalk が読めない文字等のときに起こる
|
| 141 |
+
## 例外を送出する場合
|
| 142 |
+
if raise_yomi_error:
|
| 143 |
+
raise YomiError(f"Cannot read: {word} in:\n{norm_text}")
|
| 144 |
+
## 例外を送出しない場合
|
| 145 |
+
## 読めない文字は「'」として扱う
|
| 146 |
+
logger.warning(
|
| 147 |
+
f'Cannot read: {word} in:\n{norm_text}, replaced with "\'"'
|
| 148 |
+
)
|
| 149 |
+
# word の文字数分「'」を追加
|
| 150 |
+
yomi = "'" * len(word)
|
| 151 |
+
else:
|
| 152 |
+
# yomi は元の記号のままに変更
|
| 153 |
+
yomi = word
|
| 154 |
+
elif yomi == "?":
|
| 155 |
+
assert word == "?", f"yomi `?` comes from: {word}"
|
| 156 |
+
yomi = "?"
|
| 157 |
+
sep_text.append(word)
|
| 158 |
+
sep_kata.append(yomi)
|
| 159 |
+
|
| 160 |
+
return sep_text, sep_kata
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def adjust_word2ph(
|
| 164 |
+
word2ph: list[int],
|
| 165 |
+
generated_phone: list[str],
|
| 166 |
+
given_phone: list[str],
|
| 167 |
+
) -> list[int]:
|
| 168 |
+
"""
|
| 169 |
+
`g2p()` で得られた `word2ph` を、generated_phone と given_phone の差分情報を使っていい感じに調整する。
|
| 170 |
+
generated_phone は正規化された読み上げテキストから生成された読みの情報だが、
|
| 171 |
+
given_phone で 同じ読み上げテキストに異なる読みが与えられた場合、正規化された読み上げテキストの各文字に
|
| 172 |
+
音素が何文字割り当てられるかを示す word2ph の合計値が given_phone の長さ (音素数) と一致しなくなりうる
|
| 173 |
+
そこで generated_phone と given_phone の差分を取り変更箇所に対応する word2ph の要素の値だけを増減させ、
|
| 174 |
+
アクセントへの影響を最低限に抑えつつ word2ph の合計値を given_phone の長さ (音素数) に一致させる。
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
word2ph (list[int]): 単語ごとの音素の数のリスト
|
| 178 |
+
generated_phone (list[str]): 生成された音素のリスト
|
| 179 |
+
given_phone (list[str]): 与えられた音素のリスト
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
list[int]: 修正された word2ph のリスト
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
# word2ph・generated_phone・given_phone 全ての先頭と末尾にダミー要素が入っているので、処理の都合上それらを削除
|
| 186 |
+
# word2ph は先頭と末尾に 1 が入っている (返す際に再度追加する)
|
| 187 |
+
word2ph = word2ph[1:-1]
|
| 188 |
+
generated_phone = generated_phone[1:-1]
|
| 189 |
+
given_phone = given_phone[1:-1]
|
| 190 |
+
|
| 191 |
+
class DiffDetail(TypedDict):
|
| 192 |
+
begin_index: int
|
| 193 |
+
end_index: int
|
| 194 |
+
value: list[str]
|
| 195 |
+
|
| 196 |
+
class Diff(TypedDict):
|
| 197 |
+
generated: DiffDetail
|
| 198 |
+
given: DiffDetail
|
| 199 |
+
|
| 200 |
+
def extract_differences(
|
| 201 |
+
generated_phone: list[str], given_phone: list[str]
|
| 202 |
+
) -> list[Diff]:
|
| 203 |
+
"""
|
| 204 |
+
最長共通部分列を基にして、二つのリストの異なる部分を抽出する。
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
def longest_common_subsequence(
|
| 208 |
+
X: list[str], Y: list[str]
|
| 209 |
+
) -> list[tuple[int, int]]:
|
| 210 |
+
"""
|
| 211 |
+
二つのリストの最長共通部分列のインデックスのペアを返す。
|
| 212 |
+
"""
|
| 213 |
+
m, n = len(X), len(Y)
|
| 214 |
+
L = [[0] * (n + 1) for _ in range(m + 1)]
|
| 215 |
+
# LCSの長さを構築
|
| 216 |
+
for i in range(1, m + 1):
|
| 217 |
+
for j in range(1, n + 1):
|
| 218 |
+
if X[i - 1] == Y[j - 1]:
|
| 219 |
+
L[i][j] = L[i - 1][j - 1] + 1
|
| 220 |
+
else:
|
| 221 |
+
L[i][j] = max(L[i - 1][j], L[i][j - 1])
|
| 222 |
+
# LCSを逆方向にトレースしてインデックスのペアを取得
|
| 223 |
+
index_pairs = []
|
| 224 |
+
i, j = m, n
|
| 225 |
+
while i > 0 and j > 0:
|
| 226 |
+
if X[i - 1] == Y[j - 1]:
|
| 227 |
+
index_pairs.append((i - 1, j - 1))
|
| 228 |
+
i -= 1
|
| 229 |
+
j -= 1
|
| 230 |
+
elif L[i - 1][j] >= L[i][j - 1]:
|
| 231 |
+
i -= 1
|
| 232 |
+
else:
|
| 233 |
+
j -= 1
|
| 234 |
+
index_pairs.reverse()
|
| 235 |
+
return index_pairs
|
| 236 |
+
|
| 237 |
+
differences = []
|
| 238 |
+
common_indices = longest_common_subsequence(generated_phone, given_phone)
|
| 239 |
+
prev_x, prev_y = -1, -1
|
| 240 |
+
|
| 241 |
+
# 共通部分のインデックスを基にして差分を抽出
|
| 242 |
+
for x, y in common_indices:
|
| 243 |
+
diff_X = {
|
| 244 |
+
"begin_index": prev_x + 1,
|
| 245 |
+
"end_index": x,
|
| 246 |
+
"value": generated_phone[prev_x + 1 : x],
|
| 247 |
+
}
|
| 248 |
+
diff_Y = {
|
| 249 |
+
"begin_index": prev_y + 1,
|
| 250 |
+
"end_index": y,
|
| 251 |
+
"value": given_phone[prev_y + 1 : y],
|
| 252 |
+
}
|
| 253 |
+
if diff_X or diff_Y:
|
| 254 |
+
differences.append({"generated": diff_X, "given": diff_Y})
|
| 255 |
+
prev_x, prev_y = x, y
|
| 256 |
+
# 最後の非共通部分を追加
|
| 257 |
+
if prev_x < len(generated_phone) - 1 or prev_y < len(given_phone) - 1:
|
| 258 |
+
differences.append(
|
| 259 |
+
{
|
| 260 |
+
"generated": {
|
| 261 |
+
"begin_index": prev_x + 1,
|
| 262 |
+
"end_index": len(generated_phone) - 1,
|
| 263 |
+
"value": generated_phone[prev_x + 1 : len(generated_phone) - 1],
|
| 264 |
+
},
|
| 265 |
+
"given": {
|
| 266 |
+
"begin_index": prev_y + 1,
|
| 267 |
+
"end_index": len(given_phone) - 1,
|
| 268 |
+
"value": given_phone[prev_y + 1 : len(given_phone) - 1],
|
| 269 |
+
},
|
| 270 |
+
}
|
| 271 |
+
)
|
| 272 |
+
# generated.value と given.value の両方が空の要素を diffrences から削除
|
| 273 |
+
for diff in differences[:]:
|
| 274 |
+
if (
|
| 275 |
+
len(diff["generated"]["value"]) == 0
|
| 276 |
+
and len(diff["given"]["value"]) == 0
|
| 277 |
+
):
|
| 278 |
+
differences.remove(diff)
|
| 279 |
+
|
| 280 |
+
return differences
|
| 281 |
+
|
| 282 |
+
# 二つのリストの差分を抽出
|
| 283 |
+
differences = extract_differences(generated_phone, given_phone)
|
| 284 |
+
|
| 285 |
+
# word2ph をもとにして新しく作る word2ph のリスト
|
| 286 |
+
## 長さは word2ph と同じだが、中身は 0 で初期化されている
|
| 287 |
+
adjusted_word2ph: list[int] = [0] * len(word2ph)
|
| 288 |
+
# 現在処理中の generated_phone のインデックス
|
| 289 |
+
current_generated_index = 0
|
| 290 |
+
|
| 291 |
+
# word2ph の要素数 (=正規化された読み上げテキストの文字数) を維持しながら、差分情報を使って word2ph を修正
|
| 292 |
+
## 音素数が generated_phone と given_phone で異なる場合にこの align_word2ph() が呼び出される
|
| 293 |
+
## word2ph は正規化された読み上げテキストの文字数に対応しているので、要素数はそのまま given_phone で増減した音素数に合わせて各要素の値を増減する
|
| 294 |
+
for word2ph_element_index, word2ph_element in enumerate(word2ph):
|
| 295 |
+
# ここの word2ph_element は、正規化された読み上げテキストの各文字に割り当てられる音素の数を示す
|
| 296 |
+
# 例えば word2ph_element が 2 ならば、その文字には 2 つの音素 (例: "k", "a") が割り当てられる
|
| 297 |
+
# 音素の数だけループを回す
|
| 298 |
+
for _ in range(word2ph_element):
|
| 299 |
+
# difference の中に 処理中の generated_phone から始まる差分があるかどうかを確認
|
| 300 |
+
current_diff: Diff | None = None
|
| 301 |
+
for diff in differences:
|
| 302 |
+
if diff["generated"]["begin_index"] == current_generated_index:
|
| 303 |
+
current_diff = diff
|
| 304 |
+
break
|
| 305 |
+
# current_diff が None でない場合、generated_phone から始まる差分がある
|
| 306 |
+
if current_diff is not None:
|
| 307 |
+
# generated から given で変わった音素数の差分を取得 (2増えた場合は +2 だし、2減った場合は -2)
|
| 308 |
+
diff_in_phonemes = \
|
| 309 |
+
len(current_diff["given"]["value"]) - len(current_diff["generated"]["value"]) # fmt: skip
|
| 310 |
+
# adjusted_word2ph[(読み上げテキストの各文字のインデックス)] に上記差分を反映
|
| 311 |
+
adjusted_word2ph[word2ph_element_index] += diff_in_phonemes
|
| 312 |
+
# adjusted_word2ph[(読み上げテキストの各文字のインデックス)] に処理が完了した分の音素として 1 を加える
|
| 313 |
+
adjusted_word2ph[word2ph_element_index] += 1
|
| 314 |
+
# 処理中の generated_phone のインデックスを進める
|
| 315 |
+
current_generated_index += 1
|
| 316 |
+
|
| 317 |
+
# この時点で given_phone の長さと adjusted_word2ph に記録されている音素数の合計が一致しているはず
|
| 318 |
+
assert len(given_phone) == sum(adjusted_word2ph), f"{len(given_phone)} != {sum(adjusted_word2ph)}" # fmt: skip
|
| 319 |
+
|
| 320 |
+
# generated_phone から given_phone の間で音素が減った場合 (例: a, sh, i, t, a -> a, s, u) 、
|
| 321 |
+
# adjusted_word2ph の要素の値が 1 未満になることがあるので、1 になるように値を増やす
|
| 322 |
+
## この時、adjusted_word2ph に記録されている音素数の合計を変えないために、
|
| 323 |
+
## 値を 1 にした分だけ右隣の要素から増やした分の差分を差し引く
|
| 324 |
+
for adjusted_word2ph_element_index, adjusted_word2ph_element in enumerate(adjusted_word2ph): # fmt: skip
|
| 325 |
+
# もし現在の要素が 1 未満ならば
|
| 326 |
+
if adjusted_word2ph_element < 1:
|
| 327 |
+
# 値を 1 にするためにどれだけ足せばいいかを計算
|
| 328 |
+
diff = 1 - adjusted_word2ph_element
|
| 329 |
+
# adjusted_word2ph[(読み上げテキストの各文字のインデックス)] を 1 にする
|
| 330 |
+
# これにより、当該文字に最低ラインとして 1 つの音素が割り当てられる
|
| 331 |
+
adjusted_word2ph[adjusted_word2ph_element_index] = 1
|
| 332 |
+
# 次の要素のうち、一番近くてかつ 1 以上の要素から diff を引く
|
| 333 |
+
# この時、diff を引いた結果引いた要素が 1 未満になる場合は、その要素の次の要素の中から一番近くてかつ 1 以上の要素から引く
|
| 334 |
+
# 上記を繰り返していって、diff が 0 になるまで続ける
|
| 335 |
+
for i in range(1, len(adjusted_word2ph)):
|
| 336 |
+
if adjusted_word2ph_element_index + i >= len(adjusted_word2ph):
|
| 337 |
+
break # adjusted_word2ph の最後に達した場合は諦める
|
| 338 |
+
if adjusted_word2ph[adjusted_word2ph_element_index + i] - diff >= 1:
|
| 339 |
+
adjusted_word2ph[adjusted_word2ph_element_index + i] -= diff
|
| 340 |
+
break
|
| 341 |
+
else:
|
| 342 |
+
diff -= adjusted_word2ph[adjusted_word2ph_element_index + i] - 1
|
| 343 |
+
adjusted_word2ph[adjusted_word2ph_element_index + i] = 1
|
| 344 |
+
if diff == 0:
|
| 345 |
+
break
|
| 346 |
+
|
| 347 |
+
# 逆に、generated_phone から given_phone の間で音素が増えた場合 (例: a, s, u -> a, sh, i, t, a) 、
|
| 348 |
+
# 1文字あたり7音素以上も割り当てられてしまう場合があるので、最大6音素にした上で削った分の差分を次の要素に加える
|
| 349 |
+
# 次の要素に差分を加えた結果7音素以上になってしまう場合は、その差分をさらに次の要素に加える
|
| 350 |
+
for adjusted_word2ph_element_index, adjusted_word2ph_element in enumerate(adjusted_word2ph): # fmt: skip
|
| 351 |
+
if adjusted_word2ph_element > 6:
|
| 352 |
+
diff = adjusted_word2ph_element - 6
|
| 353 |
+
adjusted_word2ph[adjusted_word2ph_element_index] = 6
|
| 354 |
+
for i in range(1, len(adjusted_word2ph)):
|
| 355 |
+
if adjusted_word2ph_element_index + i >= len(adjusted_word2ph):
|
| 356 |
+
break # adjusted_word2ph の最後に達した場合は諦める
|
| 357 |
+
if adjusted_word2ph[adjusted_word2ph_element_index + i] + diff <= 6:
|
| 358 |
+
adjusted_word2ph[adjusted_word2ph_element_index + i] += diff
|
| 359 |
+
break
|
| 360 |
+
else:
|
| 361 |
+
diff -= 6 - adjusted_word2ph[adjusted_word2ph_element_index + i]
|
| 362 |
+
adjusted_word2ph[adjusted_word2ph_element_index + i] = 6
|
| 363 |
+
if diff == 0:
|
| 364 |
+
break
|
| 365 |
+
|
| 366 |
+
# この時点で given_phone の長さと adjusted_word2ph に記録されている音素数の合計が一致していない場合、
|
| 367 |
+
# 正規化された読み上げテキストと given_phone が著しく乖離していることを示す
|
| 368 |
+
# このとき、この関数の呼び出し元の get_text() にて InvalidPhoneError が送出される
|
| 369 |
+
|
| 370 |
+
# 最初に削除した前後のダミー要素を追加して返す
|
| 371 |
+
return [1] + adjusted_word2ph + [1]
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def __g2phone_tone_wo_punct(text: str) -> list[tuple[str, int]]:
|
| 375 |
+
"""
|
| 376 |
+
テキストに対して、音素とアクセント(0か1)のペアのリストを返す。
|
| 377 |
+
ただし「!」「.」「?」等の非音素記号 (punctuation) は全て消える(ポーズ記号も残さない)。
|
| 378 |
+
非音素記号を含める処理は `align_tones()` で行われる。
|
| 379 |
+
また「っ」は「q」に、「ん」は「N」に変換される。
|
| 380 |
+
例: "こんにちは、世界ー。。元気?!" →
|
| 381 |
+
[('k', 0), ('o', 0), ('N', 1), ('n', 1), ('i', 1), ('ch', 1), ('i', 1), ('w', 1), ('a', 1), ('s', 1), ('e', 1), ('k', 0), ('a', 0), ('i', 0), ('i', 0), ('g', 1), ('e', 1), ('N', 0), ('k', 0), ('i', 0)]
|
| 382 |
+
|
| 383 |
+
Args:
|
| 384 |
+
text (str): テキスト
|
| 385 |
+
|
| 386 |
+
Returns:
|
| 387 |
+
list[tuple[str, int]]: 音素とアクセントのペアのリスト
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
prosodies = __pyopenjtalk_g2p_prosody(text, drop_unvoiced_vowels=True)
|
| 391 |
+
# logger.debug(f"prosodies: {prosodies}")
|
| 392 |
+
result: list[tuple[str, int]] = []
|
| 393 |
+
current_phrase: list[tuple[str, int]] = []
|
| 394 |
+
current_tone = 0
|
| 395 |
+
|
| 396 |
+
for i, letter in enumerate(prosodies):
|
| 397 |
+
# 特殊記号の処理
|
| 398 |
+
|
| 399 |
+
# 文頭記号、無視する
|
| 400 |
+
if letter == "^":
|
| 401 |
+
assert i == 0, "Unexpected ^"
|
| 402 |
+
# アクセント句の終わりに来る記号
|
| 403 |
+
elif letter in ("$", "?", "_", "#"):
|
| 404 |
+
# 保持しているフレーズを、アクセント数値を 0-1 に修正し結果に追加
|
| 405 |
+
result.extend(__fix_phone_tone(current_phrase))
|
| 406 |
+
# 末尾に来る終了記号、無視(文中の疑問文は `_` になる)
|
| 407 |
+
if letter in ("$", "?"):
|
| 408 |
+
assert i == len(prosodies) - 1, f"Unexpected {letter}"
|
| 409 |
+
# あとは "_"(ポーズ)と "#"(アクセント句の境界)のみ
|
| 410 |
+
# これらは残さず、次のアクセント句に備える。
|
| 411 |
+
current_phrase = []
|
| 412 |
+
# 0 を基準点にしてそこから上昇・下降する(負の場合は上の `fix_phone_tone` で直る)
|
| 413 |
+
current_tone = 0
|
| 414 |
+
# アクセント上昇記号
|
| 415 |
+
elif letter == "[":
|
| 416 |
+
current_tone = current_tone + 1
|
| 417 |
+
# アクセント下降記号
|
| 418 |
+
elif letter == "]":
|
| 419 |
+
current_tone = current_tone - 1
|
| 420 |
+
# それ以外は通常の音素
|
| 421 |
+
else:
|
| 422 |
+
if letter == "cl": # 「っ」の処理
|
| 423 |
+
letter = "q"
|
| 424 |
+
# elif letter == "N": # 「ん」の処理
|
| 425 |
+
# letter = "n"
|
| 426 |
+
current_phrase.append((letter, current_tone))
|
| 427 |
+
|
| 428 |
+
return result
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
__PYOPENJTALK_G2P_PROSODY_A1_PATTERN = re.compile(r"/A:([0-9\-]+)\+")
|
| 432 |
+
__PYOPENJTALK_G2P_PROSODY_A2_PATTERN = re.compile(r"\+(\d+)\+")
|
| 433 |
+
__PYOPENJTALK_G2P_PROSODY_A3_PATTERN = re.compile(r"\+(\d+)/")
|
| 434 |
+
__PYOPENJTALK_G2P_PROSODY_E3_PATTERN = re.compile(r"!(\d+)_")
|
| 435 |
+
__PYOPENJTALK_G2P_PROSODY_F1_PATTERN = re.compile(r"/F:(\d+)_")
|
| 436 |
+
__PYOPENJTALK_G2P_PROSODY_P3_PATTERN = re.compile(r"\-(.*?)\+")
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def __pyopenjtalk_g2p_prosody(
|
| 440 |
+
text: str, drop_unvoiced_vowels: bool = True
|
| 441 |
+
) -> list[str]:
|
| 442 |
+
"""
|
| 443 |
+
ESPnet の実装から引用、概ね変更点無し。「ん」は「N」なことに注意。
|
| 444 |
+
ref: https://github.com/espnet/espnet/blob/master/espnet2/text/phoneme_tokenizer.py
|
| 445 |
+
------------------------------------------------------------------------------------------
|
| 446 |
+
|
| 447 |
+
Extract phoneme + prosody symbol sequence from input full-context labels.
|
| 448 |
+
|
| 449 |
+
The algorithm is based on `Prosodic features control by symbols as input of
|
| 450 |
+
sequence-to-sequence acoustic modeling for neural TTS`_ with some r9y9's tweaks.
|
| 451 |
+
|
| 452 |
+
Args:
|
| 453 |
+
text (str): Input text.
|
| 454 |
+
drop_unvoiced_vowels (bool): whether to drop unvoiced vowels.
|
| 455 |
+
|
| 456 |
+
Returns:
|
| 457 |
+
List[str]: List of phoneme + prosody symbols.
|
| 458 |
+
|
| 459 |
+
Examples:
|
| 460 |
+
>>> from espnet2.text.phoneme_tokenizer import pyopenjtalk_g2p_prosody
|
| 461 |
+
>>> pyopenjtalk_g2p_prosody("こんにちは。")
|
| 462 |
+
['^', 'k', 'o', '[', 'N', 'n', 'i', 'ch', 'i', 'w', 'a', '$']
|
| 463 |
+
|
| 464 |
+
.. _`Prosodic features control by symbols as input of sequence-to-sequence acoustic
|
| 465 |
+
modeling for neural TTS`: https://doi.org/10.1587/transinf.2020EDP7104
|
| 466 |
+
"""
|
| 467 |
+
|
| 468 |
+
def _numeric_feature_by_regex(pattern: re.Pattern[str], s: str) -> int:
|
| 469 |
+
match = pattern.search(s)
|
| 470 |
+
if match is None:
|
| 471 |
+
return -50
|
| 472 |
+
return int(match.group(1))
|
| 473 |
+
|
| 474 |
+
labels = pyopenjtalk.make_label(pyopenjtalk.run_frontend(text))
|
| 475 |
+
N = len(labels)
|
| 476 |
+
|
| 477 |
+
phones = []
|
| 478 |
+
for n in range(N):
|
| 479 |
+
lab_curr = labels[n]
|
| 480 |
+
|
| 481 |
+
# current phoneme
|
| 482 |
+
p3 = __PYOPENJTALK_G2P_PROSODY_P3_PATTERN.search(lab_curr).group(1) # type: ignore
|
| 483 |
+
# deal unvoiced vowels as normal vowels
|
| 484 |
+
if drop_unvoiced_vowels and p3 in "AEIOU":
|
| 485 |
+
p3 = p3.lower()
|
| 486 |
+
|
| 487 |
+
# deal with sil at the beginning and the end of text
|
| 488 |
+
if p3 == "sil":
|
| 489 |
+
assert n == 0 or n == N - 1
|
| 490 |
+
if n == 0:
|
| 491 |
+
phones.append("^")
|
| 492 |
+
elif n == N - 1:
|
| 493 |
+
# check question form or not
|
| 494 |
+
e3 = _numeric_feature_by_regex(
|
| 495 |
+
__PYOPENJTALK_G2P_PROSODY_E3_PATTERN, lab_curr
|
| 496 |
+
)
|
| 497 |
+
if e3 == 0:
|
| 498 |
+
phones.append("$")
|
| 499 |
+
elif e3 == 1:
|
| 500 |
+
phones.append("?")
|
| 501 |
+
continue
|
| 502 |
+
elif p3 == "pau":
|
| 503 |
+
phones.append("_")
|
| 504 |
+
continue
|
| 505 |
+
else:
|
| 506 |
+
phones.append(p3)
|
| 507 |
+
|
| 508 |
+
# accent type and position info (forward or backward)
|
| 509 |
+
a1 = _numeric_feature_by_regex(__PYOPENJTALK_G2P_PROSODY_A1_PATTERN, lab_curr)
|
| 510 |
+
a2 = _numeric_feature_by_regex(__PYOPENJTALK_G2P_PROSODY_A2_PATTERN, lab_curr)
|
| 511 |
+
a3 = _numeric_feature_by_regex(__PYOPENJTALK_G2P_PROSODY_A3_PATTERN, lab_curr)
|
| 512 |
+
|
| 513 |
+
# number of mora in accent phrase
|
| 514 |
+
f1 = _numeric_feature_by_regex(__PYOPENJTALK_G2P_PROSODY_F1_PATTERN, lab_curr)
|
| 515 |
+
|
| 516 |
+
a2_next = _numeric_feature_by_regex(
|
| 517 |
+
__PYOPENJTALK_G2P_PROSODY_A2_PATTERN, labels[n + 1]
|
| 518 |
+
)
|
| 519 |
+
# accent phrase border
|
| 520 |
+
if a3 == 1 and a2_next == 1 and p3 in "aeiouAEIOUNcl":
|
| 521 |
+
phones.append("#")
|
| 522 |
+
# pitch falling
|
| 523 |
+
elif a1 == 0 and a2_next == a2 + 1 and a2 != f1:
|
| 524 |
+
phones.append("]")
|
| 525 |
+
# pitch rising
|
| 526 |
+
elif a2 == 1 and a2_next == 2:
|
| 527 |
+
phones.append("[")
|
| 528 |
+
|
| 529 |
+
return phones
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def __fix_phone_tone(phone_tone_list: list[tuple[str, int]]) -> list[tuple[str, int]]:
|
| 533 |
+
"""
|
| 534 |
+
`phone_tone_list` の tone(アクセントの値)を 0 か 1 の範囲に修正する。
|
| 535 |
+
例: [(a, 0), (i, -1), (u, -1)] → [(a, 1), (i, 0), (u, 0)]
|
| 536 |
+
|
| 537 |
+
Args:
|
| 538 |
+
phone_tone_list (list[tuple[str, int]]): 音素とアクセントのペアのリスト
|
| 539 |
+
|
| 540 |
+
Returns:
|
| 541 |
+
list[tuple[str, int]]: 修正された音素とアクセントのペアのリスト
|
| 542 |
+
"""
|
| 543 |
+
|
| 544 |
+
tone_values = set(tone for _, tone in phone_tone_list)
|
| 545 |
+
if len(tone_values) == 1:
|
| 546 |
+
assert tone_values == {0}, tone_values
|
| 547 |
+
return phone_tone_list
|
| 548 |
+
elif len(tone_values) == 2:
|
| 549 |
+
if tone_values == {0, 1}:
|
| 550 |
+
return phone_tone_list
|
| 551 |
+
elif tone_values == {-1, 0}:
|
| 552 |
+
return [
|
| 553 |
+
(letter, 0 if tone == -1 else 1) for letter, tone in phone_tone_list
|
| 554 |
+
]
|
| 555 |
+
else:
|
| 556 |
+
raise ValueError(f"Unexpected tone values: {tone_values}")
|
| 557 |
+
else:
|
| 558 |
+
raise ValueError(f"Unexpected tone values: {tone_values}")
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def __handle_long(sep_phonemes: list[list[str]]) -> list[list[str]]:
|
| 562 |
+
"""
|
| 563 |
+
フレーズごとに分かれた音素(長音記号がそのまま)のリストのリスト `sep_phonemes` を受け取り、
|
| 564 |
+
その長音記号を処理して、音素のリストのリストを返す。
|
| 565 |
+
基本的には直前の音素を伸ばすが、直前の音素が母音でない場合もしくは冒頭の場合は、
|
| 566 |
+
おそらく長音記号とダッシュを勘違いしていると思われるので、ダッシュに対応する音素 `-` に変換する。
|
| 567 |
+
|
| 568 |
+
Args:
|
| 569 |
+
sep_phonemes (list[list[str]]): フレーズごとに分かれた音素のリストのリスト
|
| 570 |
+
|
| 571 |
+
Returns:
|
| 572 |
+
list[list[str]]: 長音記号を処理した音素のリストのリスト
|
| 573 |
+
"""
|
| 574 |
+
|
| 575 |
+
for i in range(len(sep_phonemes)):
|
| 576 |
+
if len(sep_phonemes[i]) == 0:
|
| 577 |
+
# 空白文字等でリストが空の場合
|
| 578 |
+
continue
|
| 579 |
+
if sep_phonemes[i][0] == "ー":
|
| 580 |
+
if i != 0:
|
| 581 |
+
prev_phoneme = sep_phonemes[i - 1][-1]
|
| 582 |
+
if prev_phoneme in VOWELS:
|
| 583 |
+
# 母音と「ん」のあとの伸ばし棒なので、その母音に変換
|
| 584 |
+
sep_phonemes[i][0] = sep_phonemes[i - 1][-1]
|
| 585 |
+
else:
|
| 586 |
+
# 「。ーー」等おそらく予期しない長音記号
|
| 587 |
+
# ダッシュの勘違いだと思われる
|
| 588 |
+
sep_phonemes[i][0] = "-"
|
| 589 |
+
else:
|
| 590 |
+
# 冒頭に長音記号が来ていおり、これはダッシュの勘違いと思われる
|
| 591 |
+
sep_phonemes[i][0] = "-"
|
| 592 |
+
if "ー" in sep_phonemes[i]:
|
| 593 |
+
for j in range(len(sep_phonemes[i])):
|
| 594 |
+
if sep_phonemes[i][j] == "ー":
|
| 595 |
+
sep_phonemes[i][j] = sep_phonemes[i][j - 1][-1]
|
| 596 |
+
|
| 597 |
+
return sep_phonemes
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
__KATAKANA_PATTERN = re.compile(r"[\u30A0-\u30FF]+")
|
| 601 |
+
__MORA_PATTERN = re.compile(
|
| 602 |
+
"|".join(
|
| 603 |
+
map(re.escape, sorted(MORA_KATA_TO_MORA_PHONEMES.keys(), key=len, reverse=True))
|
| 604 |
+
)
|
| 605 |
+
)
|
| 606 |
+
__LONG_PATTERN = re.compile(r"(\w)(ー*)")
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def __kata_to_phoneme_list(text: str) -> list[str]:
|
| 610 |
+
"""
|
| 611 |
+
原則カタカナの `text` を受け取り、それをその���まいじらずに音素記号のリストに変換。
|
| 612 |
+
注意点:
|
| 613 |
+
- punctuation かその繰り返しが来た場合、punctuation たちをそのままリストにして返す。
|
| 614 |
+
- 冒頭に続く「ー」はそのまま「ー」のままにする(`handle_long()` で処理される)
|
| 615 |
+
- 文中の「ー」は前の音素記号の最後の音素記号に変換される。
|
| 616 |
+
例:
|
| 617 |
+
`ーーソーナノカーー` → ["ー", "ー", "s", "o", "o", "n", "a", "n", "o", "k", "a", "a", "a"]
|
| 618 |
+
`?` → ["?"]
|
| 619 |
+
`!?!?!?!?!` → ["!", "?", "!", "?", "!", "?", "!", "?", "!"]
|
| 620 |
+
|
| 621 |
+
Args:
|
| 622 |
+
text (str): カタカナのテキスト
|
| 623 |
+
|
| 624 |
+
Returns:
|
| 625 |
+
list[str]: 音素記号のリスト
|
| 626 |
+
"""
|
| 627 |
+
|
| 628 |
+
if set(text).issubset(set(PUNCTUATIONS)):
|
| 629 |
+
return list(text)
|
| 630 |
+
# `text` がカタカナ(`ー`含む)のみからなるかどうかをチェック
|
| 631 |
+
if __KATAKANA_PATTERN.fullmatch(text) is None:
|
| 632 |
+
raise ValueError(f"Input must be katakana only: {text}")
|
| 633 |
+
|
| 634 |
+
def mora2phonemes(mora: str) -> str:
|
| 635 |
+
consonant, vowel = MORA_KATA_TO_MORA_PHONEMES[mora]
|
| 636 |
+
if consonant is None:
|
| 637 |
+
return f" {vowel}"
|
| 638 |
+
return f" {consonant} {vowel}"
|
| 639 |
+
|
| 640 |
+
spaced_phonemes = __MORA_PATTERN.sub(lambda m: mora2phonemes(m.group()), text)
|
| 641 |
+
|
| 642 |
+
# 長音記号「ー」の処理
|
| 643 |
+
long_replacement = lambda m: m.group(1) + (" " + m.group(1)) * len(m.group(2)) # type: ignore
|
| 644 |
+
spaced_phonemes = __LONG_PATTERN.sub(long_replacement, spaced_phonemes)
|
| 645 |
+
|
| 646 |
+
return spaced_phonemes.strip().split(" ")
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def __align_tones(
|
| 650 |
+
phones_with_punct: list[str], phone_tone_list: list[tuple[str, int]]
|
| 651 |
+
) -> list[tuple[str, int]]:
|
| 652 |
+
"""
|
| 653 |
+
例: …私は、、そう思う。
|
| 654 |
+
phones_with_punct:
|
| 655 |
+
[".", ".", ".", "w", "a", "t", "a", "sh", "i", "w", "a", ",", ",", "s", "o", "o", "o", "m", "o", "u", "."]
|
| 656 |
+
phone_tone_list:
|
| 657 |
+
[("w", 0), ("a", 0), ("t", 1), ("a", 1), ("sh", 1), ("i", 1), ("w", 1), ("a", 1), ("_", 0), ("s", 0), ("o", 0), ("o", 1), ("o", 1), ("m", 1), ("o", 1), ("u", 0))]
|
| 658 |
+
Return:
|
| 659 |
+
[(".", 0), (".", 0), (".", 0), ("w", 0), ("a", 0), ("t", 1), ("a", 1), ("sh", 1), ("i", 1), ("w", 1), ("a", 1), (",", 0), (",", 0), ("s", 0), ("o", 0), ("o", 1), ("o", 1), ("m", 1), ("o", 1), ("u", 0), (".", 0)]
|
| 660 |
+
|
| 661 |
+
Args:
|
| 662 |
+
phones_with_punct (list[str]): punctuation を含む音素のリスト
|
| 663 |
+
phone_tone_list (list[tuple[str, int]]): punctuation を含まない音素とアクセントのペアのリスト
|
| 664 |
+
|
| 665 |
+
Returns:
|
| 666 |
+
list[tuple[str, int]]: punctuation を含む音素とアクセントのペアのリスト
|
| 667 |
+
"""
|
| 668 |
+
|
| 669 |
+
result: list[tuple[str, int]] = []
|
| 670 |
+
tone_index = 0
|
| 671 |
+
for phone in phones_with_punct:
|
| 672 |
+
if tone_index >= len(phone_tone_list):
|
| 673 |
+
# 余った punctuation がある場合 → (punctuation, 0) を追加
|
| 674 |
+
result.append((phone, 0))
|
| 675 |
+
elif phone == phone_tone_list[tone_index][0]:
|
| 676 |
+
# phone_tone_list の現在の音素と一致する場合 → tone をそこから取得、(phone, tone) を追加
|
| 677 |
+
result.append((phone, phone_tone_list[tone_index][1]))
|
| 678 |
+
# 探す index を1つ進める
|
| 679 |
+
tone_index += 1
|
| 680 |
+
elif phone in PUNCTUATIONS:
|
| 681 |
+
# phone が punctuation の場合 → (phone, 0) を追加
|
| 682 |
+
result.append((phone, 0))
|
| 683 |
+
else:
|
| 684 |
+
logger.debug(f"phones: {phones_with_punct}")
|
| 685 |
+
logger.debug(f"phone_tone_list: {phone_tone_list}")
|
| 686 |
+
logger.debug(f"result: {result}")
|
| 687 |
+
logger.debug(f"tone_index: {tone_index}")
|
| 688 |
+
logger.debug(f"phone: {phone}")
|
| 689 |
+
raise ValueError(f"Unexpected phone: {phone}")
|
| 690 |
+
|
| 691 |
+
return result
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def __distribute_phone(n_phone: int, n_word: int) -> list[int]:
|
| 695 |
+
"""
|
| 696 |
+
左から右に 1 ずつ振り分け、次にまた左から右に1ずつ増やし、というふうに、
|
| 697 |
+
音素の数 `n_phone` を単語の数 `n_word` に分配する。
|
| 698 |
+
|
| 699 |
+
Args:
|
| 700 |
+
n_phone (int): 音素の数
|
| 701 |
+
n_word (int): 単語の数
|
| 702 |
+
|
| 703 |
+
Returns:
|
| 704 |
+
list[int]: 単語ごとの音素の数のリスト
|
| 705 |
+
"""
|
| 706 |
+
|
| 707 |
+
phones_per_word = [0] * n_word
|
| 708 |
+
for _ in range(n_phone):
|
| 709 |
+
min_tasks = min(phones_per_word)
|
| 710 |
+
min_index = phones_per_word.index(min_tasks)
|
| 711 |
+
phones_per_word[min_index] += 1
|
| 712 |
+
|
| 713 |
+
return phones_per_word
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
class YomiError(Exception):
|
| 717 |
+
"""
|
| 718 |
+
OpenJTalk で、読みが正しく取得できない箇所があるときに発生する例外。
|
| 719 |
+
基本的に「学習の前処理のテキスト処理時」には発生させ、そうでない場合は、
|
| 720 |
+
ignore_yomi_error=True にしておいて、この例外を発生させないようにする。
|
| 721 |
+
"""
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/g2p_utils.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from style_bert_vits2.nlp.japanese.g2p import g2p
|
| 2 |
+
from style_bert_vits2.nlp.japanese.mora_list import (
|
| 3 |
+
CONSONANTS,
|
| 4 |
+
MORA_KATA_TO_MORA_PHONEMES,
|
| 5 |
+
MORA_PHONEMES_TO_MORA_KATA,
|
| 6 |
+
)
|
| 7 |
+
from style_bert_vits2.nlp.symbols import PUNCTUATIONS
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def g2kata_tone(norm_text: str) -> list[tuple[str, int]]:
|
| 11 |
+
"""
|
| 12 |
+
テキストからカタカナとアクセントのペアのリストを返す。
|
| 13 |
+
推論時のみに使われる関数のため、常に `raise_yomi_error=False` を指定して g2p() を呼ぶ仕様になっている。
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
norm_text: 正規化されたテキスト。
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
カタカナと音高のリスト。
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
phones, tones, _ = g2p(norm_text, use_jp_extra=True, raise_yomi_error=False)
|
| 23 |
+
return phone_tone2kata_tone(list(zip(phones, tones)))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def phone_tone2kata_tone(phone_tone: list[tuple[str, int]]) -> list[tuple[str, int]]:
|
| 27 |
+
"""
|
| 28 |
+
phone_tone の phone 部分をカタカナに変換する。ただし最初と最後の ("_", 0) は無視する。
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
phone_tone: 音素と音高のリスト。
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
カタカナと音高のリスト。
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
phone_tone = phone_tone[1:] # 最初の("_", 0)を無視
|
| 38 |
+
phones = [phone for phone, _ in phone_tone]
|
| 39 |
+
tones = [tone for _, tone in phone_tone]
|
| 40 |
+
result: list[tuple[str, int]] = []
|
| 41 |
+
current_mora = ""
|
| 42 |
+
for phone, next_phone, tone, next_tone in zip(phones, phones[1:], tones, tones[1:]):
|
| 43 |
+
# zip の関係で最後の ("_", 0) は無視されている
|
| 44 |
+
if phone in PUNCTUATIONS:
|
| 45 |
+
result.append((phone, tone))
|
| 46 |
+
continue
|
| 47 |
+
if phone in CONSONANTS: # n以外の子音の場合
|
| 48 |
+
assert current_mora == "", f"Unexpected {phone} after {current_mora}"
|
| 49 |
+
assert tone == next_tone, f"Unexpected {phone} tone {tone} != {next_tone}"
|
| 50 |
+
current_mora = phone
|
| 51 |
+
else:
|
| 52 |
+
# phoneが母音もしくは「N」
|
| 53 |
+
current_mora += phone
|
| 54 |
+
result.append((MORA_PHONEMES_TO_MORA_KATA[current_mora], tone))
|
| 55 |
+
current_mora = ""
|
| 56 |
+
|
| 57 |
+
return result
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def kata_tone2phone_tone(kata_tone: list[tuple[str, int]]) -> list[tuple[str, int]]:
|
| 61 |
+
"""
|
| 62 |
+
`phone_tone2kata_tone()` の逆の変換を行う。
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
kata_tone: カタカナと音高のリスト。
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
音素と音高のリスト。
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
result: list[tuple[str, int]] = [("_", 0)]
|
| 72 |
+
for mora, tone in kata_tone:
|
| 73 |
+
if mora in PUNCTUATIONS:
|
| 74 |
+
result.append((mora, tone))
|
| 75 |
+
else:
|
| 76 |
+
consonant, vowel = MORA_KATA_TO_MORA_PHONEMES[mora]
|
| 77 |
+
if consonant is None:
|
| 78 |
+
result.append((vowel, tone))
|
| 79 |
+
else:
|
| 80 |
+
result.append((consonant, tone))
|
| 81 |
+
result.append((vowel, tone))
|
| 82 |
+
result.append(("_", 0))
|
| 83 |
+
|
| 84 |
+
return result
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/mora_list.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
以下のコードは VOICEVOX のソースコードからお借りし最低限の改造を行ったもの。
|
| 3 |
+
https://github.com/VOICEVOX/voicevox_engine/blob/master/voicevox_engine/tts_pipeline/mora_list.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
"""
|
| 7 |
+
以下のモーラ対応表は OpenJTalk のソースコードから取得し、
|
| 8 |
+
カタカナ表記とモーラが一対一対応するように改造した。
|
| 9 |
+
ライセンス表記:
|
| 10 |
+
-----------------------------------------------------------------
|
| 11 |
+
The Japanese TTS System "Open JTalk"
|
| 12 |
+
developed by HTS Working Group
|
| 13 |
+
http://open-jtalk.sourceforge.net/
|
| 14 |
+
-----------------------------------------------------------------
|
| 15 |
+
|
| 16 |
+
Copyright (c) 2008-2014 Nagoya Institute of Technology
|
| 17 |
+
Department of Computer Science
|
| 18 |
+
|
| 19 |
+
All rights reserved.
|
| 20 |
+
|
| 21 |
+
Redistribution and use in source and binary forms, with or
|
| 22 |
+
without modification, are permitted provided that the following
|
| 23 |
+
conditions are met:
|
| 24 |
+
|
| 25 |
+
- Redistributions of source code must retain the above copyright
|
| 26 |
+
notice, this list of conditions and the following disclaimer.
|
| 27 |
+
- Redistributions in binary form must reproduce the above
|
| 28 |
+
copyright notice, this list of conditions and the following
|
| 29 |
+
disclaimer in the documentation and/or other materials provided
|
| 30 |
+
with the distribution.
|
| 31 |
+
- Neither the name of the HTS working group nor the names of its
|
| 32 |
+
contributors may be used to endorse or promote products derived
|
| 33 |
+
from this software without specific prior written permission.
|
| 34 |
+
|
| 35 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
|
| 36 |
+
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
|
| 37 |
+
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
| 38 |
+
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 39 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
|
| 40 |
+
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
| 41 |
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
| 42 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 43 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
| 44 |
+
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 45 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
| 46 |
+
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
| 47 |
+
POSSIBILITY OF SUCH DAMAGE.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
from typing import Optional
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# (カタカナ, 子音, 母音)の順。子音がない場合は None を入れる。
|
| 54 |
+
# 但し「ン」と「ッ」は母音のみという扱いで、「ン」は「N」、「ッ」は「q」とする。
|
| 55 |
+
# (元々「ッ」は「cl」)
|
| 56 |
+
# また「デェ = dy e」は pyopenjtalk の出力(de e)と合わないため削除
|
| 57 |
+
__MORA_LIST_MINIMUM: list[tuple[str, Optional[str], str]] = [
|
| 58 |
+
("ヴォ", "v", "o"),
|
| 59 |
+
("ヴェ", "v", "e"),
|
| 60 |
+
("ヴィ", "v", "i"),
|
| 61 |
+
("ヴァ", "v", "a"),
|
| 62 |
+
("ヴ", "v", "u"),
|
| 63 |
+
("ン", None, "N"),
|
| 64 |
+
("ワ", "w", "a"),
|
| 65 |
+
("ロ", "r", "o"),
|
| 66 |
+
("レ", "r", "e"),
|
| 67 |
+
("ル", "r", "u"),
|
| 68 |
+
("リョ", "ry", "o"),
|
| 69 |
+
("リュ", "ry", "u"),
|
| 70 |
+
("リャ", "ry", "a"),
|
| 71 |
+
("リェ", "ry", "e"),
|
| 72 |
+
("リ", "r", "i"),
|
| 73 |
+
("ラ", "r", "a"),
|
| 74 |
+
("ヨ", "y", "o"),
|
| 75 |
+
("ユ", "y", "u"),
|
| 76 |
+
("ヤ", "y", "a"),
|
| 77 |
+
("モ", "m", "o"),
|
| 78 |
+
("メ", "m", "e"),
|
| 79 |
+
("ム", "m", "u"),
|
| 80 |
+
("ミョ", "my", "o"),
|
| 81 |
+
("ミュ", "my", "u"),
|
| 82 |
+
("ミャ", "my", "a"),
|
| 83 |
+
("ミェ", "my", "e"),
|
| 84 |
+
("ミ", "m", "i"),
|
| 85 |
+
("マ", "m", "a"),
|
| 86 |
+
("ポ", "p", "o"),
|
| 87 |
+
("ボ", "b", "o"),
|
| 88 |
+
("ホ", "h", "o"),
|
| 89 |
+
("ペ", "p", "e"),
|
| 90 |
+
("ベ", "b", "e"),
|
| 91 |
+
("ヘ", "h", "e"),
|
| 92 |
+
("プ", "p", "u"),
|
| 93 |
+
("ブ", "b", "u"),
|
| 94 |
+
("フォ", "f", "o"),
|
| 95 |
+
("フェ", "f", "e"),
|
| 96 |
+
("フィ", "f", "i"),
|
| 97 |
+
("ファ", "f", "a"),
|
| 98 |
+
("フ", "f", "u"),
|
| 99 |
+
("ピョ", "py", "o"),
|
| 100 |
+
("ピュ", "py", "u"),
|
| 101 |
+
("ピャ", "py", "a"),
|
| 102 |
+
("ピェ", "py", "e"),
|
| 103 |
+
("ピ", "p", "i"),
|
| 104 |
+
("ビョ", "by", "o"),
|
| 105 |
+
("ビュ", "by", "u"),
|
| 106 |
+
("ビャ", "by", "a"),
|
| 107 |
+
("ビェ", "by", "e"),
|
| 108 |
+
("ビ", "b", "i"),
|
| 109 |
+
("ヒョ", "hy", "o"),
|
| 110 |
+
("ヒュ", "hy", "u"),
|
| 111 |
+
("ヒャ", "hy", "a"),
|
| 112 |
+
("ヒェ", "hy", "e"),
|
| 113 |
+
("ヒ", "h", "i"),
|
| 114 |
+
("パ", "p", "a"),
|
| 115 |
+
("バ", "b", "a"),
|
| 116 |
+
("ハ", "h", "a"),
|
| 117 |
+
("ノ", "n", "o"),
|
| 118 |
+
("ネ", "n", "e"),
|
| 119 |
+
("ヌ", "n", "u"),
|
| 120 |
+
("ニョ", "ny", "o"),
|
| 121 |
+
("ニュ", "ny", "u"),
|
| 122 |
+
("ニャ", "ny", "a"),
|
| 123 |
+
("ニェ", "ny", "e"),
|
| 124 |
+
("ニ", "n", "i"),
|
| 125 |
+
("ナ", "n", "a"),
|
| 126 |
+
("ドゥ", "d", "u"),
|
| 127 |
+
("ド", "d", "o"),
|
| 128 |
+
("トゥ", "t", "u"),
|
| 129 |
+
("ト", "t", "o"),
|
| 130 |
+
("デョ", "dy", "o"),
|
| 131 |
+
("デュ", "dy", "u"),
|
| 132 |
+
("デャ", "dy", "a"),
|
| 133 |
+
# ("デェ", "dy", "e"),
|
| 134 |
+
("ディ", "d", "i"),
|
| 135 |
+
("デ", "d", "e"),
|
| 136 |
+
("テョ", "ty", "o"),
|
| 137 |
+
("テュ", "ty", "u"),
|
| 138 |
+
("テャ", "ty", "a"),
|
| 139 |
+
("ティ", "t", "i"),
|
| 140 |
+
("テ", "t", "e"),
|
| 141 |
+
("ツォ", "ts", "o"),
|
| 142 |
+
("ツェ", "ts", "e"),
|
| 143 |
+
("ツィ", "ts", "i"),
|
| 144 |
+
("ツァ", "ts", "a"),
|
| 145 |
+
("ツ", "ts", "u"),
|
| 146 |
+
("ッ", None, "q"), # 「cl」から「q」に変更
|
| 147 |
+
("チョ", "ch", "o"),
|
| 148 |
+
("チュ", "ch", "u"),
|
| 149 |
+
("チャ", "ch", "a"),
|
| 150 |
+
("チェ", "ch", "e"),
|
| 151 |
+
("チ", "ch", "i"),
|
| 152 |
+
("ダ", "d", "a"),
|
| 153 |
+
("タ", "t", "a"),
|
| 154 |
+
("ゾ", "z", "o"),
|
| 155 |
+
("ソ", "s", "o"),
|
| 156 |
+
("ゼ", "z", "e"),
|
| 157 |
+
("セ", "s", "e"),
|
| 158 |
+
("ズィ", "z", "i"),
|
| 159 |
+
("ズ", "z", "u"),
|
| 160 |
+
("スィ", "s", "i"),
|
| 161 |
+
("ス", "s", "u"),
|
| 162 |
+
("ジョ", "j", "o"),
|
| 163 |
+
("ジュ", "j", "u"),
|
| 164 |
+
("ジャ", "j", "a"),
|
| 165 |
+
("ジェ", "j", "e"),
|
| 166 |
+
("ジ", "j", "i"),
|
| 167 |
+
("ショ", "sh", "o"),
|
| 168 |
+
("シュ", "sh", "u"),
|
| 169 |
+
("シャ", "sh", "a"),
|
| 170 |
+
("シェ", "sh", "e"),
|
| 171 |
+
("シ", "sh", "i"),
|
| 172 |
+
("ザ", "z", "a"),
|
| 173 |
+
("サ", "s", "a"),
|
| 174 |
+
("ゴ", "g", "o"),
|
| 175 |
+
("コ", "k", "o"),
|
| 176 |
+
("ゲ", "g", "e"),
|
| 177 |
+
("ケ", "k", "e"),
|
| 178 |
+
("グヮ", "gw", "a"),
|
| 179 |
+
("グ", "g", "u"),
|
| 180 |
+
("クヮ", "kw", "a"),
|
| 181 |
+
("ク", "k", "u"),
|
| 182 |
+
("ギョ", "gy", "o"),
|
| 183 |
+
("ギュ", "gy", "u"),
|
| 184 |
+
("ギャ", "gy", "a"),
|
| 185 |
+
("ギェ", "gy", "e"),
|
| 186 |
+
("ギ", "g", "i"),
|
| 187 |
+
("キョ", "ky", "o"),
|
| 188 |
+
("キュ", "ky", "u"),
|
| 189 |
+
("キャ", "ky", "a"),
|
| 190 |
+
("キェ", "ky", "e"),
|
| 191 |
+
("キ", "k", "i"),
|
| 192 |
+
("ガ", "g", "a"),
|
| 193 |
+
("カ", "k", "a"),
|
| 194 |
+
("オ", None, "o"),
|
| 195 |
+
("エ", None, "e"),
|
| 196 |
+
("ウォ", "w", "o"),
|
| 197 |
+
("ウェ", "w", "e"),
|
| 198 |
+
("ウィ", "w", "i"),
|
| 199 |
+
("ウ", None, "u"),
|
| 200 |
+
("イェ", "y", "e"),
|
| 201 |
+
("イ", None, "i"),
|
| 202 |
+
("ア", None, "a"),
|
| 203 |
+
]
|
| 204 |
+
__MORA_LIST_ADDITIONAL: list[tuple[str, Optional[str], str]] = [
|
| 205 |
+
("ヴョ", "by", "o"),
|
| 206 |
+
("ヴュ", "by", "u"),
|
| 207 |
+
("ヴャ", "by", "a"),
|
| 208 |
+
("ヲ", None, "o"),
|
| 209 |
+
("ヱ", None, "e"),
|
| 210 |
+
("ヰ", None, "i"),
|
| 211 |
+
("ヮ", "w", "a"),
|
| 212 |
+
("ョ", "y", "o"),
|
| 213 |
+
("ュ", "y", "u"),
|
| 214 |
+
("ヅ", "z", "u"),
|
| 215 |
+
("ヂ", "j", "i"),
|
| 216 |
+
("ヶ", "k", "e"),
|
| 217 |
+
("ャ", "y", "a"),
|
| 218 |
+
("ォ", None, "o"),
|
| 219 |
+
("ェ", None, "e"),
|
| 220 |
+
("ゥ", None, "u"),
|
| 221 |
+
("ィ", None, "i"),
|
| 222 |
+
("ァ", None, "a"),
|
| 223 |
+
]
|
| 224 |
+
|
| 225 |
+
# モーラの音素表記とカタカナの対応表
|
| 226 |
+
# 例: "vo" -> "ヴォ", "a" -> "ア"
|
| 227 |
+
MORA_PHONEMES_TO_MORA_KATA: dict[str, str] = {
|
| 228 |
+
(consonant or "") + vowel: kana for [kana, consonant, vowel] in __MORA_LIST_MINIMUM
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
# モーラのカタカナ表記と音素の対応表
|
| 232 |
+
# 例: "ヴォ" -> ("v", "o"), "ア" -> (None, "a")
|
| 233 |
+
MORA_KATA_TO_MORA_PHONEMES: dict[str, tuple[Optional[str], str]] = {
|
| 234 |
+
kana: (consonant, vowel)
|
| 235 |
+
for [kana, consonant, vowel] in __MORA_LIST_MINIMUM + __MORA_LIST_ADDITIONAL
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
# 子音の集合
|
| 239 |
+
CONSONANTS = set(
|
| 240 |
+
[
|
| 241 |
+
consonant
|
| 242 |
+
for consonant, _ in MORA_KATA_TO_MORA_PHONEMES.values()
|
| 243 |
+
if consonant is not None
|
| 244 |
+
]
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import unicodedata
|
| 3 |
+
|
| 4 |
+
from num2words import num2words
|
| 5 |
+
|
| 6 |
+
from style_bert_vits2.nlp.symbols import PUNCTUATIONS
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# 記号類の正規化マップ
|
| 10 |
+
__REPLACE_MAP = {
|
| 11 |
+
":": ",",
|
| 12 |
+
";": ",",
|
| 13 |
+
",": ",",
|
| 14 |
+
"。": ".",
|
| 15 |
+
"!": "!",
|
| 16 |
+
"?": "?",
|
| 17 |
+
"\n": ".",
|
| 18 |
+
".": ".",
|
| 19 |
+
"…": "...",
|
| 20 |
+
"···": "...",
|
| 21 |
+
"・・・": "...",
|
| 22 |
+
"·": ",",
|
| 23 |
+
"・": ",",
|
| 24 |
+
"、": ",",
|
| 25 |
+
"$": ".",
|
| 26 |
+
"“": "'",
|
| 27 |
+
"”": "'",
|
| 28 |
+
'"': "'",
|
| 29 |
+
"‘": "'",
|
| 30 |
+
"’": "'",
|
| 31 |
+
"(": "'",
|
| 32 |
+
")": "'",
|
| 33 |
+
"(": "'",
|
| 34 |
+
")": "'",
|
| 35 |
+
"《": "'",
|
| 36 |
+
"》": "'",
|
| 37 |
+
"【": "'",
|
| 38 |
+
"】": "'",
|
| 39 |
+
"[": "'",
|
| 40 |
+
"]": "'",
|
| 41 |
+
# NFKC 正規化後のハイフン・ダッシュの変種を全て通常半角ハイフン - \u002d に変換
|
| 42 |
+
"\u02d7": "\u002d", # ˗, Modifier Letter Minus Sign
|
| 43 |
+
"\u2010": "\u002d", # ‐, Hyphen,
|
| 44 |
+
# "\u2011": "\u002d", # ‑, Non-Breaking Hyphen, NFKC により \u2010 に変換される
|
| 45 |
+
"\u2012": "\u002d", # ‒, Figure Dash
|
| 46 |
+
"\u2013": "\u002d", # –, En Dash
|
| 47 |
+
"\u2014": "\u002d", # —, Em Dash
|
| 48 |
+
"\u2015": "\u002d", # ―, Horizontal Bar
|
| 49 |
+
"\u2043": "\u002d", # ⁃, Hyphen Bullet
|
| 50 |
+
"\u2212": "\u002d", # −, Minus Sign
|
| 51 |
+
"\u23af": "\u002d", # ⎯, Horizontal Line Extension
|
| 52 |
+
"\u23e4": "\u002d", # ⏤, Straightness
|
| 53 |
+
"\u2500": "\u002d", # ─, Box Drawings Light Horizontal
|
| 54 |
+
"\u2501": "\u002d", # ━, Box Drawings Heavy Horizontal
|
| 55 |
+
"\u2e3a": "\u002d", # ⸺, Two-Em Dash
|
| 56 |
+
"\u2e3b": "\u002d", # ⸻, Three-Em Dash
|
| 57 |
+
# "~": "-", # これは長音記号「ー」として扱うよう変更
|
| 58 |
+
# "~": "-", # これも長音記号「ー」として扱うよう変更
|
| 59 |
+
"「": "'",
|
| 60 |
+
"」": "'",
|
| 61 |
+
}
|
| 62 |
+
# 記号類の正規化パターン
|
| 63 |
+
__REPLACE_PATTERN = re.compile("|".join(re.escape(p) for p in __REPLACE_MAP))
|
| 64 |
+
# 句読点等の正規化パターン
|
| 65 |
+
__PUNCTUATION_CLEANUP_PATTERN = re.compile(
|
| 66 |
+
# ↓ ひらがな、カタカナ、漢字
|
| 67 |
+
r"[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u3400-\u4DBF\u3005"
|
| 68 |
+
# ↓ 半角アルファベット(大文字と小文字)
|
| 69 |
+
+ r"\u0041-\u005A\u0061-\u007A"
|
| 70 |
+
# ↓ 全角アルファベット(大文字と小文字)
|
| 71 |
+
+ r"\uFF21-\uFF3A\uFF41-\uFF5A"
|
| 72 |
+
# ↓ ギリシャ文字
|
| 73 |
+
+ r"\u0370-\u03FF\u1F00-\u1FFF"
|
| 74 |
+
# ↓ "!", "?", "…", ",", ".", "'", "-", 但し`…`はすでに`...`に変換されている
|
| 75 |
+
+ "".join(PUNCTUATIONS) + r"]+", # fmt: skip
|
| 76 |
+
)
|
| 77 |
+
# 数字・通貨記号の正規化パターン
|
| 78 |
+
__CURRENCY_MAP = {"$": "ドル", "¥": "円", "£": "ポンド", "€": "ユーロ"}
|
| 79 |
+
__CURRENCY_PATTERN = re.compile(r"([$¥£€])([0-9.]*[0-9])")
|
| 80 |
+
__NUMBER_PATTERN = re.compile(r"[0-9]+(\.[0-9]+)?")
|
| 81 |
+
__NUMBER_WITH_SEPARATOR_PATTERN = re.compile("[0-9]{1,3}(,[0-9]{3})+")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def normalize_text(text: str) -> str:
|
| 85 |
+
"""
|
| 86 |
+
日本語のテキストを正規化する。
|
| 87 |
+
結果は、ちょうど次の文字のみからなる:
|
| 88 |
+
- ひらがな
|
| 89 |
+
- カタカナ(全角長音記号「ー」が入る!)
|
| 90 |
+
- 漢字
|
| 91 |
+
- 半角アルファベット(大文字と小文字)
|
| 92 |
+
- ギリシャ文字
|
| 93 |
+
- `.` (句点`。`や`…`の一部や改行等)
|
| 94 |
+
- `,` (読点`、`や`:`等)
|
| 95 |
+
- `?` (疑問符`?`)
|
| 96 |
+
- `!` (感嘆符`!`)
|
| 97 |
+
- `'` (`「`や`」`等)
|
| 98 |
+
- `-` (`―`(ダッシュ、長音記号ではない)や`-`等)
|
| 99 |
+
|
| 100 |
+
注意点:
|
| 101 |
+
- 三点リーダー`…`は`...`に変換される(`なるほど…。` → `なるほど....`)
|
| 102 |
+
- 数字は漢字に変換される(`1,100円` → `千百円`、`52.34` → `五十二点三四`)
|
| 103 |
+
- 読点や疑問符等の位置・個数等は保持される(`??あ、、!!!` → `??あ,,!!!`)
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
text (str): 正規化するテキスト
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
str: 正規化されたテキスト
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
res = unicodedata.normalize("NFKC", text) # ここでアルファベットは半角になる
|
| 113 |
+
res = __convert_numbers_to_words(res) # 「100円」→「百円」等
|
| 114 |
+
# 「~」と「〜」と「~」も長音記号として扱う
|
| 115 |
+
res = res.replace("~", "ー")
|
| 116 |
+
res = res.replace("~", "ー")
|
| 117 |
+
res = res.replace("〜", "ー")
|
| 118 |
+
|
| 119 |
+
res = replace_punctuation(res) # 句読点等正規化、読めない文字を削除
|
| 120 |
+
|
| 121 |
+
# 結合文字の濁点・半濁点を削除
|
| 122 |
+
# 通常の「ば」等はそのままのこされる、「あ゛」は上で「あ゙」になりここで「あ」になる
|
| 123 |
+
res = res.replace("\u3099", "") # 結合文字の濁点を削除、る゙ → る
|
| 124 |
+
res = res.replace("\u309A", "") # 結合文字の半濁点を削除、な゚ → な
|
| 125 |
+
return res
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def replace_punctuation(text: str) -> str:
|
| 129 |
+
"""
|
| 130 |
+
句読点等を「.」「,」「!」「?」「'」「-」に正規化し、OpenJTalk で読みが取得できるもののみ残す:
|
| 131 |
+
漢字・平仮名・カタカナ、アルファベット、ギリシャ文字
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
text (str): ��規化するテキスト
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
str: 正規化されたテキスト
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
# 句読点を辞書で置換
|
| 141 |
+
replaced_text = __REPLACE_PATTERN.sub(lambda x: __REPLACE_MAP[x.group()], text)
|
| 142 |
+
|
| 143 |
+
# 上述以外の文字を削除
|
| 144 |
+
replaced_text = __PUNCTUATION_CLEANUP_PATTERN.sub("", replaced_text)
|
| 145 |
+
|
| 146 |
+
return replaced_text
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def __convert_numbers_to_words(text: str) -> str:
|
| 150 |
+
"""
|
| 151 |
+
記号や数字を日本語の文字表現に変換する。
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
text (str): 変換するテキスト
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
str: 変換されたテキスト
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
res = __NUMBER_WITH_SEPARATOR_PATTERN.sub(lambda m: m[0].replace(",", ""), text)
|
| 161 |
+
res = __CURRENCY_PATTERN.sub(lambda m: m[2] + __CURRENCY_MAP.get(m[1], m[1]), res)
|
| 162 |
+
res = __NUMBER_PATTERN.sub(lambda m: num2words(m[0], lang="ja"), res)
|
| 163 |
+
|
| 164 |
+
return res
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/pyopenjtalk_worker/__init__.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Run the pyopenjtalk worker in a separate process
|
| 3 |
+
to avoid user dictionary access error
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Any, Optional
|
| 7 |
+
|
| 8 |
+
from style_bert_vits2.logging import logger
|
| 9 |
+
from style_bert_vits2.nlp.japanese.pyopenjtalk_worker.worker_client import WorkerClient
|
| 10 |
+
from style_bert_vits2.nlp.japanese.pyopenjtalk_worker.worker_common import WORKER_PORT
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
WORKER_CLIENT: Optional[WorkerClient] = None
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# pyopenjtalk interface
|
| 17 |
+
# g2p(): not used
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def run_frontend(text: str) -> list[dict[str, Any]]:
|
| 21 |
+
if WORKER_CLIENT is not None:
|
| 22 |
+
ret = WORKER_CLIENT.dispatch_pyopenjtalk("run_frontend", text)
|
| 23 |
+
assert isinstance(ret, list)
|
| 24 |
+
return ret
|
| 25 |
+
else:
|
| 26 |
+
# without worker
|
| 27 |
+
import pyopenjtalk
|
| 28 |
+
|
| 29 |
+
return pyopenjtalk.run_frontend(text)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def make_label(njd_features: Any) -> list[str]:
|
| 33 |
+
if WORKER_CLIENT is not None:
|
| 34 |
+
ret = WORKER_CLIENT.dispatch_pyopenjtalk("make_label", njd_features)
|
| 35 |
+
assert isinstance(ret, list)
|
| 36 |
+
return ret
|
| 37 |
+
else:
|
| 38 |
+
# without worker
|
| 39 |
+
import pyopenjtalk
|
| 40 |
+
|
| 41 |
+
return pyopenjtalk.make_label(njd_features)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def mecab_dict_index(path: str, out_path: str, dn_mecab: Optional[str] = None) -> None:
|
| 45 |
+
if WORKER_CLIENT is not None:
|
| 46 |
+
WORKER_CLIENT.dispatch_pyopenjtalk("mecab_dict_index", path, out_path, dn_mecab)
|
| 47 |
+
else:
|
| 48 |
+
# without worker
|
| 49 |
+
import pyopenjtalk
|
| 50 |
+
|
| 51 |
+
pyopenjtalk.mecab_dict_index(path, out_path, dn_mecab)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def update_global_jtalk_with_user_dict(path: str) -> None:
|
| 55 |
+
if WORKER_CLIENT is not None:
|
| 56 |
+
WORKER_CLIENT.dispatch_pyopenjtalk("update_global_jtalk_with_user_dict", path)
|
| 57 |
+
else:
|
| 58 |
+
# without worker
|
| 59 |
+
import pyopenjtalk
|
| 60 |
+
|
| 61 |
+
pyopenjtalk.update_global_jtalk_with_user_dict(path)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def unset_user_dict() -> None:
|
| 65 |
+
if WORKER_CLIENT is not None:
|
| 66 |
+
WORKER_CLIENT.dispatch_pyopenjtalk("unset_user_dict")
|
| 67 |
+
else:
|
| 68 |
+
# without worker
|
| 69 |
+
import pyopenjtalk
|
| 70 |
+
|
| 71 |
+
pyopenjtalk.unset_user_dict()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# initialize module when imported
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def initialize_worker(port: int = WORKER_PORT) -> None:
|
| 78 |
+
import atexit
|
| 79 |
+
import signal
|
| 80 |
+
import socket
|
| 81 |
+
import sys
|
| 82 |
+
import time
|
| 83 |
+
|
| 84 |
+
global WORKER_CLIENT
|
| 85 |
+
if WORKER_CLIENT:
|
| 86 |
+
return
|
| 87 |
+
|
| 88 |
+
client = None
|
| 89 |
+
try:
|
| 90 |
+
client = WorkerClient(port)
|
| 91 |
+
except (OSError, socket.timeout):
|
| 92 |
+
logger.debug("try starting pyopenjtalk worker server")
|
| 93 |
+
import os
|
| 94 |
+
import subprocess
|
| 95 |
+
|
| 96 |
+
worker_pkg_path = os.path.relpath(
|
| 97 |
+
os.path.dirname(__file__), os.getcwd()
|
| 98 |
+
).replace(os.sep, ".")
|
| 99 |
+
args = [sys.executable, "-m", worker_pkg_path, "--port", str(port)]
|
| 100 |
+
# new session, new process group
|
| 101 |
+
if sys.platform.startswith("win"):
|
| 102 |
+
cf = subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
|
| 103 |
+
si = subprocess.STARTUPINFO() # type: ignore
|
| 104 |
+
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW # type: ignore
|
| 105 |
+
si.wShowWindow = subprocess.SW_HIDE # type: ignore
|
| 106 |
+
subprocess.Popen(args, creationflags=cf, startupinfo=si)
|
| 107 |
+
else:
|
| 108 |
+
# align with Windows behavior
|
| 109 |
+
# start_new_session is same as specifying setsid in preexec_fn
|
| 110 |
+
subprocess.Popen(
|
| 111 |
+
args,
|
| 112 |
+
stdout=subprocess.DEVNULL,
|
| 113 |
+
stderr=subprocess.DEVNULL,
|
| 114 |
+
start_new_session=True,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# wait until server listening
|
| 118 |
+
count = 0
|
| 119 |
+
while True:
|
| 120 |
+
try:
|
| 121 |
+
client = WorkerClient(port)
|
| 122 |
+
break
|
| 123 |
+
except OSError:
|
| 124 |
+
time.sleep(0.5)
|
| 125 |
+
count += 1
|
| 126 |
+
# 20: max number of retries
|
| 127 |
+
if count == 20:
|
| 128 |
+
raise TimeoutError("サーバーに接続できませんでした")
|
| 129 |
+
|
| 130 |
+
logger.debug("pyopenjtalk worker server started")
|
| 131 |
+
WORKER_CLIENT = client
|
| 132 |
+
atexit.register(terminate_worker)
|
| 133 |
+
|
| 134 |
+
# when the process is killed
|
| 135 |
+
def signal_handler(signum: int, frame: Any):
|
| 136 |
+
terminate_worker()
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
signal.signal(signal.SIGTERM, signal_handler)
|
| 140 |
+
except ValueError:
|
| 141 |
+
# signal only works in main thread
|
| 142 |
+
pass
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# top-level declaration
|
| 146 |
+
def terminate_worker() -> None:
|
| 147 |
+
logger.debug("pyopenjtalk worker server terminated")
|
| 148 |
+
global WORKER_CLIENT
|
| 149 |
+
if not WORKER_CLIENT:
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
# prepare for unexpected errors
|
| 153 |
+
try:
|
| 154 |
+
if WORKER_CLIENT.status() == 1:
|
| 155 |
+
WORKER_CLIENT.quit_server()
|
| 156 |
+
except Exception as e:
|
| 157 |
+
logger.error(e)
|
| 158 |
+
|
| 159 |
+
WORKER_CLIENT.close()
|
| 160 |
+
WORKER_CLIENT = None
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/pyopenjtalk_worker/__main__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
|
| 3 |
+
from style_bert_vits2.nlp.japanese.pyopenjtalk_worker.worker_common import WORKER_PORT
|
| 4 |
+
from style_bert_vits2.nlp.japanese.pyopenjtalk_worker.worker_server import WorkerServer
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def main() -> None:
|
| 8 |
+
parser = argparse.ArgumentParser()
|
| 9 |
+
parser.add_argument("--port", type=int, default=WORKER_PORT)
|
| 10 |
+
args = parser.parse_args()
|
| 11 |
+
server = WorkerServer()
|
| 12 |
+
server.start_server(port=args.port)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if __name__ == "__main__":
|
| 16 |
+
main()
|
Mutsumi-Chan/NSW-CHUPA/style_bert_vits2/nlp/japanese/pyopenjtalk_worker/worker_client.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import socket
|
| 2 |
+
from typing import Any, cast
|
| 3 |
+
|
| 4 |
+
from style_bert_vits2.logging import logger
|
| 5 |
+
from style_bert_vits2.nlp.japanese.pyopenjtalk_worker.worker_common import (
|
| 6 |
+
RequestType,
|
| 7 |
+
receive_data,
|
| 8 |
+
send_data,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class WorkerClient:
|
| 13 |
+
"""pyopenjtalk worker client"""
|
| 14 |
+
|
| 15 |
+
def __init__(self, port: int) -> None:
|
| 16 |
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 17 |
+
# timeout: 60 seconds
|
| 18 |
+
sock.settimeout(60)
|
| 19 |
+
sock.connect((socket.gethostname(), port))
|
| 20 |
+
self.sock = sock
|
| 21 |
+
|
| 22 |
+
def __enter__(self) -> "WorkerClient":
|
| 23 |
+
return self
|
| 24 |
+
|
| 25 |
+
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
| 26 |
+
self.close()
|
| 27 |
+
|
| 28 |
+
def close(self) -> None:
|
| 29 |
+
self.sock.close()
|
| 30 |
+
|
| 31 |
+
def dispatch_pyopenjtalk(self, func: str, *args: Any, **kwargs: Any) -> Any:
|
| 32 |
+
data = {
|
| 33 |
+
"request-type": RequestType.PYOPENJTALK,
|
| 34 |
+
"func": func,
|
| 35 |
+
"args": args,
|
| 36 |
+
"kwargs": kwargs,
|
| 37 |
+
}
|
| 38 |
+
logger.trace(f"client sends request: {data}")
|
| 39 |
+
send_data(self.sock, data)
|
| 40 |
+
logger.trace("client sent request successfully")
|
| 41 |
+
response = receive_data(self.sock)
|
| 42 |
+
logger.trace(f"client received response: {response}")
|
| 43 |
+
return response.get("return")
|
| 44 |
+
|
| 45 |
+
def status(self) -> int:
|
| 46 |
+
data = {"request-type": RequestType.STATUS}
|
| 47 |
+
logger.trace(f"client sends request: {data}")
|
| 48 |
+
send_data(self.sock, data)
|
| 49 |
+
logger.trace("client sent request successfully")
|
| 50 |
+
response = receive_data(self.sock)
|
| 51 |
+
logger.trace(f"client received response: {response}")
|
| 52 |
+
return cast(int, response.get("client-count"))
|
| 53 |
+
|
| 54 |
+
def quit_server(self) -> None:
|
| 55 |
+
data = {"request-type": RequestType.QUIT_SERVER}
|
| 56 |
+
logger.trace(f"client sends request: {data}")
|
| 57 |
+
send_data(self.sock, data)
|
| 58 |
+
logger.trace("client sent request successfully")
|
| 59 |
+
response = receive_data(self.sock)
|
| 60 |
+
logger.trace(f"client received response: {response}")
|