Plana-Archive commited on
Commit
42de7f7
·
verified ·
1 Parent(s): 20d204d

Migrated content from Space: Plana-Archive/VITS-Umamusume-Voice

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -0
  2. Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_infer.py +201 -0
  3. Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_inference.py +36 -0
  4. Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_models.py +361 -0
  5. Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_modules.py +280 -0
  6. Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_to_onnx.py +31 -0
  7. Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_transforms.py +196 -0
  8. Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_utils.py +19 -0
  9. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/dec.onnx +3 -0
  10. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/dp.onnx +3 -0
  11. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/enc_p.onnx +3 -0
  12. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/flow.onnx +3 -0
  13. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/plana +1 -0
  14. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_trilingual/dec.onnx +3 -0
  15. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_trilingual/dp.onnx +3 -0
  16. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_trilingual/enc_p.onnx +3 -0
  17. Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_trilingual/flow.onnx +3 -0
  18. Mutsumi-Chan/VITS-Umamusume-Voice/README.md +16 -0
  19. Mutsumi-Chan/VITS-Umamusume-Voice/app.py +304 -0
  20. Mutsumi-Chan/VITS-Umamusume-Voice/app.py (versi sebelumnya) +361 -0
  21. Mutsumi-Chan/VITS-Umamusume-Voice/attentions.py +300 -0
  22. Mutsumi-Chan/VITS-Umamusume-Voice/commons.py +97 -0
  23. Mutsumi-Chan/VITS-Umamusume-Voice/configs/uma87.json +133 -0
  24. Mutsumi-Chan/VITS-Umamusume-Voice/configs/uma_trilingual.json +202 -0
  25. Mutsumi-Chan/VITS-Umamusume-Voice/cover.png +3 -0
  26. Mutsumi-Chan/VITS-Umamusume-Voice/data_utils.py +393 -0
  27. Mutsumi-Chan/VITS-Umamusume-Voice/haru-urara-concert.gif +3 -0
  28. Mutsumi-Chan/VITS-Umamusume-Voice/hubert_model.py +221 -0
  29. Mutsumi-Chan/VITS-Umamusume-Voice/jieba/dict.txt +0 -0
  30. Mutsumi-Chan/VITS-Umamusume-Voice/losses.py +61 -0
  31. Mutsumi-Chan/VITS-Umamusume-Voice/mel_processing.py +101 -0
  32. Mutsumi-Chan/VITS-Umamusume-Voice/models.py +542 -0
  33. Mutsumi-Chan/VITS-Umamusume-Voice/modules.py +387 -0
  34. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/__init__.py +19 -0
  35. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/__pycache__/__init__.cpython-37.pyc +0 -0
  36. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/lib.win-amd64-cpython-37/monotonic_align/core.cp37-win_amd64.pyd +3 -0
  37. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.exp +0 -0
  38. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.lib +0 -0
  39. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/temp.win-amd64-cpython-37/Release/core.obj +3 -0
  40. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/core.c +0 -0
  41. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/core.pyx +42 -0
  42. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/monotonic_align/core.cp37-win_amd64.pyd +3 -0
  43. Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/setup.py +9 -0
  44. Mutsumi-Chan/VITS-Umamusume-Voice/packages.txt +5 -0
  45. Mutsumi-Chan/VITS-Umamusume-Voice/pretrained_models/D_trilingual.pth +3 -0
  46. Mutsumi-Chan/VITS-Umamusume-Voice/pretrained_models/G_jp.pth +3 -0
  47. Mutsumi-Chan/VITS-Umamusume-Voice/pretrained_models/G_trilingual.pth +3 -0
  48. Mutsumi-Chan/VITS-Umamusume-Voice/requirements.txt +40 -0
  49. Mutsumi-Chan/VITS-Umamusume-Voice/text/LICENSE.txt +19 -0
  50. Mutsumi-Chan/VITS-Umamusume-Voice/text/__init__.py +32 -0
.gitattributes CHANGED
@@ -169,3 +169,8 @@ Blue-Archive/Library-VITS/MyGO-Bert-VITS2/Data/Bushiroad/classifedSample/花音/
169
  Blue-Archive/Library-VITS/MyGO-Bert-VITS2/Data/Bushiroad/classifedSample/花音/class2/event185-04-045.wav filter=lfs diff=lfs merge=lfs -text
170
  Blue-Archive/Library-VITS/MyGO-Bert-VITS2/Data/Bushiroad/classifedSample/花音/class2/event28-01-031.wav filter=lfs diff=lfs merge=lfs -text
171
  Blue-Archive/Library-VITS/MyGO-Bert-VITS2/Data/Bushiroad/classifedSample/花音/class2/event68-01-014.wav filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
169
  Blue-Archive/Library-VITS/MyGO-Bert-VITS2/Data/Bushiroad/classifedSample/花音/class2/event185-04-045.wav filter=lfs diff=lfs merge=lfs -text
170
  Blue-Archive/Library-VITS/MyGO-Bert-VITS2/Data/Bushiroad/classifedSample/花音/class2/event28-01-031.wav filter=lfs diff=lfs merge=lfs -text
171
  Blue-Archive/Library-VITS/MyGO-Bert-VITS2/Data/Bushiroad/classifedSample/花音/class2/event68-01-014.wav filter=lfs diff=lfs merge=lfs -text
172
+ Mutsumi-Chan/VITS-Umamusume-Voice/cover.png filter=lfs diff=lfs merge=lfs -text
173
+ Mutsumi-Chan/VITS-Umamusume-Voice/haru-urara-concert.gif 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
Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_infer.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import commons
3
+ import models
4
+
5
+ import math
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ import modules
10
+ import attentions
11
+
12
+ from torch.nn import Conv1d, ConvTranspose1d, Conv2d
13
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
14
+ from commons import init_weights, get_padding
15
+
16
+
17
+ class TextEncoder(nn.Module):
18
+ def __init__(self,
19
+ n_vocab,
20
+ out_channels,
21
+ hidden_channels,
22
+ filter_channels,
23
+ n_heads,
24
+ n_layers,
25
+ kernel_size,
26
+ p_dropout,
27
+ emotion_embedding):
28
+ super().__init__()
29
+ self.n_vocab = n_vocab
30
+ self.out_channels = out_channels
31
+ self.hidden_channels = hidden_channels
32
+ self.filter_channels = filter_channels
33
+ self.n_heads = n_heads
34
+ self.n_layers = n_layers
35
+ self.kernel_size = kernel_size
36
+ self.p_dropout = p_dropout
37
+ self.emotion_embedding = emotion_embedding
38
+
39
+ if self.n_vocab != 0:
40
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
41
+ if emotion_embedding:
42
+ self.emo_proj = nn.Linear(1024, hidden_channels)
43
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5)
44
+
45
+ self.encoder = attentions.Encoder(
46
+ hidden_channels,
47
+ filter_channels,
48
+ n_heads,
49
+ n_layers,
50
+ kernel_size,
51
+ p_dropout)
52
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
53
+
54
+ def forward(self, x, x_lengths, emotion_embedding=None):
55
+ if self.n_vocab != 0:
56
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
57
+ if emotion_embedding is not None:
58
+ print("emotion added")
59
+ x = x + self.emo_proj(emotion_embedding.unsqueeze(1))
60
+ x = torch.transpose(x, 1, -1) # [b, h, t]
61
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
62
+
63
+ x = self.encoder(x * x_mask, x_mask)
64
+ stats = self.proj(x) * x_mask
65
+
66
+ m, logs = torch.split(stats, self.out_channels, dim=1)
67
+ return x, m, logs, x_mask
68
+
69
+
70
+ class PosteriorEncoder(nn.Module):
71
+ def __init__(self,
72
+ in_channels,
73
+ out_channels,
74
+ hidden_channels,
75
+ kernel_size,
76
+ dilation_rate,
77
+ n_layers,
78
+ gin_channels=0):
79
+ super().__init__()
80
+ self.in_channels = in_channels
81
+ self.out_channels = out_channels
82
+ self.hidden_channels = hidden_channels
83
+ self.kernel_size = kernel_size
84
+ self.dilation_rate = dilation_rate
85
+ self.n_layers = n_layers
86
+ self.gin_channels = gin_channels
87
+
88
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
89
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
90
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
91
+
92
+ def forward(self, x, x_lengths, g=None):
93
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
94
+ x = self.pre(x) * x_mask
95
+ x = self.enc(x, x_mask, g=g)
96
+ stats = self.proj(x) * x_mask
97
+ m, logs = torch.split(stats, self.out_channels, dim=1)
98
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
99
+ return z, m, logs, x_mask
100
+
101
+
102
+ class SynthesizerTrn(models.SynthesizerTrn):
103
+ """
104
+ Synthesizer for Training
105
+ """
106
+
107
+ def __init__(self,
108
+ n_vocab,
109
+ spec_channels,
110
+ segment_size,
111
+ inter_channels,
112
+ hidden_channels,
113
+ filter_channels,
114
+ n_heads,
115
+ n_layers,
116
+ kernel_size,
117
+ p_dropout,
118
+ resblock,
119
+ resblock_kernel_sizes,
120
+ resblock_dilation_sizes,
121
+ upsample_rates,
122
+ upsample_initial_channel,
123
+ upsample_kernel_sizes,
124
+ n_speakers=0,
125
+ gin_channels=0,
126
+ use_sdp=True,
127
+ emotion_embedding=False,
128
+ ONNX_dir="./ONNX_net/",
129
+ **kwargs):
130
+
131
+ super().__init__(
132
+ n_vocab,
133
+ spec_channels,
134
+ segment_size,
135
+ inter_channels,
136
+ hidden_channels,
137
+ filter_channels,
138
+ n_heads,
139
+ n_layers,
140
+ kernel_size,
141
+ p_dropout,
142
+ resblock,
143
+ resblock_kernel_sizes,
144
+ resblock_dilation_sizes,
145
+ upsample_rates,
146
+ upsample_initial_channel,
147
+ upsample_kernel_sizes,
148
+ n_speakers=n_speakers,
149
+ gin_channels=gin_channels,
150
+ use_sdp=use_sdp,
151
+ **kwargs
152
+ )
153
+ self.ONNX_dir = ONNX_dir
154
+ self.enc_p = TextEncoder(n_vocab,
155
+ inter_channels,
156
+ hidden_channels,
157
+ filter_channels,
158
+ n_heads,
159
+ n_layers,
160
+ kernel_size,
161
+ p_dropout,
162
+ emotion_embedding)
163
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
164
+
165
+ def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None,
166
+ emotion_embedding=None):
167
+ from ONNXVITS_utils import runonnx
168
+ with torch.no_grad():
169
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, emotion_embedding)
170
+
171
+ if self.n_speakers > 0:
172
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
173
+ else:
174
+ g = None
175
+
176
+ # logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
177
+ logw = runonnx(f"{self.ONNX_dir}dp.onnx", x=x.numpy(), x_mask=x_mask.numpy(), g=g.numpy())
178
+ logw = torch.from_numpy(logw[0])
179
+
180
+ w = torch.exp(logw) * x_mask * length_scale
181
+ w_ceil = torch.ceil(w)
182
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
183
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
184
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
185
+ attn = commons.generate_path(w_ceil, attn_mask)
186
+
187
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
188
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1,
189
+ 2) # [b, t', t], [b, t, d] -> [b, d, t']
190
+
191
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
192
+
193
+ # z = self.flow(z_p, y_mask, g=g, reverse=True)
194
+ z = runonnx(f"{self.ONNX_dir}flow.onnx", z_p=z_p.numpy(), y_mask=y_mask.numpy(), g=g.numpy())
195
+ z = torch.from_numpy(z[0])
196
+
197
+ # o = self.dec((z * y_mask)[:,:,:max_len], g=g)
198
+ o = runonnx(f"{self.ONNX_dir}dec.onnx", z_in=(z * y_mask)[:, :, :max_len].numpy(), g=g.numpy())
199
+ o = torch.from_numpy(o[0])
200
+
201
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_inference.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ logging.getLogger('numba').setLevel(logging.WARNING)
3
+ import IPython.display as ipd
4
+ import torch
5
+ import commons
6
+ import utils
7
+ import ONNXVITS_infer
8
+ from text import text_to_sequence
9
+
10
+ def get_text(text, hps):
11
+ text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
12
+ if hps.data.add_blank:
13
+ text_norm = commons.intersperse(text_norm, 0)
14
+ text_norm = torch.LongTensor(text_norm)
15
+ return text_norm
16
+
17
+ hps = utils.get_hparams_from_file("../vits/pretrained_models/uma87.json")
18
+
19
+ net_g = ONNXVITS_infer.SynthesizerTrn(
20
+ len(hps.symbols),
21
+ hps.data.filter_length // 2 + 1,
22
+ hps.train.segment_size // hps.data.hop_length,
23
+ n_speakers=hps.data.n_speakers,
24
+ **hps.model)
25
+ _ = net_g.eval()
26
+
27
+ _ = utils.load_checkpoint("../vits/pretrained_models/uma_1153000.pth", net_g)
28
+
29
+ text1 = get_text("おはようございます。", hps)
30
+ stn_tst = text1
31
+ with torch.no_grad():
32
+ x_tst = stn_tst.unsqueeze(0)
33
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)])
34
+ sid = torch.LongTensor([0])
35
+ audio = net_g.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8, length_scale=1)[0][0,0].data.cpu().float().numpy()
36
+ print(audio)
Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_models.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+ import commons
5
+ import utils
6
+ from models import SynthesizerTrn
7
+ import numpy as np
8
+ import json
9
+ import requests
10
+ import logging
11
+ import sys
12
+ import argparse
13
+ import time
14
+ from torch import no_grad, LongTensor
15
+ from text import text_to_sequence
16
+
17
+ # --- Setup Logging ---
18
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # --- Konfigurasi Model ---
22
+ BASE_URL = "https://huggingface.co/spaces/Plana-Archive/VITS-Umamusume-Voice/resolve/main"
23
+ MODELS_CONFIG = [
24
+ {
25
+ "name": "Trilingual",
26
+ "model_file": "G_trilingual.pth",
27
+ "config_file": "uma_trilingual.json",
28
+ "display_name": "🦄 Trilingual Model",
29
+ "languages": ["日本語", "简体中文", "English", "Mix"],
30
+ },
31
+ {
32
+ "name": "Japanese",
33
+ "model_file": "G_jp.pth",
34
+ "config_file": "uma87.json",
35
+ "display_name": "🇯🇵 Japanese Model",
36
+ "languages": ["Japanese"],
37
+ }
38
+ ]
39
+
40
+ LOCAL_DIR, CONFIG_DIR = "pretrained_models", "configs"
41
+ DEFAULT_COVER = "https://huggingface.co/spaces/Plana-Archive/VITS-Umamusume-Voice/resolve/main/cover.png"
42
+
43
+ def download_file(url, local_path):
44
+ if os.path.exists(local_path): return True
45
+ try:
46
+ response = requests.get(url, stream=True)
47
+ os.makedirs(os.path.dirname(local_path), exist_ok=True)
48
+ with open(local_path, 'wb') as f:
49
+ for chunk in response.iter_content(chunk_size=8192): f.write(chunk)
50
+ return True
51
+ except: return False
52
+
53
+ def get_text(text, hps):
54
+ text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
55
+ if hps.data.add_blank: text_norm = commons.intersperse(text_norm, 0)
56
+ return LongTensor(text_norm)
57
+
58
+ # --- Load Models Backend ---
59
+ loaded_models = []
60
+ for cfg in MODELS_CONFIG:
61
+ m_p, c_p = os.path.join(LOCAL_DIR, cfg["model_file"]), os.path.join(CONFIG_DIR, cfg["config_file"])
62
+ download_file(f"{BASE_URL}/pretrained_models/{cfg['model_file']}", m_p)
63
+ download_file(f"{BASE_URL}/configs/{cfg['config_file']}", c_p)
64
+ try:
65
+ hps = utils.get_hparams_from_file(c_p)
66
+ net_g = SynthesizerTrn(len(hps.symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, **hps.model)
67
+ utils.load_checkpoint(m_p, net_g, None)
68
+ net_g.eval()
69
+ loaded_models.append({
70
+ "cfg": cfg, "model": net_g, "hps": hps,
71
+ "display_name": cfg["display_name"],
72
+ "speakers": list(hps.speakers.keys()),
73
+ "cleaned_speakers": [s.split('(')[0].strip() for s in hps.speakers.keys()]
74
+ })
75
+ except Exception as e: print(f"Error load {cfg['name']}: {e}")
76
+
77
+ def update_model_ui(model_name):
78
+ m = next((x for x in loaded_models if x["display_name"] == model_name), loaded_models[0])
79
+ return (
80
+ gr.update(choices=m["cleaned_speakers"], value=m["cleaned_speakers"][0]),
81
+ gr.update(choices=m["cfg"]["languages"], value=m["cfg"]["languages"][0]),
82
+ f"⚡ **SYSTEM STATUS**\n● Models: ✅ LOADED\n● Total Models: {len(loaded_models)}\n● Total Speakers: {len(m['speakers'])}"
83
+ )
84
+
85
+ def generate_voice(model_name, text, speaker, lang, speed):
86
+ if not text: return None, "⚠️ Tolong Isi teks dulu kak, yah! ⚠️"
87
+ try:
88
+ m = next((x for x in loaded_models if x["display_name"] == model_name), loaded_models[0])
89
+ full_speaker_name = next(s for s in m["speakers"] if speaker in s)
90
+ speaker_id = m["hps"].speakers[full_speaker_name]
91
+ stn_tst = get_text(text, m["hps"])
92
+ with no_grad():
93
+ x_tst = stn_tst.unsqueeze(0)
94
+ x_tst_lengths = LongTensor([stn_tst.size(0)])
95
+ sid = LongTensor([speaker_id])
96
+ audio = m["model"].infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8, length_scale=1.0/speed)[0][0,0].data.cpu().float().numpy()
97
+ audio = (audio / np.abs(audio).max() * 32767).astype(np.int16)
98
+ return (m["hps"].data.sampling_rate, audio), "✅ Berhasil dibuat!"
99
+ except Exception as e: return None, f"❌ Error: {str(e)}"
100
+
101
+ # ============================================
102
+ # UI INTERFACE
103
+ # ============================================
104
+ with gr.Blocks(css="""
105
+ @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;800&family=Dancing+Script:wght@600&display=swap');
106
+ body { background-color: #fff8f9; font-family: 'Plus Jakarta Sans', sans-serif; }
107
+
108
+ :root { --loader-color: #ff4d6d !important; --primary-500: #ff4d6d !important; }
109
+
110
+ /* CUSTOM LOADER */
111
+ #custom-loader {
112
+ position: fixed; top: 0; left: 0; width: 100%; height: 100%;
113
+ background: radial-gradient(circle, #ffffff 0%, #fff0f3 100%);
114
+ display: flex; flex-direction: column;
115
+ justify-content: center; align-items: center; z-index: 99999;
116
+ transition: opacity 0.8s ease-out;
117
+ }
118
+ .unicorn-bounce {
119
+ font-size: 80px; animation: bounce 0.6s infinite alternate;
120
+ filter: drop-shadow(0 10px 10px rgba(255, 77, 109, 0.2));
121
+ }
122
+ @keyframes bounce { from { transform: translateY(0); } to { transform: translateY(-30px); } }
123
+ .loading-bar-container { width: 200px; height: 6px; background: #ffeef2; border-radius: 10px; margin-top: 20px; overflow: hidden; }
124
+ .loading-bar-progress { width: 100%; height: 100%; background: linear-gradient(90deg, #ff758c, #ff4d6d); animation: loadingLine 2s infinite ease-in-out; transform-origin: left; }
125
+ @keyframes loadingLine { 0% { transform: scaleX(0); } 50% { transform: scaleX(1); } 100% { transform: scaleX(0); transform-origin: right; } }
126
+
127
+ .header-container { text-align: center; padding: 20px 0; }
128
+ .main-title {
129
+ font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;
130
+ font-size: clamp(1.8rem, 8vw, 2.8rem);
131
+ color: #ff4d6d; display: inline-block;
132
+ background: linear-gradient(to bottom, #ff758c 0%, #ff4d6d 100%);
133
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent;
134
+ line-height: 1.1; margin: 0;
135
+ }
136
+
137
+ /* UPDATE: HIJAU TEBAL TANPA SHADOW/LIGHT */
138
+ .sub-title-green {
139
+ font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;
140
+ font-size: clamp(1.2rem, 5vw, 1.8rem);
141
+ color: #32CD32; /* LimeGreen yang padat */
142
+ text-shadow: none !important; /* Hapus semua bayangan */
143
+ text-transform: uppercase; margin: 5px 0;
144
+ }
145
+
146
+ .glow-card {
147
+ background: white !important; border-radius: 30px !important;
148
+ border: 2px solid #ffeef2 !important;
149
+ box-shadow: 0 15px 45px rgba(255, 77, 109, 0.07) !important;
150
+ padding: 25px !important; margin-bottom: 20px !important;
151
+ }
152
+
153
+ .fixed-cover img {
154
+ width: 100% !important;
155
+ aspect-ratio: 2400 / 1350 !important;
156
+ object-fit: cover !important;
157
+ border-radius: 20px !important;
158
+ display: block !important;
159
+ }
160
+
161
+ .btn-generate {
162
+ background: linear-gradient(135deg, #ff758c 0%, #ff4d6d 100%) !important;
163
+ color: white !important; border-radius: 20px !important;
164
+ font-weight: 800 !important; border: none !important;
165
+ box-shadow: 0 10px 30px rgba(255, 77, 109, 0.4) !important;
166
+ height: 70px !important; font-size: 1.4rem !important; cursor: pointer;
167
+ }
168
+
169
+ /* PROMO STYLING */
170
+ .promo-link { text-decoration: none !important; }
171
+ .promo-container {
172
+ margin-top: 25px; padding: 20px;
173
+ background: linear-gradient(135deg, rgba(255, 117, 140, 0.08) 0%, rgba(255, 77, 109, 0.08) 100%);
174
+ border: 2.5px dashed #ffb3c1; border-radius: 25px;
175
+ text-align: center; transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
176
+ }
177
+ .promo-container:hover {
178
+ transform: scale(1.02); background: rgba(255, 240, 243, 0.9); border-color: #ff4d6d;
179
+ }
180
+ .promo-text {
181
+ color: #ff4d6d; font-weight: 800; font-size: 1.2rem;
182
+ margin-bottom: 12px; display: flex; align-items: center; justify-content: center; gap: 10px;
183
+ }
184
+ .gif-display {
185
+ width: 100%; max-width: 220px; margin: 10px auto 0;
186
+ border-radius: 15px; box-shadow: 0 8px 20px rgba(255, 77, 109, 0.2);
187
+ }
188
+
189
+ /* DIARY BOX STYLING */
190
+ .diary-box {
191
+ margin-top: 20px;
192
+ background: #fffafa;
193
+ border-radius: 20px;
194
+ padding: 20px;
195
+ border: 1px solid #ffe5ec;
196
+ box-shadow: inset 0 0 15px rgba(255, 182, 193, 0.1);
197
+ position: relative;
198
+ }
199
+ .diary-header {
200
+ font-family: 'Dancing Script', cursive;
201
+ color: #ff8fab;
202
+ font-size: 1.5rem;
203
+ text-align: center;
204
+ margin-bottom: 10px;
205
+ }
206
+ .diary-content {
207
+ font-size: 0.9rem;
208
+ color: #7d8597;
209
+ line-height: 1.6;
210
+ text-align: center;
211
+ font-style: italic;
212
+ }
213
+ .diary-footer {
214
+ text-align: right;
215
+ font-size: 0.8rem;
216
+ color: #ffb3c1;
217
+ margin-top: 10px;
218
+ font-weight: 600;
219
+ }
220
+
221
+ .char-btn-premium {
222
+ background: rgba(255, 255, 255, 0.6) !important;
223
+ border: 1.5px solid #ffeef2 !important; border-radius: 15px !important;
224
+ color: #ff5d8f !important; font-weight: 700 !important; font-size: 0.85rem !important;
225
+ padding: 10px !important; transition: all 0.3s ease;
226
+ }
227
+ .char-btn-premium:hover { background: #fff0f3 !important; border-color: #ffb3c1 !important; }
228
+
229
+ .premium-footer {
230
+ background: rgba(255, 255, 255, 0.7) !important;
231
+ backdrop-filter: blur(12px); border: 2px solid #ffffff !important;
232
+ border-radius: 30px !important; padding: 25px !important;
233
+ text-align: center; box-shadow: 0 -10px 40px rgba(255, 182, 193, 0.15) !important;
234
+ margin-top: 20px;
235
+ }
236
+ .footer-text-main { color: #5a647e; font-weight: 800; font-size: 0.9rem; letter-spacing: 2px; }
237
+
238
+ .char-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 12px; }
239
+ .scroll-box { height: 350px; overflow-y: auto !important; padding: 10px; }
240
+ .scroll-box::-webkit-scrollbar { width: 6px; }
241
+ .scroll-box::-webkit-scrollbar-thumb { background: #ffb3c1; border-radius: 10px; }
242
+
243
+ footer { display: none !important; }
244
+ """, head="""
245
+ <div id="custom-loader">
246
+ <div class="unicorn-bounce">🦄</div>
247
+ <div class="loading-bar-container"><div class="loading-bar-progress"></div></div>
248
+ <div class="loading-text" style="color:#ff4d6d; margin-top:10px; font-weight:800;">MAGICAL LOADING...</div>
249
+ </div>
250
+ <script>
251
+ window.addEventListener('load', function() {
252
+ setTimeout(function() {
253
+ var loader = document.getElementById('custom-loader');
254
+ if(loader) {
255
+ loader.style.opacity = '0';
256
+ setTimeout(function() { loader.style.display = 'none'; }, 800);
257
+ }
258
+ }, 3000);
259
+ });
260
+ </script>
261
+ """) as demo:
262
+
263
+ gr.HTML("""
264
+ <div class="header-container">
265
+ <h1 class="main-title">🦄 UMAMUSUME PRETTY 🦄</h1>
266
+ <div class="sub-title-green">VITS - by Mutsumi</div>
267
+ <p style="font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 600; font-size: 1rem; color: #5a647e; margin-top: 2px; opacity: 0.8;">
268
+ 🦄 Generate Voice Anime 🦄
269
+ </p>
270
+ </div>
271
+ """)
272
+
273
+ with gr.Row():
274
+ with gr.Column(scale=4):
275
+ with gr.Column(elem_classes="glow-card"):
276
+ gr.HTML(f"""
277
+ <div align="center" class="fixed-cover">
278
+ <img src="{DEFAULT_COVER}" alt="Umamusume TTS Preview">
279
+ </div>
280
+ """)
281
+ status_box = gr.Markdown(f"⚡ **READY**\n● Models: ✅ LOADED")
282
+ model_dropdown = gr.Dropdown(choices=[m["display_name"] for m in loaded_models], value=loaded_models[0]["display_name"], label="Pilih Versi Model")
283
+
284
+ with gr.Column(scale=6):
285
+ with gr.Column(elem_classes="glow-card"):
286
+ text_input = gr.Textbox(label="Input Teks", placeholder="Tuliskan kalimat...", lines=5)
287
+ with gr.Row():
288
+ char_dropdown = gr.Dropdown(choices=loaded_models[0]["cleaned_speakers"], value=loaded_models[0]["cleaned_speakers"][0], label="🏷️ Pilih Character")
289
+ lang_dropdown = gr.Dropdown(choices=loaded_models[0]["cfg"]["languages"], value=loaded_models[0]["cfg"]["languages"][0], label="📑 Bahasa")
290
+ speed_slider = gr.Slider(0.5, 2.0, 1.0, step=0.1, label="Kecepatan")
291
+ generate_btn = gr.Button("GENERATE VOICE", elem_classes="btn-generate")
292
+
293
+ # --- ADS / MODE LAINNYA SECTION ---
294
+ gr.HTML("""
295
+ <a href="https://huggingface.co/Plana-Archive" target="_blank" class="promo-link">
296
+ <div class="promo-container">
297
+ <div class="promo-text">
298
+ <span>🍒</span> Lihat Mode Anime Lainnya <span>🍒</span>
299
+ </div>
300
+ <div style="font-size: 0.85rem; color: #5a647e; margin-bottom: 10px; font-weight: 600;">
301
+ Klik di sini untuk mengunjungi koleksi Plana-Archive
302
+ </div>
303
+ <img src="https://huggingface.co/spaces/Plana-Archive/DATE-A-LIVE/resolve/main/kurumi-tokisaki.gif" class="gif-display" alt="Kurumi GIF">
304
+ </div>
305
+ </a>
306
+
307
+ <div class="diary-box">
308
+ <div class="diary-header">💚 Mutsumi Diary 💚</div>
309
+ <div class="diary-content">
310
+ "Umm.. kalau kamu suka dengan Models ini, jangan lupa Follow Mutsumi yah?
311
+ Mutsumi senang sekali kalau karyanya dihargai.. tapi, tolong jangan
312
+ ambil modelnya sembarangan tanpa izin ya kak? Itu sangat berarti buat Mutsumi..
313
+ Terima kasih! 🍀"
314
+ </div>
315
+ <div class="diary-footer">— Salam sayang, Mutsumi 🌸</div>
316
+ </div>
317
+ """)
318
+
319
+ with gr.Column(elem_classes="glow-card"):
320
+ audio_out = gr.Audio(label=None, type="numpy")
321
+ status_msg = gr.Markdown("🌺 HASILNYA AKAN MUNCUL CEK SINI 🌺")
322
+
323
+ with gr.Column(elem_classes="glow-card"):
324
+ gr.HTML("""
325
+ <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 20px;">
326
+ <span style="font-size: 1.5rem;">📑</span>
327
+ <h3 style="color: #ff4d6d; margin: 0; font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;">Daftar Karakter Tersedia</h3>
328
+ </div>
329
+ """)
330
+ with gr.Column(elem_classes="scroll-box"):
331
+ with gr.Row(elem_classes="char-grid"):
332
+ for name in loaded_models[0]["cleaned_speakers"]:
333
+ btn = gr.Button(f"🩷 {name}", elem_classes="char-btn-premium")
334
+ btn.click(lambda n=name: gr.update(value=n), None, char_dropdown)
335
+
336
+ gr.HTML("""
337
+ <div class="premium-footer">
338
+ <div class="footer-text-main">🍀 CREATED BY MUTSUMI 🍀</div>
339
+ <div style="color: #8e9aaf; font-weight: 600; font-size: 0.85rem; margin-top: 5px;">
340
+ Umamusume Pretty • Powered by VITS
341
+ </div>
342
+ <div style="margin-top: 15px; color: #ffb3c1; font-weight: 600; font-size: 0.8rem;">
343
+ 🦄 Built with Gradio 🦄
344
+ </div>
345
+ </div>
346
+ """)
347
+
348
+ model_dropdown.change(update_model_ui, inputs=[model_dropdown], outputs=[char_dropdown, lang_dropdown, status_box])
349
+
350
+ generate_btn.click(
351
+ lambda: "🌷 Generate teks menjadi suara ♻️",
352
+ outputs=[status_msg]
353
+ ).then(
354
+ generate_voice,
355
+ inputs=[model_dropdown, text_input, char_dropdown, lang_dropdown, speed_slider],
356
+ outputs=[audio_out, status_msg],
357
+ show_progress="full"
358
+ )
359
+
360
+ if __name__ == "__main__":
361
+ demo.launch(favicon_path="https://fav.farm/🩷")
Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_modules.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+ import commons
5
+ import utils
6
+ from models import SynthesizerTrn
7
+ import numpy as np
8
+ import json
9
+ import requests
10
+ import logging
11
+ import sys
12
+ import argparse
13
+ import time
14
+ from torch import no_grad, LongTensor
15
+ from text import text_to_sequence
16
+
17
+ # --- Setup Logging ---
18
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # --- Konfigurasi Model ---
22
+ BASE_URL = "https://huggingface.co/spaces/Rosmontis-Chan/VITS-Umamusume-Voice/resolve/main"
23
+ MODELS_CONFIG = [
24
+ {
25
+ "name": "Trilingual",
26
+ "model_file": "G_trilingual.pth",
27
+ "config_file": "uma_trilingual.json",
28
+ "display_name": "🦄 Trilingual Model",
29
+ "languages": ["日本語", "简体中文", "English", "Mix"],
30
+ },
31
+ {
32
+ "name": "Japanese",
33
+ "model_file": "G_jp.pth",
34
+ "config_file": "uma87.json",
35
+ "display_name": "🇯🇵 Japanese Model",
36
+ "languages": ["Japanese"],
37
+ }
38
+ ]
39
+
40
+ LOCAL_DIR, CONFIG_DIR = "pretrained_models", "configs"
41
+
42
+ # FIX: Menggunakan link resolve agar gambar muncul secara permanen di web
43
+ DEFAULT_COVER = "https://huggingface.co/spaces/Rosmontis-Chan/VITS-Umamusume-Voice/resolve/main/cover.png"
44
+
45
+ def download_file(url, local_path):
46
+ if os.path.exists(local_path): return True
47
+ try:
48
+ response = requests.get(url, stream=True)
49
+ os.makedirs(os.path.dirname(local_path), exist_ok=True)
50
+ with open(local_path, 'wb') as f:
51
+ for chunk in response.iter_content(chunk_size=8192): f.write(chunk)
52
+ return True
53
+ except: return False
54
+
55
+ def get_text(text, hps):
56
+ text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
57
+ if hps.data.add_blank: text_norm = commons.intersperse(text_norm, 0)
58
+ return LongTensor(text_norm)
59
+
60
+ # --- Load Models Backend ---
61
+ loaded_models = []
62
+ for cfg in MODELS_CONFIG:
63
+ m_p, c_p = os.path.join(LOCAL_DIR, cfg["model_file"]), os.path.join(CONFIG_DIR, cfg["config_file"])
64
+ download_file(f"{BASE_URL}/pretrained_models/{cfg['model_file']}", m_p)
65
+ download_file(f"{BASE_URL}/configs/{cfg['config_file']}", c_p)
66
+ try:
67
+ hps = utils.get_hparams_from_file(c_p)
68
+ net_g = SynthesizerTrn(len(hps.symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, **hps.model)
69
+ utils.load_checkpoint(m_p, net_g, None)
70
+ net_g.eval()
71
+ loaded_models.append({
72
+ "cfg": cfg, "model": net_g, "hps": hps,
73
+ "display_name": cfg["display_name"],
74
+ "speakers": list(hps.speakers.keys()),
75
+ "cleaned_speakers": [s.split('(')[0].strip() for s in hps.speakers.keys()]
76
+ })
77
+ except Exception as e: print(f"Error load {cfg['name']}: {e}")
78
+
79
+ def update_model_ui(model_name):
80
+ m = next((x for x in loaded_models if x["display_name"] == model_name), loaded_models[0])
81
+ return (
82
+ gr.update(choices=m["cleaned_speakers"], value=m["cleaned_speakers"][0]),
83
+ gr.update(choices=m["cfg"]["languages"], value=m["cfg"]["languages"][0]),
84
+ f"⚡ **SYSTEM STATUS**\n● Models: ✅ LOADED\n● Total Models: {len(loaded_models)}\n● Total Speakers: {len(m['speakers'])}"
85
+ )
86
+
87
+ def generate_voice(model_name, text, speaker, lang, speed):
88
+ if not text: return None, "⚠️ Tolong Isi teks dulu kak, yah! ⚠️"
89
+ try:
90
+ m = next((x for x in loaded_models if x["display_name"] == model_name), loaded_models[0])
91
+ full_speaker_name = next(s for s in m["speakers"] if speaker in s)
92
+ speaker_id = m["hps"].speakers[full_speaker_name]
93
+ stn_tst = get_text(text, m["hps"])
94
+ with no_grad():
95
+ x_tst = stn_tst.unsqueeze(0)
96
+ x_tst_lengths = LongTensor([stn_tst.size(0)])
97
+ sid = LongTensor([speaker_id])
98
+ audio = m["model"].infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8, length_scale=1.0/speed)[0][0,0].data.cpu().float().numpy()
99
+ audio = (audio / np.abs(audio).max() * 32767).astype(np.int16)
100
+ return (m["hps"].data.sampling_rate, audio), "✅ Berhasil dibuat!"
101
+ except Exception as e: return None, f"❌ Error: {str(e)}"
102
+
103
+ # ============================================
104
+ # UI INTERFACE
105
+ # ============================================
106
+ with gr.Blocks(css="""
107
+ @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;800&display=swap');
108
+ body { background-color: #fff8f9; font-family: 'Plus Jakarta Sans', sans-serif; }
109
+
110
+ :root { --loader-color: #ff4d6d !important; --primary-500: #ff4d6d !important; }
111
+
112
+ /* CUSTOM LOADER */
113
+ #custom-loader {
114
+ position: fixed; top: 0; left: 0; width: 100%; height: 100%;
115
+ background: radial-gradient(circle, #ffffff 0%, #fff0f3 100%);
116
+ display: flex; flex-direction: column;
117
+ justify-content: center; align-items: center; z-index: 99999;
118
+ transition: opacity 0.8s ease-out;
119
+ }
120
+ .unicorn-bounce {
121
+ font-size: 80px; animation: bounce 0.6s infinite alternate;
122
+ filter: drop-shadow(0 10px 10px rgba(255, 77, 109, 0.2));
123
+ }
124
+ @keyframes bounce { from { transform: translateY(0); } to { transform: translateY(-30px); } }
125
+ .loading-bar-container { width: 200px; height: 6px; background: #ffeef2; border-radius: 10px; margin-top: 20px; overflow: hidden; }
126
+ .loading-bar-progress { width: 100%; height: 100%; background: linear-gradient(90deg, #ff758c, #ff4d6d); animation: loadingLine 2s infinite ease-in-out; transform-origin: left; }
127
+ @keyframes loadingLine { 0% { transform: scaleX(0); } 50% { transform: scaleX(1); } 100% { transform: scaleX(0); transform-origin: right; } }
128
+
129
+ .header-container { text-align: center; padding: 20px 0; }
130
+ .main-title {
131
+ font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;
132
+ font-size: clamp(1.8rem, 8vw, 2.8rem);
133
+ color: #ff4d6d; display: inline-block;
134
+ background: linear-gradient(to bottom, #ff758c 0%, #ff4d6d 100%);
135
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent;
136
+ line-height: 1.1; margin: 0;
137
+ }
138
+ .sub-title-pink {
139
+ font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;
140
+ font-size: clamp(1.2rem, 5vw, 1.8rem);
141
+ color: #ff8fab; text-transform: uppercase; margin: 5px 0;
142
+ }
143
+
144
+ .glow-card {
145
+ background: white !important; border-radius: 30px !important;
146
+ border: 2px solid #ffeef2 !important;
147
+ box-shadow: 0 15px 45px rgba(255, 77, 109, 0.07) !important;
148
+ padding: 25px !important; margin-bottom: 20px !important;
149
+ }
150
+
151
+ /* FIX UKURAN GAMBAR 2400x1350 */
152
+ .custom-cover-img {
153
+ width: 100% !important;
154
+ aspect-ratio: 2400 / 1350 !important;
155
+ object-fit: cover !important;
156
+ border-radius: 20px !important;
157
+ display: block !important;
158
+ }
159
+
160
+ .btn-generate {
161
+ background: linear-gradient(135deg, #ff758c 0%, #ff4d6d 100%) !important;
162
+ color: white !important; border-radius: 20px !important;
163
+ font-weight: 800 !important; border: none !important;
164
+ box-shadow: 0 10px 30px rgba(255, 77, 109, 0.4) !important;
165
+ height: 70px !important; font-size: 1.4rem !important; cursor: pointer;
166
+ }
167
+
168
+ .char-btn-premium {
169
+ background: rgba(255, 255, 255, 0.6) !important;
170
+ border: 1.5px solid #ffeef2 !important; border-radius: 15px !important;
171
+ color: #ff5d8f !important; font-weight: 700 !important; font-size: 0.85rem !important;
172
+ padding: 10px !important; transition: all 0.3s ease;
173
+ }
174
+ .char-btn-premium:hover { background: #fff0f3 !important; border-color: #ffb3c1 !important; }
175
+
176
+ .premium-footer {
177
+ background: rgba(255, 255, 255, 0.7) !important;
178
+ backdrop-filter: blur(12px); border: 2px solid #ffffff !important;
179
+ border-radius: 30px !important; padding: 25px !important;
180
+ text-align: center; box-shadow: 0 -10px 40px rgba(255, 182, 193, 0.15) !important;
181
+ margin-top: 20px;
182
+ }
183
+ .footer-text-main { color: #5a647e; font-weight: 800; font-size: 0.9rem; letter-spacing: 2px; }
184
+
185
+ .char-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 12px; }
186
+ .scroll-box { height: 350px; overflow-y: auto !important; padding: 10px; }
187
+ .scroll-box::-webkit-scrollbar { width: 6px; }
188
+ .scroll-box::-webkit-scrollbar-thumb { background: #ffb3c1; border-radius: 10px; }
189
+
190
+ footer { display: none !important; }
191
+ """, head="""
192
+ <div id="custom-loader">
193
+ <div class="unicorn-bounce">🦄</div>
194
+ <div class="loading-bar-container"><div class="loading-bar-progress"></div></div>
195
+ <div class="loading-text" style="color:#ff4d6d; margin-top:10px; font-weight:800;">MAGICAL LOADING...</div>
196
+ </div>
197
+ <script>
198
+ window.addEventListener('load', function() {
199
+ setTimeout(function() {
200
+ var loader = document.getElementById('custom-loader');
201
+ if(loader) {
202
+ loader.style.opacity = '0';
203
+ setTimeout(function() { loader.style.display = 'none'; }, 800);
204
+ }
205
+ }, 3000);
206
+ });
207
+ </script>
208
+ """) as demo:
209
+
210
+ gr.HTML("""
211
+ <div class="header-container">
212
+ <h1 class="main-title">🦄 UMAMUSUME PRETTY - TTS 🦄</h1>
213
+ <div class="sub-title-pink">Umamusume TTS - Premium</div>
214
+ <p style="font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 600; font-size: 1rem; color: #5a647e; margin-top: 2px; opacity: 0.8;">
215
+ 🦄 Generate Voice Anime 🦄
216
+ </p>
217
+ </div>
218
+ """)
219
+
220
+ with gr.Row():
221
+ with gr.Column(scale=4):
222
+ with gr.Column(elem_classes="glow-card"):
223
+ # Menampilkan gambar cover dengan link permanen dan CSS kustom
224
+ gr.Image(DEFAULT_COVER, show_label=False, container=False, elem_classes="custom-cover-img")
225
+ status_box = gr.Markdown(f"⚡ **READY**\n● Models: ✅ LOADED")
226
+ model_dropdown = gr.Dropdown(choices=[m["display_name"] for m in loaded_models], value=loaded_models[0]["display_name"], label="Pilih Versi Model")
227
+
228
+ with gr.Column(scale=6):
229
+ with gr.Column(elem_classes="glow-card"):
230
+ text_input = gr.Textbox(label="Input Teks", placeholder="Tuliskan kalimat...", lines=5)
231
+ with gr.Row():
232
+ char_dropdown = gr.Dropdown(choices=loaded_models[0]["cleaned_speakers"], value=loaded_models[0]["cleaned_speakers"][0], label="🏷️ Pilih Character")
233
+ lang_dropdown = gr.Dropdown(choices=loaded_models[0]["cfg"]["languages"], value=loaded_models[0]["cfg"]["languages"][0], label="📑 Bahasa")
234
+ speed_slider = gr.Slider(0.5, 2.0, 1.0, step=0.1, label="Kecepatan")
235
+ generate_btn = gr.Button("🪄GENERATE VOICE🪄", elem_classes="btn-generate")
236
+
237
+ with gr.Column(elem_classes="glow-card"):
238
+ audio_out = gr.Audio(label=None, type="numpy")
239
+ status_msg = gr.Markdown("Siap memproses... ✨")
240
+
241
+ with gr.Column(elem_classes="glow-card"):
242
+ gr.HTML("""
243
+ <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 20px;">
244
+ <span style="font-size: 1.5rem;">📑</span>
245
+ <h3 style="color: #ff4d6d; margin: 0; font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;">Daftar Karakter</h3>
246
+ </div>
247
+ """)
248
+ with gr.Column(elem_classes="scroll-box"):
249
+ with gr.Row(elem_classes="char-grid"):
250
+ for name in loaded_models[0]["cleaned_speakers"]:
251
+ btn = gr.Button(f"🩷 {name}", elem_classes="char-btn-premium")
252
+ btn.click(lambda n=name: gr.update(value=n), None, char_dropdown)
253
+
254
+ gr.HTML("""
255
+ <div class="premium-footer">
256
+ <div class="footer-text-main">CREATED BY ROSMONTIS</div>
257
+ <div style="color: #8e9aaf; font-weight: 600; font-size: 0.85rem; margin-top: 5px;">
258
+ Umamusume Pretty - Premium TTS v2.0 • Powered by VITS
259
+ </div>
260
+ <div style="margin-top: 15px; color: #ffb3c1; font-weight: 600; font-size: 0.8rem;">
261
+ 🦄 Built with Gradio 🦄
262
+ </div>
263
+ </div>
264
+ """)
265
+
266
+ model_dropdown.change(update_model_ui, inputs=[model_dropdown], outputs=[char_dropdown, lang_dropdown, status_box])
267
+
268
+ generate_btn.click(
269
+ lambda: "🪄 Menyulap teks menjadi suara 🪄",
270
+ outputs=[status_msg]
271
+ ).then(
272
+ generate_voice,
273
+ inputs=[model_dropdown, text_input, char_dropdown, lang_dropdown, speed_slider],
274
+ outputs=[audio_out, status_msg],
275
+ show_progress="full"
276
+ )
277
+
278
+ if __name__ == "__main__":
279
+ # Link favicon juga diperbaiki agar tidak error
280
+ demo.launch(favicon_path="https://fav.farm/🩷")
Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_to_onnx.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ONNXVITS_models
2
+ import utils
3
+ from text import text_to_sequence
4
+ import torch
5
+ import commons
6
+
7
+ def get_text(text, hps):
8
+ text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
9
+ if hps.data.add_blank:
10
+ text_norm = commons.intersperse(text_norm, 0)
11
+ text_norm = torch.LongTensor(text_norm)
12
+ return text_norm
13
+
14
+ hps = utils.get_hparams_from_file("../vits/pretrained_models/uma87.json")
15
+ symbols = hps.symbols
16
+ net_g = ONNXVITS_models.SynthesizerTrn(
17
+ len(symbols),
18
+ hps.data.filter_length // 2 + 1,
19
+ hps.train.segment_size // hps.data.hop_length,
20
+ n_speakers=hps.data.n_speakers,
21
+ **hps.model)
22
+ _ = net_g.eval()
23
+ _ = utils.load_checkpoint("../vits/pretrained_models/uma_1153000.pth", net_g)
24
+
25
+ text1 = get_text("ありがとうございます。", hps)
26
+ stn_tst = text1
27
+ with torch.no_grad():
28
+ x_tst = stn_tst.unsqueeze(0)
29
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)])
30
+ sid = torch.tensor([0])
31
+ o = net_g(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8, length_scale=1)
Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_transforms.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import numpy as np
5
+
6
+
7
+ DEFAULT_MIN_BIN_WIDTH = 1e-3
8
+ DEFAULT_MIN_BIN_HEIGHT = 1e-3
9
+ DEFAULT_MIN_DERIVATIVE = 1e-3
10
+
11
+
12
+ def piecewise_rational_quadratic_transform(inputs,
13
+ unnormalized_widths,
14
+ unnormalized_heights,
15
+ unnormalized_derivatives,
16
+ inverse=False,
17
+ tails=None,
18
+ tail_bound=1.,
19
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
20
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
21
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
22
+
23
+ if tails is None:
24
+ spline_fn = rational_quadratic_spline
25
+ spline_kwargs = {}
26
+ else:
27
+ spline_fn = unconstrained_rational_quadratic_spline
28
+ spline_kwargs = {
29
+ 'tails': tails,
30
+ 'tail_bound': tail_bound
31
+ }
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
43
+ )
44
+ return outputs, logabsdet
45
+
46
+
47
+ def searchsorted(bin_locations, inputs, eps=1e-6):
48
+ bin_locations[..., -1] += eps
49
+ return torch.sum(
50
+ inputs[..., None] >= bin_locations,
51
+ dim=-1
52
+ ) - 1
53
+
54
+
55
+ def unconstrained_rational_quadratic_spline(inputs,
56
+ unnormalized_widths,
57
+ unnormalized_heights,
58
+ unnormalized_derivatives,
59
+ inverse=False,
60
+ tails='linear',
61
+ tail_bound=1.,
62
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
63
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
64
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
65
+ inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
66
+ outside_interval_mask = ~inside_interval_mask
67
+
68
+ outputs = torch.zeros_like(inputs)
69
+ logabsdet = torch.zeros_like(inputs)
70
+
71
+ if tails == 'linear':
72
+ #unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
73
+ unnormalized_derivatives_ = torch.zeros((1, 1, unnormalized_derivatives.size(2), unnormalized_derivatives.size(3)+2))
74
+ unnormalized_derivatives_[...,1:-1] = unnormalized_derivatives
75
+ unnormalized_derivatives = unnormalized_derivatives_
76
+ constant = np.log(np.exp(1 - min_derivative) - 1)
77
+ unnormalized_derivatives[..., 0] = constant
78
+ unnormalized_derivatives[..., -1] = constant
79
+
80
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
81
+ logabsdet[outside_interval_mask] = 0
82
+ else:
83
+ raise RuntimeError('{} tails are not implemented.'.format(tails))
84
+
85
+ outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(
86
+ inputs=inputs[inside_interval_mask],
87
+ unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
88
+ unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
89
+ unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
90
+ inverse=inverse,
91
+ left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,
92
+ min_bin_width=min_bin_width,
93
+ min_bin_height=min_bin_height,
94
+ min_derivative=min_derivative
95
+ )
96
+
97
+ return outputs, logabsdet
98
+
99
+ def rational_quadratic_spline(inputs,
100
+ unnormalized_widths,
101
+ unnormalized_heights,
102
+ unnormalized_derivatives,
103
+ inverse=False,
104
+ left=0., right=1., bottom=0., top=1.,
105
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
106
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
107
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
108
+ if torch.min(inputs) < left or torch.max(inputs) > right:
109
+ raise ValueError('Input to a transform is not within its domain')
110
+
111
+ num_bins = unnormalized_widths.shape[-1]
112
+
113
+ if min_bin_width * num_bins > 1.0:
114
+ raise ValueError('Minimal bin width too large for the number of bins')
115
+ if min_bin_height * num_bins > 1.0:
116
+ raise ValueError('Minimal bin height too large for the number of bins')
117
+
118
+ widths = F.softmax(unnormalized_widths, dim=-1)
119
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
120
+ cumwidths = torch.cumsum(widths, dim=-1)
121
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)
122
+ cumwidths = (right - left) * cumwidths + left
123
+ cumwidths[..., 0] = left
124
+ cumwidths[..., -1] = right
125
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
126
+
127
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
128
+
129
+ heights = F.softmax(unnormalized_heights, dim=-1)
130
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
131
+ cumheights = torch.cumsum(heights, dim=-1)
132
+ cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)
133
+ cumheights = (top - bottom) * cumheights + bottom
134
+ cumheights[..., 0] = bottom
135
+ cumheights[..., -1] = top
136
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
137
+
138
+ if inverse:
139
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
140
+ else:
141
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
142
+
143
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
144
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
145
+
146
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
147
+ delta = heights / widths
148
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
149
+
150
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
151
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
152
+
153
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
154
+
155
+ if inverse:
156
+ a = (((inputs - input_cumheights) * (input_derivatives
157
+ + input_derivatives_plus_one
158
+ - 2 * input_delta)
159
+ + input_heights * (input_delta - input_derivatives)))
160
+ b = (input_heights * input_derivatives
161
+ - (inputs - input_cumheights) * (input_derivatives
162
+ + input_derivatives_plus_one
163
+ - 2 * input_delta))
164
+ c = - input_delta * (inputs - input_cumheights)
165
+
166
+ discriminant = b.pow(2) - 4 * a * c
167
+ assert (discriminant >= 0).all()
168
+
169
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
170
+ outputs = root * input_bin_widths + input_cumwidths
171
+
172
+ theta_one_minus_theta = root * (1 - root)
173
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
174
+ * theta_one_minus_theta)
175
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)
176
+ + 2 * input_delta * theta_one_minus_theta
177
+ + input_derivatives * (1 - root).pow(2))
178
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
179
+
180
+ return outputs, -logabsdet
181
+ else:
182
+ theta = (inputs - input_cumwidths) / input_bin_widths
183
+ theta_one_minus_theta = theta * (1 - theta)
184
+
185
+ numerator = input_heights * (input_delta * theta.pow(2)
186
+ + input_derivatives * theta_one_minus_theta)
187
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
188
+ * theta_one_minus_theta)
189
+ outputs = input_cumheights + numerator / denominator
190
+
191
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)
192
+ + 2 * input_delta * theta_one_minus_theta
193
+ + input_derivatives * (1 - theta).pow(2))
194
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
195
+
196
+ return outputs, logabsdet
Mutsumi-Chan/VITS-Umamusume-Voice/ONNXVITS_utils.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import random
4
+ import onnxruntime as ort
5
+ def set_random_seed(seed=0):
6
+ ort.set_seed(seed)
7
+ torch.manual_seed(seed)
8
+ torch.cuda.manual_seed(seed)
9
+ torch.backends.cudnn.deterministic = True
10
+ random.seed(seed)
11
+ np.random.seed(seed)
12
+
13
+ def runonnx(model_path, **kwargs):
14
+ ort_session = ort.InferenceSession(model_path)
15
+ outputs = ort_session.run(
16
+ None,
17
+ kwargs
18
+ )
19
+ return outputs
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:559b9b8db0784cffd24e4bb3de2ec44799beb367cbf2bfa8e2868a7744463dcb
3
+ size 58201240
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/dp.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4a7393ca121d3d2a21626841d9b66e49a45e6a287c88c4f707c041a58cf20bc
3
+ size 7781725
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/enc_p.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad8b13ac90e35576ec57f97d879acf543f4d1c37785b8182c1ef48a87cda7106
3
+ size 28764539
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/flow.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13ea432975f560f8c34fcf08fb7e6bee3278ea3e2fe97319b2c34aeb21ae657c
3
+ size 35774909
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_jp/plana ADDED
@@ -0,0 +1 @@
 
 
1
+ Halo
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_trilingual/dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b51d61f0c621f0e6531f59c0322c692aef9cc0f0cbb633f890f820027cfdbec
3
+ size 58201240
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_trilingual/dp.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b699d166d7c95648763fc322ee7ba7aadd7289f9c038dec81d14d98c0de3d5d
3
+ size 7781725
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_trilingual/enc_p.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5a4c00c85c82f916d24fe22a46fb70f5d6da9b4e122692b4561c027a514988b
3
+ size 28786043
Mutsumi-Chan/VITS-Umamusume-Voice/ONNX_net/G_trilingual/flow.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a5e74edc4d412e1857bb3a33b819d7ac4b3f6119484a775c478989b79351097
3
+ size 35774909
Mutsumi-Chan/VITS-Umamusume-Voice/README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Vits Umamusume Voice
3
+ emoji: 🦄
4
+ short_description: Generate Voice From Anime TTS
5
+ colorFrom: green
6
+ colorTo: gray
7
+ sdk: gradio
8
+ sdk_version: 4.19.2
9
+ app_file: app.py
10
+ pinned: false
11
+ header: mini
12
+ python_version: '3.10'
13
+ ---
14
+
15
+ # VITS Umamusume Voice
16
+ Aplikasi TTS (Text-to-Speech) untuk karakter Umamusume menggunakan arsitektur VITS.
Mutsumi-Chan/VITS-Umamusume-Voice/app.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+ import commons
5
+ import utils
6
+ from models import SynthesizerTrn
7
+ import numpy as np
8
+ import json
9
+ import requests
10
+ import logging
11
+ import random
12
+ from torch import no_grad, LongTensor
13
+ from text import text_to_sequence
14
+
15
+ # --- 1. SETUP LOGGING ---
16
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
17
+ logger = logging.getLogger(__name__)
18
+
19
+ # --- 2. KONFIGURASI MODEL ---
20
+ BASE_URL = "https://huggingface.co/spaces/Plana-Archive/VITS-Umamusume-Voice/resolve/main"
21
+ MODELS_CONFIG = [
22
+ {
23
+ "name": "Trilingual",
24
+ "model_file": "G_trilingual.pth",
25
+ "config_file": "uma_trilingual.json",
26
+ "display_name": "🦄 Trilingual Model",
27
+ "languages": ["日本語", "简体中文", "English", "Mix"],
28
+ },
29
+ {
30
+ "name": "Japanese",
31
+ "model_file": "G_jp.pth",
32
+ "config_file": "uma87.json",
33
+ "display_name": "🇯🇵 Japanese Model",
34
+ "languages": ["Japanese"],
35
+ }
36
+ ]
37
+
38
+ LOCAL_DIR, CONFIG_DIR = "pretrained_models", "configs"
39
+ DEFAULT_COVER = "https://huggingface.co/spaces/Plana-Archive/VITS-Umamusume-Voice/resolve/main/cover.png"
40
+ GIF_URL = "https://huggingface.co/spaces/Plana-Archive/VITS-Umamusume-Voice/resolve/main/haru-urara-concert.gif"
41
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
42
+
43
+ # Random English Texts
44
+ RANDOM_TEXTS = [
45
+ "Hello! Let's do our best today!",
46
+ "I think your voice is very lovely.",
47
+ "Would you like to go out with me? I'm looking forward to it!",
48
+ "I want to become even stronger. Please watch over me!",
49
+ "Good job today. Please get some good rest.",
50
+ "Hehe, I get a bit shy when you praise me like that.",
51
+ "This melody is echoing deep within my heart."
52
+ ]
53
+
54
+ # --- 3. HELPER FUNCTIONS ---
55
+ def download_file(url, local_path):
56
+ if os.path.exists(local_path): return True
57
+ try:
58
+ response = requests.get(url, stream=True)
59
+ os.makedirs(os.path.dirname(local_path), exist_ok=True)
60
+ with open(local_path, 'wb') as f:
61
+ for chunk in response.iter_content(chunk_size=8192): f.write(chunk)
62
+ return True
63
+ except: return False
64
+
65
+ def get_text(text, hps):
66
+ text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
67
+ if hps.data.add_blank: text_norm = commons.intersperse(text_norm, 0)
68
+ return LongTensor(text_norm)
69
+
70
+ def get_random_en_text():
71
+ return random.choice(RANDOM_TEXTS)
72
+
73
+ # --- 4. LOAD MODELS BACKEND ---
74
+ loaded_models = []
75
+ for cfg in MODELS_CONFIG:
76
+ m_p, c_p = os.path.join(LOCAL_DIR, cfg["model_file"]), os.path.join(CONFIG_DIR, cfg["config_file"])
77
+ download_file(f"{BASE_URL}/pretrained_models/{cfg['model_file']}", m_p)
78
+ download_file(f"{BASE_URL}/configs/{cfg['config_file']}", c_p)
79
+ try:
80
+ hps = utils.get_hparams_from_file(c_p)
81
+ net_g = SynthesizerTrn(
82
+ len(hps.symbols),
83
+ hps.data.filter_length // 2 + 1,
84
+ hps.train.segment_size // hps.data.hop_length,
85
+ n_speakers=hps.data.n_speakers,
86
+ **hps.model
87
+ ).to(device)
88
+ utils.load_checkpoint(m_p, net_g, None)
89
+ net_g.eval()
90
+ loaded_models.append({
91
+ "cfg": cfg, "model": net_g, "hps": hps,
92
+ "display_name": cfg["display_name"],
93
+ "speakers": list(hps.speakers.keys()),
94
+ "cleaned_speakers": [s.split('(')[0].strip() for s in hps.speakers.keys()]
95
+ })
96
+ except Exception as e: logger.error(f"Error load {cfg['name']}: {e}")
97
+
98
+ # --- 5. CORE LOGIC ---
99
+ def tts_execute(model_name, text, speaker, lang, speed):
100
+ if not text: return "⚠️ Isi teks dulu!", None
101
+ if not speaker: return "⚠️ Pilih Karakter!", None
102
+ try:
103
+ m = next((x for x in loaded_models if x["display_name"] == model_name), loaded_models[0])
104
+ full_speaker_name = next(s for s in m["speakers"] if speaker in s)
105
+ speaker_id = m["hps"].speakers[full_speaker_name]
106
+ stn_tst = get_text(text, m["hps"])
107
+ with no_grad():
108
+ x_tst = stn_tst.unsqueeze(0).to(device)
109
+ x_tst_lengths = LongTensor([stn_tst.size(0)]).to(device)
110
+ sid = LongTensor([speaker_id]).to(device)
111
+ audio = m["model"].infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667,
112
+ noise_scale_w=0.8, length_scale=1.0/speed)[0][0,0].data.cpu().float().numpy()
113
+ audio_int16 = (audio / np.abs(audio).max() * 32767).astype(np.int16)
114
+ return "✅ Success!", (m["hps"].data.sampling_rate, audio_int16)
115
+ except Exception as e:
116
+ return f"❌ Error: {str(e)}", None
117
+
118
+ def update_model_info(model_name):
119
+ m = next((x for x in loaded_models if x["display_name"] == model_name), loaded_models[0])
120
+ return (
121
+ gr.update(choices=m["cleaned_speakers"], value=m["cleaned_speakers"][0]),
122
+ gr.update(choices=m["cfg"]["languages"], value=m["cfg"]["languages"][0])
123
+ )
124
+
125
+ # --- 6. UI STYLE & THEME ---
126
+ css = """
127
+ @import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght@600&family=Quicksand:wght@500;700&display=swap');
128
+
129
+ :root { --primary-500: #ff4d6d !important; --accent-500: #ff4d6d !important; --loader-color: #ff4d6d !important; }
130
+ .ba-header-container { border: 1.5px solid #ffeef2; border-radius: 12px; padding: 12px; margin-bottom: 8px; background: white; text-align: center; }
131
+ .ba-header-container h1 { color: #ff4d6d !important; font-weight: 800 !important; font-size: 20px !important; margin: 0; padding: 0; line-height: 1.2; }
132
+ .ba-header-container p { font-size: 11px !important; color: #ff8fab; font-weight: 600; margin: 2px 0 0 0; }
133
+ .status-container { border: 1.5px solid #ffeef2; border-radius: 12px; padding: 10px 15px; margin-bottom: 10px; background: white; font-size: 13px; }
134
+ .status-title { color: #ff4d6d !important; font-weight: 800; font-size: 14px; margin-bottom: 4px; }
135
+ .text-green-bold { color: #28a745 !important; font-weight: 900 !important; }
136
+ .slim-card { max-width: 550px; margin: 0 auto; background: transparent; padding: 5px; }
137
+ .scroll-box { height: 200px; overflow-y: auto; border: 1px solid #ffeef2; border-radius: 12px; padding: 8px; background: #fffafa; margin-bottom: 8px; }
138
+ .char-btn { background: white !important; border: 1px solid #ffeef2 !important; border-left: 4px solid #ff4d6d !important; text-align: left !important; padding: 6px !important; font-size: 12px !important; margin-bottom: 3px !important; width: 100%; color: #4a5568 !important; }
139
+ .warning-card { background: #fff9f0; border: 2px dashed #ff4d6d; border-radius: 10px; padding: 10px; margin-bottom: 10px; text-align: center; font-size: 11px; }
140
+ .gen-btn { background: #ff4d6d !important; color: white !important; font-weight: 700 !important; border-radius: 10px !important; height: 45px !important; width: 100%; border: none !important; cursor: pointer; font-size: 16px !important; }
141
+ .random-btn { background: #ff4d6d !important; color: white !important; font-weight: 700 !important; border-radius: 8px !important; border: none !important; font-size: 12px !important; padding: 4px 10px !important; margin-top: -10px; margin-bottom: 10px; cursor: pointer; }
142
+ .credit-footer { margin-top: 20px; padding: 12px; background: white; border-radius: 12px; text-align: center; border-bottom: 4px solid #ff4d6d; color: #94a3b8; font-weight: 700; font-size: 11px; letter-spacing: 1px; }
143
+ .img-container { text-align: center; margin-bottom: 10px; display: flex; justify-content: center; }
144
+ .img-container img { max-width: 100%; height: auto; border-radius: 10px; }
145
+ .gif-container { text-align: center; margin: 15px 0; display: flex; justify-content: center; width: 100%; }
146
+ .gif-container img { width: 100%; max-width: 550px; height: auto; border-radius: 12px; box-shadow: 0 4px 10px rgba(255, 77, 109, 0.2); }
147
+
148
+ /* PINK LABELS */
149
+ .pink-label span {
150
+ background-color: #ff4d6d !important;
151
+ color: white !important;
152
+ padding: 2px 10px !important;
153
+ border-radius: 8px !important;
154
+ font-weight: 700 !important;
155
+ font-size: 13px !important;
156
+ }
157
+
158
+ /* DIARY STYLING AESTHETIC */
159
+ .diary-box {
160
+ margin-top: 20px; background: #ffffff; border: 1px solid #ffe5ec;
161
+ border-radius: 20px; padding: 20px; position: relative;
162
+ box-shadow: 0 10px 25px -5px rgba(255, 77, 109, 0.1);
163
+ }
164
+ .diary-header {
165
+ font-family: 'Dancing Script', cursive;
166
+ color: #ff4d6d !important; font-weight: 700 !important;
167
+ font-size: 24px !important; margin-bottom: 10px; text-align: center;
168
+ }
169
+ .diary-content {
170
+ font-family: 'Quicksand', sans-serif;
171
+ font-size: 13.5px; color: #5c677d; line-height: 1.6; font-weight: 500;
172
+ font-style: italic; text-align: center;
173
+ }
174
+
175
+ /* NO COLOR ON AUDIO LABEL */
176
+ .no-label-color span {
177
+ background-color: transparent !important;
178
+ color: #4a5568 !important;
179
+ font-weight: 700 !important;
180
+ padding: 0 !important;
181
+ }
182
+ .elegant-audio {
183
+ background: #ffffff !important;
184
+ border: 1.5px solid #f1f5f9 !important;
185
+ border-radius: 12px !important;
186
+ box-shadow: none !important;
187
+ padding: 5px !important;
188
+ }
189
+ """
190
+
191
+ # --- 7. GRADIO INTERFACE ---
192
+ with gr.Blocks(css=css, theme=gr.themes.Soft(primary_hue="pink")) as app:
193
+ with gr.Column(elem_classes="slim-card"):
194
+ # Header
195
+ gr.HTML(f"""
196
+ <div class="ba-header-container">
197
+ <h1>UMAMUSUME VITS</h1>
198
+ <p>🦄 Magical Voice Generation 🦄</p>
199
+ </div>
200
+ <div class="status-container">
201
+ <div class="status-title">System Status</div>
202
+ <div class="status-item"><span style="color:#4a5568">Model :</span> <span class="text-green-bold">&nbsp;Umamusume Pack ✅</span></div>
203
+ <div class="status-item"><span style="color:#4a5568">Engine :</span> <span style="color:#ff4d6d">&nbsp;VITS Emotional</span></div>
204
+ </div>
205
+ """)
206
+
207
+ # Cover Image
208
+ gr.HTML(f"""<div class="img-container"><img src="{DEFAULT_COVER}" alt="Cover" loading="lazy"></div>""")
209
+
210
+ # Model & Language Select
211
+ with gr.Row():
212
+ model_select = gr.Dropdown(
213
+ choices=[m["display_name"] for m in loaded_models],
214
+ value=loaded_models[0]["display_name"],
215
+ label="Versi Model",
216
+ elem_classes="pink-label"
217
+ )
218
+ lang_select = gr.Dropdown(
219
+ choices=loaded_models[0]["cfg"]["languages"],
220
+ value=loaded_models[0]["cfg"]["languages"][0],
221
+ label="Bahasa",
222
+ elem_classes="pink-label"
223
+ )
224
+
225
+ selected_char = gr.State(loaded_models[0]["cleaned_speakers"][0])
226
+ char_label = gr.Markdown(f"📍 Selected: **{loaded_models[0]['cleaned_speakers'][0]}**")
227
+
228
+ # Daftar Karakter
229
+ gr.HTML('<div style="font-weight:800; color:#ff4d6d; font-size:12px; margin-bottom:4px;">📑 DAFTAR KARAKTER TERSEDIA</div>')
230
+ with gr.Column(elem_classes="scroll-box"):
231
+ char_dropdown_hidden = gr.Dropdown(
232
+ choices=loaded_models[0]["cleaned_speakers"],
233
+ value=loaded_models[0]["cleaned_speakers"][0],
234
+ visible=False
235
+ )
236
+ for name in loaded_models[0]["cleaned_speakers"]:
237
+ btn = gr.Button(f"🩷 {name}", elem_classes="char-btn")
238
+ btn.click(
239
+ fn=lambda n=name: (n, f"📍 Selected: **{n}**"),
240
+ outputs=[selected_char, char_label]
241
+ )
242
+
243
+ # Input Section
244
+ with gr.Column():
245
+ gr.HTML("""
246
+ <div class="warning-card">
247
+ <div style="color:#ff4d6d;font-weight:800;">🔖 PERINGATAN MINNA 🔖</div>
248
+ Pilih karakter di atas, ketik teks, lalu klik Generate! ✨
249
+ </div>
250
+ """)
251
+
252
+ txt_input = gr.TextArea(label="Input Teks", placeholder="Type something...", lines=3, elem_classes="pink-label")
253
+ btn_random = gr.Button("🎲 RANDOM INPUT TEKS", elem_classes="random-btn")
254
+
255
+ speed_slider = gr.Slider(0.5, 2.0, 1.0, step=0.1, label="Kecepatan Audio", elem_classes="pink-label")
256
+
257
+ btn_generate = gr.Button("💮 GENERATE VOICE 💮", elem_classes="gen-btn")
258
+
259
+ status_msg = gr.Textbox(label="Status", interactive=False, elem_classes="pink-label")
260
+ audio_output = gr.Audio(label="Voice Output", elem_classes=["elegant-audio", "no-label-color"])
261
+
262
+ # Click Events
263
+ btn_random.click(fn=get_random_en_text, outputs=[txt_input])
264
+
265
+ btn_generate.click(
266
+ fn=tts_execute,
267
+ inputs=[model_select, txt_input, selected_char, lang_select, speed_slider],
268
+ outputs=[status_msg, audio_output]
269
+ )
270
+
271
+ # GIF Section
272
+ gr.HTML(f"""
273
+ <div class="gif-container">
274
+ <img src="{GIF_URL}" alt="Haru Urara Concert GIF" loading="lazy">
275
+ </div>
276
+ """)
277
+
278
+ # Aesthetic Diary Box
279
+ gr.HTML("""
280
+ <div class="diary-box">
281
+ <div class="diary-header">Mutsumi Diary</div>
282
+ <div class="diary-content">
283
+ "Kalau kamu suka dengan Models ini, jangan lupa Follow Mutsumi yah?
284
+ Mutsumi senang sekali kalau karyanya dihargai. Tolong jangan ambil modelnya sembarangan tanpa izin! Terima kasih banyak! 💚"
285
+ </div>
286
+ <div style="text-align:right; font-family:'Dancing Script', cursive; color:#ff4d6d; margin-top:10px; font-size:18px;">— Mutsumi</div>
287
+ </div>
288
+ """)
289
+
290
+ # Footer
291
+ gr.HTML("""<div class="credit-footer">💮 CREATED BY MUTSUMI 💮</div>""")
292
+
293
+ # Event Update
294
+ model_select.change(
295
+ fn=update_model_info,
296
+ inputs=[model_select],
297
+ outputs=[char_dropdown_hidden, lang_select]
298
+ )
299
+
300
+ if __name__ == "__main__":
301
+ app.queue().launch(
302
+ server_name="0.0.0.0",
303
+ server_port=7860
304
+ )
Mutsumi-Chan/VITS-Umamusume-Voice/app.py (versi sebelumnya) ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+ import commons
5
+ import utils
6
+ from models import SynthesizerTrn
7
+ import numpy as np
8
+ import json
9
+ import requests
10
+ import logging
11
+ import sys
12
+ import argparse
13
+ import time
14
+ from torch import no_grad, LongTensor
15
+ from text import text_to_sequence
16
+
17
+ # --- Setup Logging ---
18
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # --- Konfigurasi Model ---
22
+ BASE_URL = "https://huggingface.co/spaces/Plana-Archive/VITS-Umamusume-Voice/resolve/main"
23
+ MODELS_CONFIG = [
24
+ {
25
+ "name": "Trilingual",
26
+ "model_file": "G_trilingual.pth",
27
+ "config_file": "uma_trilingual.json",
28
+ "display_name": "🦄 Trilingual Model",
29
+ "languages": ["日本語", "简体中文", "English", "Mix"],
30
+ },
31
+ {
32
+ "name": "Japanese",
33
+ "model_file": "G_jp.pth",
34
+ "config_file": "uma87.json",
35
+ "display_name": "🇯🇵 Japanese Model",
36
+ "languages": ["Japanese"],
37
+ }
38
+ ]
39
+
40
+ LOCAL_DIR, CONFIG_DIR = "pretrained_models", "configs"
41
+ DEFAULT_COVER = "https://huggingface.co/spaces/Plana-Archive/VITS-Umamusume-Voice/resolve/main/cover.png"
42
+
43
+ def download_file(url, local_path):
44
+ if os.path.exists(local_path): return True
45
+ try:
46
+ response = requests.get(url, stream=True)
47
+ os.makedirs(os.path.dirname(local_path), exist_ok=True)
48
+ with open(local_path, 'wb') as f:
49
+ for chunk in response.iter_content(chunk_size=8192): f.write(chunk)
50
+ return True
51
+ except: return False
52
+
53
+ def get_text(text, hps):
54
+ text_norm = text_to_sequence(text, hps.symbols, hps.data.text_cleaners)
55
+ if hps.data.add_blank: text_norm = commons.intersperse(text_norm, 0)
56
+ return LongTensor(text_norm)
57
+
58
+ # --- Load Models Backend ---
59
+ loaded_models = []
60
+ for cfg in MODELS_CONFIG:
61
+ m_p, c_p = os.path.join(LOCAL_DIR, cfg["model_file"]), os.path.join(CONFIG_DIR, cfg["config_file"])
62
+ download_file(f"{BASE_URL}/pretrained_models/{cfg['model_file']}", m_p)
63
+ download_file(f"{BASE_URL}/configs/{cfg['config_file']}", c_p)
64
+ try:
65
+ hps = utils.get_hparams_from_file(c_p)
66
+ net_g = SynthesizerTrn(len(hps.symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, **hps.model)
67
+ utils.load_checkpoint(m_p, net_g, None)
68
+ net_g.eval()
69
+ loaded_models.append({
70
+ "cfg": cfg, "model": net_g, "hps": hps,
71
+ "display_name": cfg["display_name"],
72
+ "speakers": list(hps.speakers.keys()),
73
+ "cleaned_speakers": [s.split('(')[0].strip() for s in hps.speakers.keys()]
74
+ })
75
+ except Exception as e: print(f"Error load {cfg['name']}: {e}")
76
+
77
+ def update_model_ui(model_name):
78
+ m = next((x for x in loaded_models if x["display_name"] == model_name), loaded_models[0])
79
+ return (
80
+ gr.update(choices=m["cleaned_speakers"], value=m["cleaned_speakers"][0]),
81
+ gr.update(choices=m["cfg"]["languages"], value=m["cfg"]["languages"][0]),
82
+ f"⚡ **SYSTEM STATUS**\n● Models: ✅ LOADED\n● Total Models: {len(loaded_models)}\n● Total Speakers: {len(m['speakers'])}"
83
+ )
84
+
85
+ def generate_voice(model_name, text, speaker, lang, speed):
86
+ if not text: return None, "⚠️ Tolong Isi teks dulu kak, yah! ⚠️"
87
+ try:
88
+ m = next((x for x in loaded_models if x["display_name"] == model_name), loaded_models[0])
89
+ full_speaker_name = next(s for s in m["speakers"] if speaker in s)
90
+ speaker_id = m["hps"].speakers[full_speaker_name]
91
+ stn_tst = get_text(text, m["hps"])
92
+ with no_grad():
93
+ x_tst = stn_tst.unsqueeze(0)
94
+ x_tst_lengths = LongTensor([stn_tst.size(0)])
95
+ sid = LongTensor([speaker_id])
96
+ audio = m["model"].infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8, length_scale=1.0/speed)[0][0,0].data.cpu().float().numpy()
97
+ audio = (audio / np.abs(audio).max() * 32767).astype(np.int16)
98
+ return (m["hps"].data.sampling_rate, audio), "✅ Berhasil dibuat!"
99
+ except Exception as e: return None, f"❌ Error: {str(e)}"
100
+
101
+ # ============================================
102
+ # UI INTERFACE
103
+ # ============================================
104
+ with gr.Blocks(css="""
105
+ @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;800&family=Dancing+Script:wght@600&display=swap');
106
+ body { background-color: #fff8f9; font-family: 'Plus Jakarta Sans', sans-serif; }
107
+
108
+ :root { --loader-color: #ff4d6d !important; --primary-500: #ff4d6d !important; }
109
+
110
+ /* CUSTOM LOADER */
111
+ #custom-loader {
112
+ position: fixed; top: 0; left: 0; width: 100%; height: 100%;
113
+ background: radial-gradient(circle, #ffffff 0%, #fff0f3 100%);
114
+ display: flex; flex-direction: column;
115
+ justify-content: center; align-items: center; z-index: 99999;
116
+ transition: opacity 0.8s ease-out;
117
+ }
118
+ .unicorn-bounce {
119
+ font-size: 80px; animation: bounce 0.6s infinite alternate;
120
+ filter: drop-shadow(0 10px 10px rgba(255, 77, 109, 0.2));
121
+ }
122
+ @keyframes bounce { from { transform: translateY(0); } to { transform: translateY(-30px); } }
123
+ .loading-bar-container { width: 200px; height: 6px; background: #ffeef2; border-radius: 10px; margin-top: 20px; overflow: hidden; }
124
+ .loading-bar-progress { width: 100%; height: 100%; background: linear-gradient(90deg, #ff758c, #ff4d6d); animation: loadingLine 2s infinite ease-in-out; transform-origin: left; }
125
+ @keyframes loadingLine { 0% { transform: scaleX(0); } 50% { transform: scaleX(1); } 100% { transform: scaleX(0); transform-origin: right; } }
126
+
127
+ .header-container { text-align: center; padding: 20px 0; }
128
+ .main-title {
129
+ font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;
130
+ font-size: clamp(1.8rem, 8vw, 2.8rem);
131
+ color: #ff4d6d; display: inline-block;
132
+ background: linear-gradient(to bottom, #ff758c 0%, #ff4d6d 100%);
133
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent;
134
+ line-height: 1.1; margin: 0;
135
+ }
136
+
137
+ /* UPDATE: HIJAU TEBAL TANPA SHADOW/LIGHT */
138
+ .sub-title-green {
139
+ font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;
140
+ font-size: clamp(1.2rem, 5vw, 1.8rem);
141
+ color: #32CD32; /* LimeGreen yang padat */
142
+ text-shadow: none !important; /* Hapus semua bayangan */
143
+ text-transform: uppercase; margin: 5px 0;
144
+ }
145
+
146
+ .glow-card {
147
+ background: white !important; border-radius: 30px !important;
148
+ border: 2px solid #ffeef2 !important;
149
+ box-shadow: 0 15px 45px rgba(255, 77, 109, 0.07) !important;
150
+ padding: 25px !important; margin-bottom: 20px !important;
151
+ }
152
+
153
+ .fixed-cover img {
154
+ width: 100% !important;
155
+ aspect-ratio: 2400 / 1350 !important;
156
+ object-fit: cover !important;
157
+ border-radius: 20px !important;
158
+ display: block !important;
159
+ }
160
+
161
+ .btn-generate {
162
+ background: linear-gradient(135deg, #ff758c 0%, #ff4d6d 100%) !important;
163
+ color: white !important; border-radius: 20px !important;
164
+ font-weight: 800 !important; border: none !important;
165
+ box-shadow: 0 10px 30px rgba(255, 77, 109, 0.4) !important;
166
+ height: 70px !important; font-size: 1.4rem !important; cursor: pointer;
167
+ }
168
+
169
+ /* PROMO STYLING */
170
+ .promo-link { text-decoration: none !important; }
171
+ .promo-container {
172
+ margin-top: 25px; padding: 20px;
173
+ background: linear-gradient(135deg, rgba(255, 117, 140, 0.08) 0%, rgba(255, 77, 109, 0.08) 100%);
174
+ border: 2.5px dashed #ffb3c1; border-radius: 25px;
175
+ text-align: center; transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
176
+ }
177
+ .promo-container:hover {
178
+ transform: scale(1.02); background: rgba(255, 240, 243, 0.9); border-color: #ff4d6d;
179
+ }
180
+ .promo-text {
181
+ color: #ff4d6d; font-weight: 800; font-size: 1.2rem;
182
+ margin-bottom: 12px; display: flex; align-items: center; justify-content: center; gap: 10px;
183
+ }
184
+ .gif-display {
185
+ width: 100%; max-width: 220px; margin: 10px auto 0;
186
+ border-radius: 15px; box-shadow: 0 8px 20px rgba(255, 77, 109, 0.2);
187
+ }
188
+
189
+ /* DIARY BOX STYLING */
190
+ .diary-box {
191
+ margin-top: 20px;
192
+ background: #fffafa;
193
+ border-radius: 20px;
194
+ padding: 20px;
195
+ border: 1px solid #ffe5ec;
196
+ box-shadow: inset 0 0 15px rgba(255, 182, 193, 0.1);
197
+ position: relative;
198
+ }
199
+ .diary-header {
200
+ font-family: 'Dancing Script', cursive;
201
+ color: #ff8fab;
202
+ font-size: 1.5rem;
203
+ text-align: center;
204
+ margin-bottom: 10px;
205
+ }
206
+ .diary-content {
207
+ font-size: 0.9rem;
208
+ color: #7d8597;
209
+ line-height: 1.6;
210
+ text-align: center;
211
+ font-style: italic;
212
+ }
213
+ .diary-footer {
214
+ text-align: right;
215
+ font-size: 0.8rem;
216
+ color: #ffb3c1;
217
+ margin-top: 10px;
218
+ font-weight: 600;
219
+ }
220
+
221
+ .char-btn-premium {
222
+ background: rgba(255, 255, 255, 0.6) !important;
223
+ border: 1.5px solid #ffeef2 !important; border-radius: 15px !important;
224
+ color: #ff5d8f !important; font-weight: 700 !important; font-size: 0.85rem !important;
225
+ padding: 10px !important; transition: all 0.3s ease;
226
+ }
227
+ .char-btn-premium:hover { background: #fff0f3 !important; border-color: #ffb3c1 !important; }
228
+
229
+ .premium-footer {
230
+ background: rgba(255, 255, 255, 0.7) !important;
231
+ backdrop-filter: blur(12px); border: 2px solid #ffffff !important;
232
+ border-radius: 30px !important; padding: 25px !important;
233
+ text-align: center; box-shadow: 0 -10px 40px rgba(255, 182, 193, 0.15) !important;
234
+ margin-top: 20px;
235
+ }
236
+ .footer-text-main { color: #5a647e; font-weight: 800; font-size: 0.9rem; letter-spacing: 2px; }
237
+
238
+ .char-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 12px; }
239
+ .scroll-box { height: 350px; overflow-y: auto !important; padding: 10px; }
240
+ .scroll-box::-webkit-scrollbar { width: 6px; }
241
+ .scroll-box::-webkit-scrollbar-thumb { background: #ffb3c1; border-radius: 10px; }
242
+
243
+ footer { display: none !important; }
244
+ """, head="""
245
+ <div id="custom-loader">
246
+ <div class="unicorn-bounce">🦄</div>
247
+ <div class="loading-bar-container"><div class="loading-bar-progress"></div></div>
248
+ <div class="loading-text" style="color:#ff4d6d; margin-top:10px; font-weight:800;">MAGICAL LOADING...</div>
249
+ </div>
250
+ <script>
251
+ window.addEventListener('load', function() {
252
+ setTimeout(function() {
253
+ var loader = document.getElementById('custom-loader');
254
+ if(loader) {
255
+ loader.style.opacity = '0';
256
+ setTimeout(function() { loader.style.display = 'none'; }, 800);
257
+ }
258
+ }, 3000);
259
+ });
260
+ </script>
261
+ """) as demo:
262
+
263
+ gr.HTML("""
264
+ <div class="header-container">
265
+ <h1 class="main-title">🦄 UMAMUSUME PRETTY 🦄</h1>
266
+ <div class="sub-title-green">VITS - by Mutsumi</div>
267
+ <p style="font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 600; font-size: 1rem; color: #5a647e; margin-top: 2px; opacity: 0.8;">
268
+ 🦄 Generate Voice Anime 🦄
269
+ </p>
270
+ </div>
271
+ """)
272
+
273
+ with gr.Row():
274
+ with gr.Column(scale=4):
275
+ with gr.Column(elem_classes="glow-card"):
276
+ gr.HTML(f"""
277
+ <div align="center" class="fixed-cover">
278
+ <img src="{DEFAULT_COVER}" alt="Umamusume TTS Preview">
279
+ </div>
280
+ """)
281
+ status_box = gr.Markdown(f"⚡ **READY**\n● Models: ✅ LOADED")
282
+ model_dropdown = gr.Dropdown(choices=[m["display_name"] for m in loaded_models], value=loaded_models[0]["display_name"], label="Pilih Versi Model")
283
+
284
+ with gr.Column(scale=6):
285
+ with gr.Column(elem_classes="glow-card"):
286
+ text_input = gr.Textbox(label="Input Teks", placeholder="Tuliskan kalimat...", lines=5)
287
+ with gr.Row():
288
+ char_dropdown = gr.Dropdown(choices=loaded_models[0]["cleaned_speakers"], value=loaded_models[0]["cleaned_speakers"][0], label="🏷️ Pilih Character")
289
+ lang_dropdown = gr.Dropdown(choices=loaded_models[0]["cfg"]["languages"], value=loaded_models[0]["cfg"]["languages"][0], label="📑 Bahasa")
290
+ speed_slider = gr.Slider(0.5, 2.0, 1.0, step=0.1, label="Kecepatan")
291
+ generate_btn = gr.Button("GENERATE VOICE", elem_classes="btn-generate")
292
+
293
+ # --- ADS / MODE LAINNYA SECTION ---
294
+ gr.HTML("""
295
+ <a href="https://huggingface.co/Plana-Archive" target="_blank" class="promo-link">
296
+ <div class="promo-container">
297
+ <div class="promo-text">
298
+ <span>🍒</span> Lihat Mode Anime Lainnya <span>🍒</span>
299
+ </div>
300
+ <div style="font-size: 0.85rem; color: #5a647e; margin-bottom: 10px; font-weight: 600;">
301
+ Klik di sini untuk mengunjungi koleksi Plana-Archive
302
+ </div>
303
+ <img src="https://huggingface.co/spaces/Library-Anime/DATE-A-LIVE/resolve/main/kurumi-tokisaki.gif" class="gif-display" alt="Kurumi GIF">
304
+ </div>
305
+ </a>
306
+
307
+ <div class="diary-box">
308
+ <div class="diary-header">🌿Mutsumi Diary🌿</div>
309
+ <div class="diary-content">
310
+ "Umm..kalau kamu suka dengan Models ini, jangan lupa Follow Mutsumi yah?
311
+ Mutsumi Senang sekali kalau karyanya dihargai.
312
+ tolong jangan ambil modelnya sembarangan tanpa izin yah!
313
+ Terima kasih!💚"
314
+ </div>
315
+ <div class="diary-footer">🍃BY Mutsumi—</div>
316
+ </div>
317
+ """)
318
+
319
+ with gr.Column(elem_classes="glow-card"):
320
+ audio_out = gr.Audio(label=None, type="numpy")
321
+ status_msg = gr.Markdown("🌺 HASILNYA AKAN MUNCUL CEK SINI 🌺")
322
+
323
+ with gr.Column(elem_classes="glow-card"):
324
+ gr.HTML("""
325
+ <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 20px;">
326
+ <span style="font-size: 1.5rem;">📑</span>
327
+ <h3 style="color: #ff4d6d; margin: 0; font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 800;">Daftar Karakter Tersedia</h3>
328
+ </div>
329
+ """)
330
+ with gr.Column(elem_classes="scroll-box"):
331
+ with gr.Row(elem_classes="char-grid"):
332
+ for name in loaded_models[0]["cleaned_speakers"]:
333
+ btn = gr.Button(f"🩷 {name}", elem_classes="char-btn-premium")
334
+ btn.click(lambda n=name: gr.update(value=n), None, char_dropdown)
335
+
336
+ gr.HTML("""
337
+ <div class="premium-footer">
338
+ <div class="footer-text-main">🍀 CREATED BY MUTSUMI 🍀</div>
339
+ <div style="color: #8e9aaf; font-weight: 600; font-size: 0.85rem; margin-top: 5px;">
340
+ Umamusume Pretty • Powered by VITS
341
+ </div>
342
+ <div style="margin-top: 15px; color: #ffb3c1; font-weight: 600; font-size: 0.8rem;">
343
+ 🦄 Built with Gradio 🦄
344
+ </div>
345
+ </div>
346
+ """)
347
+
348
+ model_dropdown.change(update_model_ui, inputs=[model_dropdown], outputs=[char_dropdown, lang_dropdown, status_box])
349
+
350
+ generate_btn.click(
351
+ lambda: "🌷Generate teks menjadi suara ♻️",
352
+ outputs=[status_msg]
353
+ ).then(
354
+ generate_voice,
355
+ inputs=[model_dropdown, text_input, char_dropdown, lang_dropdown, speed_slider],
356
+ outputs=[audio_out, status_msg],
357
+ show_progress="full"
358
+ )
359
+
360
+ if __name__ == "__main__":
361
+ demo.launch(favicon_path="https://fav.farm/🩷")
Mutsumi-Chan/VITS-Umamusume-Voice/attentions.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ from modules import LayerNorm
8
+
9
+
10
+ class Encoder(nn.Module):
11
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
12
+ super().__init__()
13
+ self.hidden_channels = hidden_channels
14
+ self.filter_channels = filter_channels
15
+ self.n_heads = n_heads
16
+ self.n_layers = n_layers
17
+ self.kernel_size = kernel_size
18
+ self.p_dropout = p_dropout
19
+ self.window_size = window_size
20
+
21
+ self.drop = nn.Dropout(p_dropout)
22
+ self.attn_layers = nn.ModuleList()
23
+ self.norm_layers_1 = nn.ModuleList()
24
+ self.ffn_layers = nn.ModuleList()
25
+ self.norm_layers_2 = nn.ModuleList()
26
+ for i in range(self.n_layers):
27
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
28
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
29
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
30
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
31
+
32
+ def forward(self, x, x_mask):
33
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
34
+ x = x * x_mask
35
+ for i in range(self.n_layers):
36
+ y = self.attn_layers[i](x, x, attn_mask)
37
+ y = self.drop(y)
38
+ x = self.norm_layers_1[i](x + y)
39
+
40
+ y = self.ffn_layers[i](x, x_mask)
41
+ y = self.drop(y)
42
+ x = self.norm_layers_2[i](x + y)
43
+ x = x * x_mask
44
+ return x
45
+
46
+
47
+ class Decoder(nn.Module):
48
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
49
+ super().__init__()
50
+ self.hidden_channels = hidden_channels
51
+ self.filter_channels = filter_channels
52
+ self.n_heads = n_heads
53
+ self.n_layers = n_layers
54
+ self.kernel_size = kernel_size
55
+ self.p_dropout = p_dropout
56
+ self.proximal_bias = proximal_bias
57
+ self.proximal_init = proximal_init
58
+
59
+ self.drop = nn.Dropout(p_dropout)
60
+ self.self_attn_layers = nn.ModuleList()
61
+ self.norm_layers_0 = nn.ModuleList()
62
+ self.encdec_attn_layers = nn.ModuleList()
63
+ self.norm_layers_1 = nn.ModuleList()
64
+ self.ffn_layers = nn.ModuleList()
65
+ self.norm_layers_2 = nn.ModuleList()
66
+ for i in range(self.n_layers):
67
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
68
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
69
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
70
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
71
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
72
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
73
+
74
+ def forward(self, x, x_mask, h, h_mask):
75
+ """
76
+ x: decoder input
77
+ h: encoder output
78
+ """
79
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
80
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
81
+ x = x * x_mask
82
+ for i in range(self.n_layers):
83
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
84
+ y = self.drop(y)
85
+ x = self.norm_layers_0[i](x + y)
86
+
87
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
88
+ y = self.drop(y)
89
+ x = self.norm_layers_1[i](x + y)
90
+
91
+ y = self.ffn_layers[i](x, x_mask)
92
+ y = self.drop(y)
93
+ x = self.norm_layers_2[i](x + y)
94
+ x = x * x_mask
95
+ return x
96
+
97
+
98
+ class MultiHeadAttention(nn.Module):
99
+ def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
100
+ super().__init__()
101
+ assert channels % n_heads == 0
102
+
103
+ self.channels = channels
104
+ self.out_channels = out_channels
105
+ self.n_heads = n_heads
106
+ self.p_dropout = p_dropout
107
+ self.window_size = window_size
108
+ self.heads_share = heads_share
109
+ self.block_length = block_length
110
+ self.proximal_bias = proximal_bias
111
+ self.proximal_init = proximal_init
112
+ self.attn = None
113
+
114
+ self.k_channels = channels // n_heads
115
+ self.conv_q = nn.Conv1d(channels, channels, 1)
116
+ self.conv_k = nn.Conv1d(channels, channels, 1)
117
+ self.conv_v = nn.Conv1d(channels, channels, 1)
118
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
119
+ self.drop = nn.Dropout(p_dropout)
120
+
121
+ if window_size is not None:
122
+ n_heads_rel = 1 if heads_share else n_heads
123
+ rel_stddev = self.k_channels**-0.5
124
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
125
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
126
+
127
+ nn.init.xavier_uniform_(self.conv_q.weight)
128
+ nn.init.xavier_uniform_(self.conv_k.weight)
129
+ nn.init.xavier_uniform_(self.conv_v.weight)
130
+ if proximal_init:
131
+ with torch.no_grad():
132
+ self.conv_k.weight.copy_(self.conv_q.weight)
133
+ self.conv_k.bias.copy_(self.conv_q.bias)
134
+
135
+ def forward(self, x, c, attn_mask=None):
136
+ q = self.conv_q(x)
137
+ k = self.conv_k(c)
138
+ v = self.conv_v(c)
139
+
140
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
141
+
142
+ x = self.conv_o(x)
143
+ return x
144
+
145
+ def attention(self, query, key, value, mask=None):
146
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
147
+ b, d, t_s, t_t = (*key.size(), query.size(2))
148
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
149
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
150
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
151
+
152
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
153
+ if self.window_size is not None:
154
+ assert t_s == t_t, "Relative attention is only available for self-attention."
155
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
156
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
157
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
158
+ scores = scores + scores_local
159
+ if self.proximal_bias:
160
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
161
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
162
+ if mask is not None:
163
+ scores = scores.masked_fill(mask == 0, -1e4)
164
+ if self.block_length is not None:
165
+ assert t_s == t_t, "Local attention is only available for self-attention."
166
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
167
+ scores = scores.masked_fill(block_mask == 0, -1e4)
168
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
169
+ p_attn = self.drop(p_attn)
170
+ output = torch.matmul(p_attn, value)
171
+ if self.window_size is not None:
172
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
173
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
174
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
175
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
176
+ return output, p_attn
177
+
178
+ def _matmul_with_relative_values(self, x, y):
179
+ """
180
+ x: [b, h, l, m]
181
+ y: [h or 1, m, d]
182
+ ret: [b, h, l, d]
183
+ """
184
+ ret = torch.matmul(x, y.unsqueeze(0))
185
+ return ret
186
+
187
+ def _matmul_with_relative_keys(self, x, y):
188
+ """
189
+ x: [b, h, l, d]
190
+ y: [h or 1, m, d]
191
+ ret: [b, h, l, m]
192
+ """
193
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
194
+ return ret
195
+
196
+ def _get_relative_embeddings(self, relative_embeddings, length):
197
+ max_relative_position = 2 * self.window_size + 1
198
+ # Pad first before slice to avoid using cond ops.
199
+ pad_length = max(length - (self.window_size + 1), 0)
200
+ slice_start_position = max((self.window_size + 1) - length, 0)
201
+ slice_end_position = slice_start_position + 2 * length - 1
202
+ if pad_length > 0:
203
+ padded_relative_embeddings = F.pad(
204
+ relative_embeddings,
205
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
206
+ else:
207
+ padded_relative_embeddings = relative_embeddings
208
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
209
+ return used_relative_embeddings
210
+
211
+ def _relative_position_to_absolute_position(self, x):
212
+ """
213
+ x: [b, h, l, 2*l-1]
214
+ ret: [b, h, l, l]
215
+ """
216
+ batch, heads, length, _ = x.size()
217
+ # Concat columns of pad to shift from relative to absolute indexing.
218
+ x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
219
+
220
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
221
+ x_flat = x.view([batch, heads, length * 2 * length])
222
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
223
+
224
+ # Reshape and slice out the padded elements.
225
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
226
+ return x_final
227
+
228
+ def _absolute_position_to_relative_position(self, x):
229
+ """
230
+ x: [b, h, l, l]
231
+ ret: [b, h, l, 2*l-1]
232
+ """
233
+ batch, heads, length, _ = x.size()
234
+ # padd along column
235
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
236
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
237
+ # add 0's in the beginning that will skew the elements after reshape
238
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
239
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
240
+ return x_final
241
+
242
+ def _attention_bias_proximal(self, length):
243
+ """Bias for self-attention to encourage attention to close positions.
244
+ Args:
245
+ length: an integer scalar.
246
+ Returns:
247
+ a Tensor with shape [1, 1, length, length]
248
+ """
249
+ r = torch.arange(length, dtype=torch.float32)
250
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
251
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
252
+
253
+
254
+ class FFN(nn.Module):
255
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
256
+ super().__init__()
257
+ self.in_channels = in_channels
258
+ self.out_channels = out_channels
259
+ self.filter_channels = filter_channels
260
+ self.kernel_size = kernel_size
261
+ self.p_dropout = p_dropout
262
+ self.activation = activation
263
+ self.causal = causal
264
+
265
+ if causal:
266
+ self.padding = self._causal_padding
267
+ else:
268
+ self.padding = self._same_padding
269
+
270
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
271
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
272
+ self.drop = nn.Dropout(p_dropout)
273
+
274
+ def forward(self, x, x_mask):
275
+ x = self.conv_1(self.padding(x * x_mask))
276
+ if self.activation == "gelu":
277
+ x = x * torch.sigmoid(1.702 * x)
278
+ else:
279
+ x = torch.relu(x)
280
+ x = self.drop(x)
281
+ x = self.conv_2(self.padding(x * x_mask))
282
+ return x * x_mask
283
+
284
+ def _causal_padding(self, x):
285
+ if self.kernel_size == 1:
286
+ return x
287
+ pad_l = self.kernel_size - 1
288
+ pad_r = 0
289
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
290
+ x = F.pad(x, commons.convert_pad_shape(padding))
291
+ return x
292
+
293
+ def _same_padding(self, x):
294
+ if self.kernel_size == 1:
295
+ return x
296
+ pad_l = (self.kernel_size - 1) // 2
297
+ pad_r = self.kernel_size // 2
298
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
299
+ x = F.pad(x, commons.convert_pad_shape(padding))
300
+ return x
Mutsumi-Chan/VITS-Umamusume-Voice/commons.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch.nn import functional as F
4
+ import torch.jit
5
+
6
+
7
+ def script_method(fn, _rcb=None):
8
+ return fn
9
+
10
+
11
+ def script(obj, optimize=True, _frames_up=0, _rcb=None):
12
+ return obj
13
+
14
+
15
+ torch.jit.script_method = script_method
16
+ torch.jit.script = script
17
+
18
+
19
+ def init_weights(m, mean=0.0, std=0.01):
20
+ classname = m.__class__.__name__
21
+ if classname.find("Conv") != -1:
22
+ m.weight.data.normal_(mean, std)
23
+
24
+
25
+ def get_padding(kernel_size, dilation=1):
26
+ return int((kernel_size*dilation - dilation)/2)
27
+
28
+
29
+ def intersperse(lst, item):
30
+ result = [item] * (len(lst) * 2 + 1)
31
+ result[1::2] = lst
32
+ return result
33
+
34
+
35
+ def slice_segments(x, ids_str, segment_size=4):
36
+ ret = torch.zeros_like(x[:, :, :segment_size])
37
+ for i in range(x.size(0)):
38
+ idx_str = ids_str[i]
39
+ idx_end = idx_str + segment_size
40
+ ret[i] = x[i, :, idx_str:idx_end]
41
+ return ret
42
+
43
+
44
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
45
+ b, d, t = x.size()
46
+ if x_lengths is None:
47
+ x_lengths = t
48
+ ids_str_max = x_lengths - segment_size + 1
49
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
50
+ ret = slice_segments(x, ids_str, segment_size)
51
+ return ret, ids_str
52
+
53
+
54
+ def subsequent_mask(length):
55
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
56
+ return mask
57
+
58
+
59
+ @torch.jit.script
60
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
61
+ n_channels_int = n_channels[0]
62
+ in_act = input_a + input_b
63
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
64
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
65
+ acts = t_act * s_act
66
+ return acts
67
+
68
+
69
+ def convert_pad_shape(pad_shape):
70
+ l = pad_shape[::-1]
71
+ pad_shape = [item for sublist in l for item in sublist]
72
+ return pad_shape
73
+
74
+
75
+ def sequence_mask(length, max_length=None):
76
+ if max_length is None:
77
+ max_length = length.max()
78
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
79
+ return x.unsqueeze(0) < length.unsqueeze(1)
80
+
81
+
82
+ def generate_path(duration, mask):
83
+ """
84
+ duration: [b, 1, t_x]
85
+ mask: [b, 1, t_y, t_x]
86
+ """
87
+ device = duration.device
88
+
89
+ b, _, t_y, t_x = mask.shape
90
+ cum_duration = torch.cumsum(duration, -1)
91
+
92
+ cum_duration_flat = cum_duration.view(b * t_x)
93
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
94
+ path = path.view(b, t_x, t_y)
95
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
96
+ path = path.unsqueeze(1).transpose(2,3) * mask
97
+ return path
Mutsumi-Chan/VITS-Umamusume-Voice/configs/uma87.json ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 1,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"E:/uma_voice/output_train.txt.cleaned",
21
+ "validation_files":"E:/uma_voice/output_val.txt.cleaned",
22
+ "text_cleaners":["japanese_cleaners"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 87,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "speakers": {"特别周 Special Week (Umamusume Pretty Derby)": 0,
54
+ "无声铃鹿 Silence Suzuka (Umamusume Pretty Derby)": 1,
55
+ "东海帝王 Tokai Teio (Umamusume Pretty Derby)": 2,
56
+ "丸善斯基 Maruzensky (Umamusume Pretty Derby)": 3,
57
+ "富士奇迹 Fuji Kiseki (Umamusume Pretty Derby)": 4,
58
+ "小栗帽 Oguri Cap (Umamusume Pretty Derby)": 5,
59
+ "黄金船 Gold Ship (Umamusume Pretty Derby)": 6,
60
+ "伏特加 Vodka (Umamusume Pretty Derby)": 7,
61
+ "大和赤骥 Daiwa Scarlet (Umamusume Pretty Derby)": 8,
62
+ "大树快车 Taiki Shuttle (Umamusume Pretty Derby)": 9,
63
+ "草上飞 Grass Wonder (Umamusume Pretty Derby)": 10,
64
+ "菱亚马逊 Hishi Amazon (Umamusume Pretty Derby)": 11,
65
+ "目白麦昆 Mejiro Mcqueen (Umamusume Pretty Derby)": 12,
66
+ "神鹰 El Condor Pasa (Umamusume Pretty Derby)": 13,
67
+ "好歌剧 T.M. Opera O (Umamusume Pretty Derby)": 14,
68
+ "成田白仁 Narita Brian (Umamusume Pretty Derby)": 15,
69
+ "鲁道夫象征 Symboli Rudolf (Umamusume Pretty Derby)": 16,
70
+ "气槽 Air Groove (Umamusume Pretty Derby)": 17,
71
+ "爱丽数码 Agnes Digital (Umamusume Pretty Derby)": 18,
72
+ "青云天空 Seiun Sky (Umamusume Pretty Derby)": 19,
73
+ "玉藻十字 Tamamo Cross (Umamusume Pretty Derby)": 20,
74
+ "美妙姿势 Fine Motion (Umamusume Pretty Derby)": 21,
75
+ "琵琶晨光 Biwa Hayahide (Umamusume Pretty Derby)": 22,
76
+ "重炮 Mayano Topgun (Umamusume Pretty Derby)": 23,
77
+ "曼城茶座 Manhattan Cafe (Umamusume Pretty Derby)": 24,
78
+ "美普波旁 Mihono Bourbon (Umamusume Pretty Derby)": 25,
79
+ "目白雷恩 Mejiro Ryan (Umamusume Pretty Derby)": 26,
80
+ "雪之美人 Yukino Bijin (Umamusume Pretty Derby)": 28,
81
+ "米浴 Rice Shower (Umamusume Pretty Derby)": 29,
82
+ "艾尼斯风神 Ines Fujin (Umamusume Pretty Derby)": 30,
83
+ "爱丽速子 Agnes Tachyon (Umamusume Pretty Derby)": 31,
84
+ "爱慕织姬 Admire Vega (Umamusume Pretty Derby)": 32,
85
+ "稻荷一 Inari One (Umamusume Pretty Derby)": 33,
86
+ "胜利奖券 Winning Ticket (Umamusume Pretty Derby)": 34,
87
+ "空中神宫 Air Shakur (Umamusume Pretty Derby)": 35,
88
+ "荣进闪耀 Eishin Flash (Umamusume Pretty Derby)": 36,
89
+ "真机伶 Curren Chan (Umamusume Pretty Derby)": 37,
90
+ "川上公主 Kawakami Princess (Umamusume Pretty Derby)": 38,
91
+ "黄金城市 Gold City (Umamusume Pretty Derby)": 39,
92
+ "樱花进王 Sakura Bakushin O (Umamusume Pretty Derby)": 40,
93
+ "采珠 Seeking the Pearl (Umamusume Pretty Derby)": 41,
94
+ "新光风 Shinko Windy (Umamusume Pretty Derby)": 42,
95
+ "东商变革 Sweep Tosho (Umamusume Pretty Derby)": 43,
96
+ "超级小溪 Super Creek (Umamusume Pretty Derby)": 44,
97
+ "醒目飞鹰 Smart Falcon (Umamusume Pretty Derby)": 45,
98
+ "荒漠英雄 Zenno Rob Roy (Umamusume Pretty Derby)": 46,
99
+ "东瀛佐敦 Tosen Jordan (Umamusume Pretty Derby)": 47,
100
+ "中山庆典 Nakayama Festa (Umamusume Pretty Derby)": 48,
101
+ "成田大进 Narita Taishin (Umamusume Pretty Derby)": 49,
102
+ "西野花 Nishino Flower (Umamusume Pretty Derby)": 50,
103
+ "春乌拉拉 Haru Urara (Umamusume Pretty Derby)": 51,
104
+ "青竹回忆 Bamboo Memory (Umamusume Pretty Derby)": 52,
105
+ "待兼福来 Matikane Fukukitaru (Umamusume Pretty Derby)": 55,
106
+ "名将怒涛 Meisho Doto (Umamusume Pretty Derby)": 57,
107
+ "目白多伯 Mejiro Dober (Umamusume Pretty Derby)": 58,
108
+ "优秀素质 Nice Nature (Umamusume Pretty Derby)": 59,
109
+ "帝王光环 King Halo (Umamusume Pretty Derby)": 60,
110
+ "待兼诗歌剧 Matikane Tannhauser (Umamusume Pretty Derby)": 61,
111
+ "生野狄杜斯 Ikuno Dictus (Umamusume Pretty Derby)": 62,
112
+ "目白善信 Mejiro Palmer (Umamusume Pretty Derby)": 63,
113
+ "大拓太阳神 Daitaku Helios (Umamusume Pretty Derby)": 64,
114
+ "双涡轮 Twin Turbo (Umamusume Pretty Derby)": 65,
115
+ "里见光钻 Satono Diamond (Umamusume Pretty Derby)": 66,
116
+ "北部玄驹 Kitasan Black (Umamusume Pretty Derby)": 67,
117
+ "樱花千代王 Sakura Chiyono O (Umamusume Pretty Derby)": 68,
118
+ "天狼星象征 Sirius Symboli (Umamusume Pretty Derby)": 69,
119
+ "目白阿尔丹 Mejiro Ardan (Umamusume Pretty Derby)": 70,
120
+ "八重无敌 Yaeno Muteki (Umamusume Pretty Derby)": 71,
121
+ "鹤丸刚志 Tsurumaru Tsuyoshi (Umamusume Pretty Derby)": 72,
122
+ "目白光明 Mejiro Bright (Umamusume Pretty Derby)": 73,
123
+ "樱花桂冠 Sakura Laurel (Umamusume Pretty Derby)": 74,
124
+ "成田路 Narita Top Road (Umamusume Pretty Derby)": 75,
125
+ "也文摄辉 Yamanin Zephyr (Umamusume Pretty Derby)": 76,
126
+ "真弓快车 Aston Machan (Umamusume Pretty Derby)": 80,
127
+ "骏川手纲 Hayakawa Tazuna (Umamusume Pretty Derby)": 81,
128
+ "小林历奇 Kopano Rickey (Umamusume Pretty Derby)": 83,
129
+ "奇锐骏 Wonder Acute (Umamusume Pretty Derby)": 85,
130
+ "秋川理事长 President Akikawa (Umamusume Pretty Derby)": 86
131
+ },
132
+ "symbols": ["_", ",", ".", "!", "?", "-", "A", "E", "I", "N", "O", "Q", "U", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "o", "p", "r", "s", "t", "u", "v", "w", "y", "z", "\u0283", "\u02a7", "\u2193", "\u2191", " "]
133
+ }
Mutsumi-Chan/VITS-Umamusume-Voice/configs/uma_trilingual.json ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 2e-4,
8
+ "betas": [0.8, 0.99],
9
+ "eps": 1e-9,
10
+ "batch_size": 16,
11
+ "fp16_run": true,
12
+ "lr_decay": 0.999875,
13
+ "segment_size": 8192,
14
+ "init_lr_ratio": 1,
15
+ "warmup_epochs": 0,
16
+ "c_mel": 45,
17
+ "c_kl": 1.0
18
+ },
19
+ "data": {
20
+ "training_files":"../CH_JA_EN_mix_voice/clipped_3_vits_trilingual_annotations.train.txt.cleaned",
21
+ "validation_files":"../CH_JA_EN_mix_voice/clipped_3_vits_trilingual_annotations.val.txt.cleaned",
22
+ "text_cleaners":["cjke_cleaners2"],
23
+ "max_wav_value": 32768.0,
24
+ "sampling_rate": 22050,
25
+ "filter_length": 1024,
26
+ "hop_length": 256,
27
+ "win_length": 1024,
28
+ "n_mel_channels": 80,
29
+ "mel_fmin": 0.0,
30
+ "mel_fmax": null,
31
+ "add_blank": true,
32
+ "n_speakers": 999,
33
+ "cleaned_text": true
34
+ },
35
+ "model": {
36
+ "inter_channels": 192,
37
+ "hidden_channels": 192,
38
+ "filter_channels": 768,
39
+ "n_heads": 2,
40
+ "n_layers": 6,
41
+ "kernel_size": 3,
42
+ "p_dropout": 0.1,
43
+ "resblock": "1",
44
+ "resblock_kernel_sizes": [3,7,11],
45
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
46
+ "upsample_rates": [8,8,2,2],
47
+ "upsample_initial_channel": 512,
48
+ "upsample_kernel_sizes": [16,16,4,4],
49
+ "n_layers_q": 3,
50
+ "use_spectral_norm": false,
51
+ "gin_channels": 256
52
+ },
53
+ "symbols": ["_", ",", ".", "!", "?", "-", "~", "\u2026", "N", "Q", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "s", "t", "u", "v", "w", "x", "y", "z", "\u0251", "\u00e6", "\u0283", "\u0291", "\u00e7", "\u026f", "\u026a", "\u0254", "\u025b", "\u0279", "\u00f0", "\u0259", "\u026b", "\u0265", "\u0278", "\u028a", "\u027e", "\u0292", "\u03b8", "\u03b2", "\u014b", "\u0266", "\u207c", "\u02b0", "`", "^", "#", "*", "=", "\u02c8", "\u02cc", "\u2192", "\u2193", "\u2191", " "],
54
+ "speakers": {"特别周 Special Week (Umamusume Pretty Derby)": 0,
55
+ "无声铃鹿 Silence Suzuka (Umamusume Pretty Derby)": 1,
56
+ "东海帝王 Tokai Teio (Umamusume Pretty Derby)": 2,
57
+ "丸善斯基 Maruzensky (Umamusume Pretty Derby)": 3,
58
+ "富士奇迹 Fuji Kiseki (Umamusume Pretty Derby)": 4,
59
+ "小栗帽 Oguri Cap (Umamusume Pretty Derby)": 5,
60
+ "黄金船 Gold Ship (Umamusume Pretty Derby)": 6,
61
+ "伏特加 Vodka (Umamusume Pretty Derby)": 7,
62
+ "大和赤骥 Daiwa Scarlet (Umamusume Pretty Derby)": 8,
63
+ "大树快车 Taiki Shuttle (Umamusume Pretty Derby)": 9,
64
+ "草上飞 Grass Wonder (Umamusume Pretty Derby)": 10,
65
+ "菱亚马逊 Hishi Amazon (Umamusume Pretty Derby)": 11,
66
+ "目白麦昆 Mejiro Mcqueen (Umamusume Pretty Derby)": 12,
67
+ "神鹰 El Condor Pasa (Umamusume Pretty Derby)": 13,
68
+ "好歌剧 T.M. Opera O (Umamusume Pretty Derby)": 14,
69
+ "成田白仁 Narita Brian (Umamusume Pretty Derby)": 15,
70
+ "鲁道夫象征 Symboli Rudolf (Umamusume Pretty Derby)": 16,
71
+ "气槽 Air Groove (Umamusume Pretty Derby)": 17,
72
+ "爱丽数码 Agnes Digital (Umamusume Pretty Derby)": 18,
73
+ "青云天空 Seiun Sky (Umamusume Pretty Derby)": 19,
74
+ "玉藻十字 Tamamo Cross (Umamusume Pretty Derby)": 20,
75
+ "美妙姿势 Fine Motion (Umamusume Pretty Derby)": 21,
76
+ "琵琶晨光 Biwa Hayahide (Umamusume Pretty Derby)": 22,
77
+ "重炮 Mayano Topgun (Umamusume Pretty Derby)": 23,
78
+ "曼城茶座 Manhattan Cafe (Umamusume Pretty Derby)": 24,
79
+ "美普波旁 Mihono Bourbon (Umamusume Pretty Derby)": 25,
80
+ "目白雷恩 Mejiro Ryan (Umamusume Pretty Derby)": 26,
81
+ "雪之美人 Yukino Bijin (Umamusume Pretty Derby)": 28,
82
+ "米浴 Rice Shower (Umamusume Pretty Derby)": 29,
83
+ "艾尼斯风神 Ines Fujin (Umamusume Pretty Derby)": 30,
84
+ "爱丽速子 Agnes Tachyon (Umamusume Pretty Derby)": 31,
85
+ "爱慕织姬 Admire Vega (Umamusume Pretty Derby)": 32,
86
+ "稻荷一 Inari One (Umamusume Pretty Derby)": 33,
87
+ "胜利奖券 Winning Ticket (Umamusume Pretty Derby)": 34,
88
+ "空中神宫 Air Shakur (Umamusume Pretty Derby)": 35,
89
+ "荣进闪耀 Eishin Flash (Umamusume Pretty Derby)": 36,
90
+ "真机伶 Curren Chan (Umamusume Pretty Derby)": 37,
91
+ "川上公主 Kawakami Princess (Umamusume Pretty Derby)": 38,
92
+ "黄金城市 Gold City (Umamusume Pretty Derby)": 39,
93
+ "樱花进王 Sakura Bakushin O (Umamusume Pretty Derby)": 40,
94
+ "采珠 Seeking the Pearl (Umamusume Pretty Derby)": 41,
95
+ "新光风 Shinko Windy (Umamusume Pretty Derby)": 42,
96
+ "东商变革 Sweep Tosho (Umamusume Pretty Derby)": 43,
97
+ "超级小溪 Super Creek (Umamusume Pretty Derby)": 44,
98
+ "醒目飞鹰 Smart Falcon (Umamusume Pretty Derby)": 45,
99
+ "荒漠英雄 Zenno Rob Roy (Umamusume Pretty Derby)": 46,
100
+ "东瀛佐敦 Tosen Jordan (Umamusume Pretty Derby)": 47,
101
+ "中山庆典 Nakayama Festa (Umamusume Pretty Derby)": 48,
102
+ "成田大进 Narita Taishin (Umamusume Pretty Derby)": 49,
103
+ "西野花 Nishino Flower (Umamusume Pretty Derby)": 50,
104
+ "春乌拉拉 Haru Urara (Umamusume Pretty Derby)": 51,
105
+ "青竹回忆 Bamboo Memory (Umamusume Pretty Derby)": 52,
106
+ "待兼福来 Matikane Fukukitaru (Umamusume Pretty Derby)": 55,
107
+ "名将怒涛 Meisho Doto (Umamusume Pretty Derby)": 57,
108
+ "目白多伯 Mejiro Dober (Umamusume Pretty Derby)": 58,
109
+ "优秀素质 Nice Nature (Umamusume Pretty Derby)": 59,
110
+ "帝王光环 King Halo (Umamusume Pretty Derby)": 60,
111
+ "待兼诗歌剧 Matikane Tannhauser (Umamusume Pretty Derby)": 61,
112
+ "生野狄杜斯 Ikuno Dictus (Umamusume Pretty Derby)": 62,
113
+ "目白善信 Mejiro Palmer (Umamusume Pretty Derby)": 63,
114
+ "大拓太阳神 Daitaku Helios (Umamusume Pretty Derby)": 64,
115
+ "双涡轮 Twin Turbo (Umamusume Pretty Derby)": 65,
116
+ "里见光钻 Satono Diamond (Umamusume Pretty Derby)": 66,
117
+ "北部玄驹 Kitasan Black (Umamusume Pretty Derby)": 67,
118
+ "樱花千代王 Sakura Chiyono O (Umamusume Pretty Derby)": 68,
119
+ "天狼星象征 Sirius Symboli (Umamusume Pretty Derby)": 69,
120
+ "目白阿尔丹 Mejiro Ardan (Umamusume Pretty Derby)": 70,
121
+ "八重无敌 Yaeno Muteki (Umamusume Pretty Derby)": 71,
122
+ "鹤丸刚志 Tsurumaru Tsuyoshi (Umamusume Pretty Derby)": 72,
123
+ "目白光明 Mejiro Bright (Umamusume Pretty Derby)": 73,
124
+ "樱花桂冠 Sakura Laurel (Umamusume Pretty Derby)": 74,
125
+ "成田路 Narita Top Road (Umamusume Pretty Derby)": 75,
126
+ "也文摄辉 Yamanin Zephyr (Umamusume Pretty Derby)": 76,
127
+ "真弓快车 Aston Machan (Umamusume Pretty Derby)": 80,
128
+ "骏川手纲 Hayakawa Tazuna (Umamusume Pretty Derby)": 81,
129
+ "小林历奇 Kopano Rickey (Umamusume Pretty Derby)": 83,
130
+ "奇锐骏 Wonder Acute (Umamusume Pretty Derby)": 85,
131
+ "秋川理事长 President Akikawa (Umamusume Pretty Derby)": 86,
132
+ "綾地 寧々 Ayachi Nene (Sanoba Witch)": 87,
133
+ "因幡 めぐる Inaba Meguru (Sanoba Witch)": 88,
134
+ "椎葉 紬 Shiiba Tsumugi (Sanoba Witch)": 89,
135
+ "仮屋 和奏 Kariya Wakama (Sanoba Witch)": 90,
136
+ "戸隠 憧子 Togakushi Touko (Sanoba Witch)": 91,
137
+ "九条裟罗 Kujou Sara (Genshin Impact)": 92,
138
+ "芭芭拉 Barbara (Genshin Impact)": 93,
139
+ "派蒙 Paimon (Genshin Impact)": 94,
140
+ "荒泷一斗 Arataki Itto (Genshin Impact)": 96,
141
+ "早柚 Sayu (Genshin Impact)": 97,
142
+ "香菱 Xiangling (Genshin Impact)": 98,
143
+ "神里绫华 Kamisato Ayaka (Genshin Impact)": 99,
144
+ "重云 Chongyun (Genshin Impact)": 100,
145
+ "流浪者 Wanderer (Genshin Impact)": 102,
146
+ "优菈 Eula (Genshin Impact)": 103,
147
+ "凝光 Ningguang (Genshin Impact)": 105,
148
+ "钟离 Zhongli (Genshin Impact)": 106,
149
+ "雷电将军 Raiden Shogun (Genshin Impact)": 107,
150
+ "枫原万叶 Kaedehara Kazuha (Genshin Impact)": 108,
151
+ "赛诺 Cyno (Genshin Impact)": 109,
152
+ "诺艾尔 Noelle (Genshin Impact)": 112,
153
+ "八重神子 Yae Miko (Genshin Impact)": 113,
154
+ "凯亚 Kaeya (Genshin Impact)": 114,
155
+ "魈 Xiao (Genshin Impact)": 115,
156
+ "托马 Thoma (Genshin Impact)": 116,
157
+ "可莉 Klee (Genshin Impact)": 117,
158
+ "迪卢克 Diluc (Genshin Impact)": 120,
159
+ "夜兰 Yelan (Genshin Impact)": 121,
160
+ "鹿野院平藏 Shikanoin Heizou (Genshin Impact)": 123,
161
+ "辛焱 Xinyan (Genshin Impact)": 124,
162
+ "丽莎 Lisa (Genshin Impact)": 125,
163
+ "云堇 Yun Jin (Genshin Impact)": 126,
164
+ "坎蒂丝 Candace (Genshin Impact)": 127,
165
+ "罗莎莉亚 Rosaria (Genshin Impact)": 128,
166
+ "北斗 Beidou (Genshin Impact)": 129,
167
+ "珊瑚宫心海 Sangonomiya Kokomi (Genshin Impact)": 132,
168
+ "烟绯 Yanfei (Genshin Impact)": 133,
169
+ "久岐忍 Kuki Shinobu (Genshin Impact)": 136,
170
+ "宵宫 Yoimiya (Genshin Impact)": 139,
171
+ "安柏 Amber (Genshin Impact)": 143,
172
+ "迪奥娜 Diona (Genshin Impact)": 144,
173
+ "班尼特 Bennett (Genshin Impact)": 146,
174
+ "雷泽 Razor (Genshin Impact)": 147,
175
+ "阿贝多 Albedo (Genshin Impact)": 151,
176
+ "温迪 Venti (Genshin Impact)": 152,
177
+ "空 Player Male (Genshin Impact)": 153,
178
+ "神里绫人 Kamisato Ayato (Genshin Impact)": 154,
179
+ "琴 Jean (Genshin Impact)": 155,
180
+ "艾尔海森 Alhaitham (Genshin Impact)": 156,
181
+ "莫娜 Mona (Genshin Impact)": 157,
182
+ "妮露 Nilou (Genshin Impact)": 159,
183
+ "胡桃 Hu Tao (Genshin Impact)": 160,
184
+ "甘雨 Ganyu (Genshin Impact)": 161,
185
+ "纳西妲 Nahida (Genshin Impact)": 162,
186
+ "刻晴 Keqing (Genshin Impact)": 165,
187
+ "荧 Player Female (Genshin Impact)": 169,
188
+ "埃洛伊 Aloy (Genshin Impact)": 179,
189
+ "柯莱 Collei (Genshin Impact)": 182,
190
+ "多莉 Dori (Genshin Impact)": 184,
191
+ "提纳里 Tighnari (Genshin Impact)": 186,
192
+ "砂糖 Sucrose (Genshin Impact)": 188,
193
+ "行秋 Xingqiu (Genshin Impact)": 190,
194
+ "奥兹 Oz (Genshin Impact)": 193,
195
+ "五郎 Gorou (Genshin Impact)": 198,
196
+ "达达利亚 Tartalia (Genshin Impact)": 202,
197
+ "七七 Qiqi (Genshin Impact)": 207,
198
+ "申鹤 Shenhe (Genshin Impact)": 217,
199
+ "莱依拉 Layla (Genshin Impact)": 228,
200
+ "菲谢尔 Fishl (Genshin Impact)": 230
201
+ }
202
+ }
Mutsumi-Chan/VITS-Umamusume-Voice/cover.png ADDED

Git LFS Details

  • SHA256: af0fa81f765cfa89f349dd5eca99c58a3ff455d53834cb741b2b13265144f4ab
  • Pointer size: 132 Bytes
  • Size of remote file: 3.62 MB
Mutsumi-Chan/VITS-Umamusume-Voice/data_utils.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+
8
+ import commons
9
+ from mel_processing import spectrogram_torch
10
+ from utils import load_wav_to_torch, load_filepaths_and_text
11
+ from text import text_to_sequence, cleaned_text_to_sequence
12
+
13
+
14
+ class TextAudioLoader(torch.utils.data.Dataset):
15
+ """
16
+ 1) loads audio, text pairs
17
+ 2) normalizes text and converts them to sequences of integers
18
+ 3) computes spectrograms from audio files.
19
+ """
20
+ def __init__(self, audiopaths_and_text, hparams):
21
+ self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
22
+ self.text_cleaners = hparams.text_cleaners
23
+ self.max_wav_value = hparams.max_wav_value
24
+ self.sampling_rate = hparams.sampling_rate
25
+ self.filter_length = hparams.filter_length
26
+ self.hop_length = hparams.hop_length
27
+ self.win_length = hparams.win_length
28
+ self.sampling_rate = hparams.sampling_rate
29
+
30
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
31
+
32
+ self.add_blank = hparams.add_blank
33
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
34
+ self.max_text_len = getattr(hparams, "max_text_len", 190)
35
+
36
+ random.seed(1234)
37
+ random.shuffle(self.audiopaths_and_text)
38
+ self._filter()
39
+
40
+
41
+ def _filter(self):
42
+ """
43
+ Filter text & store spec lengths
44
+ """
45
+ # Store spectrogram lengths for Bucketing
46
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
47
+ # spec_length = wav_length // hop_length
48
+
49
+ audiopaths_and_text_new = []
50
+ lengths = []
51
+ for audiopath, text in self.audiopaths_and_text:
52
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
53
+ audiopaths_and_text_new.append([audiopath, text])
54
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
55
+ self.audiopaths_and_text = audiopaths_and_text_new
56
+ self.lengths = lengths
57
+
58
+ def get_audio_text_pair(self, audiopath_and_text):
59
+ # separate filename and text
60
+ audiopath, text = audiopath_and_text[0], audiopath_and_text[1]
61
+ text = self.get_text(text)
62
+ spec, wav = self.get_audio(audiopath)
63
+ return (text, spec, wav)
64
+
65
+ def get_audio(self, filename):
66
+ audio, sampling_rate = load_wav_to_torch(filename)
67
+ if sampling_rate != self.sampling_rate:
68
+ raise ValueError("{} {} SR doesn't match target {} SR".format(
69
+ sampling_rate, self.sampling_rate))
70
+ audio_norm = audio / self.max_wav_value
71
+ audio_norm = audio_norm.unsqueeze(0)
72
+ spec_filename = filename.replace(".wav", ".spec.pt")
73
+ if os.path.exists(spec_filename):
74
+ spec = torch.load(spec_filename)
75
+ else:
76
+ spec = spectrogram_torch(audio_norm, self.filter_length,
77
+ self.sampling_rate, self.hop_length, self.win_length,
78
+ center=False)
79
+ spec = torch.squeeze(spec, 0)
80
+ torch.save(spec, spec_filename)
81
+ return spec, audio_norm
82
+
83
+ def get_text(self, text):
84
+ if self.cleaned_text:
85
+ text_norm = cleaned_text_to_sequence(text)
86
+ else:
87
+ text_norm = text_to_sequence(text, self.text_cleaners)
88
+ if self.add_blank:
89
+ text_norm = commons.intersperse(text_norm, 0)
90
+ text_norm = torch.LongTensor(text_norm)
91
+ return text_norm
92
+
93
+ def __getitem__(self, index):
94
+ return self.get_audio_text_pair(self.audiopaths_and_text[index])
95
+
96
+ def __len__(self):
97
+ return len(self.audiopaths_and_text)
98
+
99
+
100
+ class TextAudioCollate():
101
+ """ Zero-pads model inputs and targets
102
+ """
103
+ def __init__(self, return_ids=False):
104
+ self.return_ids = return_ids
105
+
106
+ def __call__(self, batch):
107
+ """Collate's training batch from normalized text and aduio
108
+ PARAMS
109
+ ------
110
+ batch: [text_normalized, spec_normalized, wav_normalized]
111
+ """
112
+ # Right zero-pad all one-hot text sequences to max input length
113
+ _, ids_sorted_decreasing = torch.sort(
114
+ torch.LongTensor([x[1].size(1) for x in batch]),
115
+ dim=0, descending=True)
116
+
117
+ max_text_len = max([len(x[0]) for x in batch])
118
+ max_spec_len = max([x[1].size(1) for x in batch])
119
+ max_wav_len = max([x[2].size(1) for x in batch])
120
+
121
+ text_lengths = torch.LongTensor(len(batch))
122
+ spec_lengths = torch.LongTensor(len(batch))
123
+ wav_lengths = torch.LongTensor(len(batch))
124
+
125
+ text_padded = torch.LongTensor(len(batch), max_text_len)
126
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
127
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
128
+ text_padded.zero_()
129
+ spec_padded.zero_()
130
+ wav_padded.zero_()
131
+ for i in range(len(ids_sorted_decreasing)):
132
+ row = batch[ids_sorted_decreasing[i]]
133
+
134
+ text = row[0]
135
+ text_padded[i, :text.size(0)] = text
136
+ text_lengths[i] = text.size(0)
137
+
138
+ spec = row[1]
139
+ spec_padded[i, :, :spec.size(1)] = spec
140
+ spec_lengths[i] = spec.size(1)
141
+
142
+ wav = row[2]
143
+ wav_padded[i, :, :wav.size(1)] = wav
144
+ wav_lengths[i] = wav.size(1)
145
+
146
+ if self.return_ids:
147
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing
148
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths
149
+
150
+
151
+ """Multi speaker version"""
152
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
153
+ """
154
+ 1) loads audio, speaker_id, text pairs
155
+ 2) normalizes text and converts them to sequences of integers
156
+ 3) computes spectrograms from audio files.
157
+ """
158
+ def __init__(self, audiopaths_sid_text, hparams):
159
+ self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
160
+ self.text_cleaners = hparams.text_cleaners
161
+ self.max_wav_value = hparams.max_wav_value
162
+ self.sampling_rate = hparams.sampling_rate
163
+ self.filter_length = hparams.filter_length
164
+ self.hop_length = hparams.hop_length
165
+ self.win_length = hparams.win_length
166
+ self.sampling_rate = hparams.sampling_rate
167
+
168
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
169
+
170
+ self.add_blank = hparams.add_blank
171
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
172
+ self.max_text_len = getattr(hparams, "max_text_len", 190)
173
+
174
+ random.seed(1234)
175
+ random.shuffle(self.audiopaths_sid_text)
176
+ self._filter()
177
+
178
+ def _filter(self):
179
+ """
180
+ Filter text & store spec lengths
181
+ """
182
+ # Store spectrogram lengths for Bucketing
183
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
184
+ # spec_length = wav_length // hop_length
185
+
186
+ audiopaths_sid_text_new = []
187
+ lengths = []
188
+ for audiopath, sid, text in self.audiopaths_sid_text:
189
+ audiopath = "E:/uma_voice/" + audiopath
190
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
191
+ audiopaths_sid_text_new.append([audiopath, sid, text])
192
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
193
+ self.audiopaths_sid_text = audiopaths_sid_text_new
194
+ self.lengths = lengths
195
+
196
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
197
+ # separate filename, speaker_id and text
198
+ audiopath, sid, text = audiopath_sid_text[0], audiopath_sid_text[1], audiopath_sid_text[2]
199
+ text = self.get_text(text)
200
+ spec, wav = self.get_audio(audiopath)
201
+ sid = self.get_sid(sid)
202
+ return (text, spec, wav, sid)
203
+
204
+ def get_audio(self, filename):
205
+ audio, sampling_rate = load_wav_to_torch(filename)
206
+ if sampling_rate != self.sampling_rate:
207
+ raise ValueError("{} {} SR doesn't match target {} SR".format(
208
+ sampling_rate, self.sampling_rate))
209
+ audio_norm = audio / self.max_wav_value
210
+ audio_norm = audio_norm.unsqueeze(0)
211
+ spec_filename = filename.replace(".wav", ".spec.pt")
212
+ if os.path.exists(spec_filename):
213
+ spec = torch.load(spec_filename)
214
+ else:
215
+ spec = spectrogram_torch(audio_norm, self.filter_length,
216
+ self.sampling_rate, self.hop_length, self.win_length,
217
+ center=False)
218
+ spec = torch.squeeze(spec, 0)
219
+ torch.save(spec, spec_filename)
220
+ return spec, audio_norm
221
+
222
+ def get_text(self, text):
223
+ if self.cleaned_text:
224
+ text_norm = cleaned_text_to_sequence(text)
225
+ else:
226
+ text_norm = text_to_sequence(text, self.text_cleaners)
227
+ if self.add_blank:
228
+ text_norm = commons.intersperse(text_norm, 0)
229
+ text_norm = torch.LongTensor(text_norm)
230
+ return text_norm
231
+
232
+ def get_sid(self, sid):
233
+ sid = torch.LongTensor([int(sid)])
234
+ return sid
235
+
236
+ def __getitem__(self, index):
237
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
238
+
239
+ def __len__(self):
240
+ return len(self.audiopaths_sid_text)
241
+
242
+
243
+ class TextAudioSpeakerCollate():
244
+ """ Zero-pads model inputs and targets
245
+ """
246
+ def __init__(self, return_ids=False):
247
+ self.return_ids = return_ids
248
+
249
+ def __call__(self, batch):
250
+ """Collate's training batch from normalized text, audio and speaker identities
251
+ PARAMS
252
+ ------
253
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
254
+ """
255
+ # Right zero-pad all one-hot text sequences to max input length
256
+ _, ids_sorted_decreasing = torch.sort(
257
+ torch.LongTensor([x[1].size(1) for x in batch]),
258
+ dim=0, descending=True)
259
+
260
+ max_text_len = max([len(x[0]) for x in batch])
261
+ max_spec_len = max([x[1].size(1) for x in batch])
262
+ max_wav_len = max([x[2].size(1) for x in batch])
263
+
264
+ text_lengths = torch.LongTensor(len(batch))
265
+ spec_lengths = torch.LongTensor(len(batch))
266
+ wav_lengths = torch.LongTensor(len(batch))
267
+ sid = torch.LongTensor(len(batch))
268
+
269
+ text_padded = torch.LongTensor(len(batch), max_text_len)
270
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
271
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
272
+ text_padded.zero_()
273
+ spec_padded.zero_()
274
+ wav_padded.zero_()
275
+ for i in range(len(ids_sorted_decreasing)):
276
+ row = batch[ids_sorted_decreasing[i]]
277
+
278
+ text = row[0]
279
+ text_padded[i, :text.size(0)] = text
280
+ text_lengths[i] = text.size(0)
281
+
282
+ spec = row[1]
283
+ spec_padded[i, :, :spec.size(1)] = spec
284
+ spec_lengths[i] = spec.size(1)
285
+
286
+ wav = row[2]
287
+ wav_padded[i, :, :wav.size(1)] = wav
288
+ wav_lengths[i] = wav.size(1)
289
+
290
+ sid[i] = row[3]
291
+
292
+ if self.return_ids:
293
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing
294
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid
295
+
296
+
297
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
298
+ """
299
+ Maintain similar input lengths in a batch.
300
+ Length groups are specified by boundaries.
301
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
302
+
303
+ It removes samples which are not included in the boundaries.
304
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
305
+ """
306
+ def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):
307
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
308
+ self.lengths = dataset.lengths
309
+ self.batch_size = batch_size
310
+ self.boundaries = boundaries
311
+
312
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
313
+ self.total_size = sum(self.num_samples_per_bucket)
314
+ self.num_samples = self.total_size // self.num_replicas
315
+
316
+ def _create_buckets(self):
317
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
318
+ for i in range(len(self.lengths)):
319
+ length = self.lengths[i]
320
+ idx_bucket = self._bisect(length)
321
+ if idx_bucket != -1:
322
+ buckets[idx_bucket].append(i)
323
+
324
+ for i in range(len(buckets) - 1, 0, -1):
325
+ if len(buckets[i]) == 0:
326
+ buckets.pop(i)
327
+ self.boundaries.pop(i+1)
328
+
329
+ num_samples_per_bucket = []
330
+ for i in range(len(buckets)):
331
+ len_bucket = len(buckets[i])
332
+ total_batch_size = self.num_replicas * self.batch_size
333
+ rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size
334
+ num_samples_per_bucket.append(len_bucket + rem)
335
+ return buckets, num_samples_per_bucket
336
+
337
+ def __iter__(self):
338
+ # deterministically shuffle based on epoch
339
+ g = torch.Generator()
340
+ g.manual_seed(self.epoch)
341
+
342
+ indices = []
343
+ if self.shuffle:
344
+ for bucket in self.buckets:
345
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
346
+ else:
347
+ for bucket in self.buckets:
348
+ indices.append(list(range(len(bucket))))
349
+
350
+ batches = []
351
+ for i in range(len(self.buckets)):
352
+ bucket = self.buckets[i]
353
+ len_bucket = len(bucket)
354
+ ids_bucket = indices[i]
355
+ num_samples_bucket = self.num_samples_per_bucket[i]
356
+
357
+ # add extra samples to make it evenly divisible
358
+ rem = num_samples_bucket - len_bucket
359
+ ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
360
+
361
+ # subsample
362
+ ids_bucket = ids_bucket[self.rank::self.num_replicas]
363
+
364
+ # batching
365
+ for j in range(len(ids_bucket) // self.batch_size):
366
+ batch = [bucket[idx] for idx in ids_bucket[j*self.batch_size:(j+1)*self.batch_size]]
367
+ batches.append(batch)
368
+
369
+ if self.shuffle:
370
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
371
+ batches = [batches[i] for i in batch_ids]
372
+ self.batches = batches
373
+
374
+ assert len(self.batches) * self.batch_size == self.num_samples
375
+ return iter(self.batches)
376
+
377
+ def _bisect(self, x, lo=0, hi=None):
378
+ if hi is None:
379
+ hi = len(self.boundaries) - 1
380
+
381
+ if hi > lo:
382
+ mid = (hi + lo) // 2
383
+ if self.boundaries[mid] < x and x <= self.boundaries[mid+1]:
384
+ return mid
385
+ elif x <= self.boundaries[mid]:
386
+ return self._bisect(x, lo, mid)
387
+ else:
388
+ return self._bisect(x, mid + 1, hi)
389
+ else:
390
+ return -1
391
+
392
+ def __len__(self):
393
+ return self.num_samples // self.batch_size
Mutsumi-Chan/VITS-Umamusume-Voice/haru-urara-concert.gif ADDED

Git LFS Details

  • SHA256: a3c4a5829608ec8f91ae07af8f93139e5c3f1a1e41854951f0e9d17e42b792bf
  • Pointer size: 132 Bytes
  • Size of remote file: 7.83 MB
Mutsumi-Chan/VITS-Umamusume-Voice/hubert_model.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Optional, Tuple
3
+ import random
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
9
+
10
+ class Hubert(nn.Module):
11
+ def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
12
+ super().__init__()
13
+ self._mask = mask
14
+ self.feature_extractor = FeatureExtractor()
15
+ self.feature_projection = FeatureProjection()
16
+ self.positional_embedding = PositionalConvEmbedding()
17
+ self.norm = nn.LayerNorm(768)
18
+ self.dropout = nn.Dropout(0.1)
19
+ self.encoder = TransformerEncoder(
20
+ nn.TransformerEncoderLayer(
21
+ 768, 12, 3072, activation="gelu", batch_first=True
22
+ ),
23
+ 12,
24
+ )
25
+ self.proj = nn.Linear(768, 256)
26
+
27
+ self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
28
+ self.label_embedding = nn.Embedding(num_label_embeddings, 256)
29
+
30
+ def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
31
+ mask = None
32
+ if self.training and self._mask:
33
+ mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
34
+ x[mask] = self.masked_spec_embed.to(x.dtype)
35
+ return x, mask
36
+
37
+ def encode(
38
+ self, x: torch.Tensor, layer: Optional[int] = None
39
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
40
+ x = self.feature_extractor(x)
41
+ x = self.feature_projection(x.transpose(1, 2))
42
+ x, mask = self.mask(x)
43
+ x = x + self.positional_embedding(x)
44
+ x = self.dropout(self.norm(x))
45
+ x = self.encoder(x, output_layer=layer)
46
+ return x, mask
47
+
48
+ def logits(self, x: torch.Tensor) -> torch.Tensor:
49
+ logits = torch.cosine_similarity(
50
+ x.unsqueeze(2),
51
+ self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
52
+ dim=-1,
53
+ )
54
+ return logits / 0.1
55
+
56
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
57
+ x, mask = self.encode(x)
58
+ x = self.proj(x)
59
+ logits = self.logits(x)
60
+ return logits, mask
61
+
62
+
63
+ class HubertSoft(Hubert):
64
+ def __init__(self):
65
+ super().__init__()
66
+
67
+ @torch.inference_mode()
68
+ def units(self, wav: torch.Tensor) -> torch.Tensor:
69
+ wav = F.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
70
+ x, _ = self.encode(wav)
71
+ return self.proj(x)
72
+
73
+
74
+ class FeatureExtractor(nn.Module):
75
+ def __init__(self):
76
+ super().__init__()
77
+ self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
78
+ self.norm0 = nn.GroupNorm(512, 512)
79
+ self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
80
+ self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
81
+ self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
82
+ self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
83
+ self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
84
+ self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
85
+
86
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
87
+ x = F.gelu(self.norm0(self.conv0(x)))
88
+ x = F.gelu(self.conv1(x))
89
+ x = F.gelu(self.conv2(x))
90
+ x = F.gelu(self.conv3(x))
91
+ x = F.gelu(self.conv4(x))
92
+ x = F.gelu(self.conv5(x))
93
+ x = F.gelu(self.conv6(x))
94
+ return x
95
+
96
+
97
+ class FeatureProjection(nn.Module):
98
+ def __init__(self):
99
+ super().__init__()
100
+ self.norm = nn.LayerNorm(512)
101
+ self.projection = nn.Linear(512, 768)
102
+ self.dropout = nn.Dropout(0.1)
103
+
104
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
105
+ x = self.norm(x)
106
+ x = self.projection(x)
107
+ x = self.dropout(x)
108
+ return x
109
+
110
+
111
+ class PositionalConvEmbedding(nn.Module):
112
+ def __init__(self):
113
+ super().__init__()
114
+ self.conv = nn.Conv1d(
115
+ 768,
116
+ 768,
117
+ kernel_size=128,
118
+ padding=128 // 2,
119
+ groups=16,
120
+ )
121
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
122
+
123
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
124
+ x = self.conv(x.transpose(1, 2))
125
+ x = F.gelu(x[:, :, :-1])
126
+ return x.transpose(1, 2)
127
+
128
+
129
+ class TransformerEncoder(nn.Module):
130
+ def __init__(
131
+ self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
132
+ ) -> None:
133
+ super(TransformerEncoder, self).__init__()
134
+ self.layers = nn.ModuleList(
135
+ [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
136
+ )
137
+ self.num_layers = num_layers
138
+
139
+ def forward(
140
+ self,
141
+ src: torch.Tensor,
142
+ mask: torch.Tensor = None,
143
+ src_key_padding_mask: torch.Tensor = None,
144
+ output_layer: Optional[int] = None,
145
+ ) -> torch.Tensor:
146
+ output = src
147
+ for layer in self.layers[:output_layer]:
148
+ output = layer(
149
+ output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
150
+ )
151
+ return output
152
+
153
+
154
+ def _compute_mask(
155
+ shape: Tuple[int, int],
156
+ mask_prob: float,
157
+ mask_length: int,
158
+ device: torch.device,
159
+ min_masks: int = 0,
160
+ ) -> torch.Tensor:
161
+ batch_size, sequence_length = shape
162
+
163
+ if mask_length < 1:
164
+ raise ValueError("`mask_length` has to be bigger than 0.")
165
+
166
+ if mask_length > sequence_length:
167
+ raise ValueError(
168
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
169
+ )
170
+
171
+ # compute number of masked spans in batch
172
+ num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
173
+ num_masked_spans = max(num_masked_spans, min_masks)
174
+
175
+ # make sure num masked indices <= sequence_length
176
+ if num_masked_spans * mask_length > sequence_length:
177
+ num_masked_spans = sequence_length // mask_length
178
+
179
+ # SpecAugment mask to fill
180
+ mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
181
+
182
+ # uniform distribution to sample from, make sure that offset samples are < sequence_length
183
+ uniform_dist = torch.ones(
184
+ (batch_size, sequence_length - (mask_length - 1)), device=device
185
+ )
186
+
187
+ # get random indices to mask
188
+ mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
189
+
190
+ # expand masked indices to masked spans
191
+ mask_indices = (
192
+ mask_indices.unsqueeze(dim=-1)
193
+ .expand((batch_size, num_masked_spans, mask_length))
194
+ .reshape(batch_size, num_masked_spans * mask_length)
195
+ )
196
+ offsets = (
197
+ torch.arange(mask_length, device=device)[None, None, :]
198
+ .expand((batch_size, num_masked_spans, mask_length))
199
+ .reshape(batch_size, num_masked_spans * mask_length)
200
+ )
201
+ mask_idxs = mask_indices + offsets
202
+
203
+ # scatter indices to mask
204
+ mask = mask.scatter(1, mask_idxs, True)
205
+
206
+ return mask
207
+
208
+
209
+ def hubert_soft(
210
+ path: str
211
+ ) -> HubertSoft:
212
+ r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
213
+ Args:
214
+ path (str): path of a pretrained model
215
+ """
216
+ hubert = HubertSoft()
217
+ checkpoint = torch.load(path)
218
+ consume_prefix_in_state_dict_if_present(checkpoint, "module.")
219
+ hubert.load_state_dict(checkpoint)
220
+ hubert.eval()
221
+ return hubert
Mutsumi-Chan/VITS-Umamusume-Voice/jieba/dict.txt ADDED
The diff for this file is too large to render. See raw diff
 
Mutsumi-Chan/VITS-Umamusume-Voice/losses.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import commons
5
+
6
+
7
+ def feature_loss(fmap_r, fmap_g):
8
+ loss = 0
9
+ for dr, dg in zip(fmap_r, fmap_g):
10
+ for rl, gl in zip(dr, dg):
11
+ rl = rl.float().detach()
12
+ gl = gl.float()
13
+ loss += torch.mean(torch.abs(rl - gl))
14
+
15
+ return loss * 2
16
+
17
+
18
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
19
+ loss = 0
20
+ r_losses = []
21
+ g_losses = []
22
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
23
+ dr = dr.float()
24
+ dg = dg.float()
25
+ r_loss = torch.mean((1-dr)**2)
26
+ g_loss = torch.mean(dg**2)
27
+ loss += (r_loss + g_loss)
28
+ r_losses.append(r_loss.item())
29
+ g_losses.append(g_loss.item())
30
+
31
+ return loss, r_losses, g_losses
32
+
33
+
34
+ def generator_loss(disc_outputs):
35
+ loss = 0
36
+ gen_losses = []
37
+ for dg in disc_outputs:
38
+ dg = dg.float()
39
+ l = torch.mean((1-dg)**2)
40
+ gen_losses.append(l)
41
+ loss += l
42
+
43
+ return loss, gen_losses
44
+
45
+
46
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
47
+ """
48
+ z_p, logs_q: [b, h, t_t]
49
+ m_p, logs_p: [b, h, t_t]
50
+ """
51
+ z_p = z_p.float()
52
+ logs_q = logs_q.float()
53
+ m_p = m_p.float()
54
+ logs_p = logs_p.float()
55
+ z_mask = z_mask.float()
56
+
57
+ kl = logs_p - logs_q - 0.5
58
+ kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
59
+ kl = torch.sum(kl * z_mask)
60
+ l = kl / torch.sum(z_mask)
61
+ return l
Mutsumi-Chan/VITS-Umamusume-Voice/mel_processing.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.utils.data
3
+ from librosa.filters import mel as librosa_mel_fn
4
+
5
+ MAX_WAV_VALUE = 32768.0
6
+
7
+
8
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
9
+ """
10
+ PARAMS
11
+ ------
12
+ C: compression factor
13
+ """
14
+ return torch.log(torch.clamp(x, min=clip_val) * C)
15
+
16
+
17
+ def dynamic_range_decompression_torch(x, C=1):
18
+ """
19
+ PARAMS
20
+ ------
21
+ C: compression factor used to compress
22
+ """
23
+ return torch.exp(x) / C
24
+
25
+
26
+ def spectral_normalize_torch(magnitudes):
27
+ output = dynamic_range_compression_torch(magnitudes)
28
+ return output
29
+
30
+
31
+ def spectral_de_normalize_torch(magnitudes):
32
+ output = dynamic_range_decompression_torch(magnitudes)
33
+ return output
34
+
35
+
36
+ mel_basis = {}
37
+ hann_window = {}
38
+
39
+
40
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
41
+ if torch.min(y) < -1.:
42
+ print('min value is ', torch.min(y))
43
+ if torch.max(y) > 1.:
44
+ print('max value is ', torch.max(y))
45
+
46
+ global hann_window
47
+ dtype_device = str(y.dtype) + '_' + str(y.device)
48
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
49
+ if wnsize_dtype_device not in hann_window:
50
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
51
+
52
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
53
+ y = y.squeeze(1)
54
+
55
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
56
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
57
+
58
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
59
+ return spec
60
+
61
+
62
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
63
+ global mel_basis
64
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
65
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
66
+ if fmax_dtype_device not in mel_basis:
67
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
68
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
69
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
70
+ spec = spectral_normalize_torch(spec)
71
+ return spec
72
+
73
+
74
+ def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
75
+ if torch.min(y) < -1.:
76
+ print('min value is ', torch.min(y))
77
+ if torch.max(y) > 1.:
78
+ print('max value is ', torch.max(y))
79
+
80
+ global mel_basis, hann_window
81
+ dtype_device = str(y.dtype) + '_' + str(y.device)
82
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
83
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
84
+ if fmax_dtype_device not in mel_basis:
85
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
86
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
87
+ if wnsize_dtype_device not in hann_window:
88
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
89
+
90
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
91
+ y = y.squeeze(1)
92
+
93
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
94
+ center=center, pad_mode='reflect', normalized=False, onesided=True)
95
+
96
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
97
+
98
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
99
+ spec = spectral_normalize_torch(spec)
100
+
101
+ return spec
Mutsumi-Chan/VITS-Umamusume-Voice/models.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ import modules
8
+ import attentions
9
+
10
+ from torch.nn import Conv1d, ConvTranspose1d, Conv2d
11
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
12
+ from commons import init_weights, get_padding
13
+
14
+
15
+ class StochasticDurationPredictor(nn.Module):
16
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
17
+ super().__init__()
18
+ filter_channels = in_channels # it needs to be removed from future version.
19
+ self.in_channels = in_channels
20
+ self.filter_channels = filter_channels
21
+ self.kernel_size = kernel_size
22
+ self.p_dropout = p_dropout
23
+ self.n_flows = n_flows
24
+ self.gin_channels = gin_channels
25
+
26
+ self.log_flow = modules.Log()
27
+ self.flows = nn.ModuleList()
28
+ self.flows.append(modules.ElementwiseAffine(2))
29
+ for i in range(n_flows):
30
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
31
+ self.flows.append(modules.Flip())
32
+
33
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
34
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
35
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
36
+ self.post_flows = nn.ModuleList()
37
+ self.post_flows.append(modules.ElementwiseAffine(2))
38
+ for i in range(4):
39
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
40
+ self.post_flows.append(modules.Flip())
41
+
42
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
43
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
44
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
45
+ if gin_channels != 0:
46
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
47
+
48
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
49
+ x = torch.detach(x)
50
+ x = self.pre(x)
51
+ if g is not None:
52
+ g = torch.detach(g)
53
+ x = x + self.cond(g)
54
+ x = self.convs(x, x_mask)
55
+ x = self.proj(x) * x_mask
56
+
57
+ if not reverse:
58
+ flows = self.flows
59
+ assert w is not None
60
+
61
+ logdet_tot_q = 0
62
+ h_w = self.post_pre(w)
63
+ h_w = self.post_convs(h_w, x_mask)
64
+ h_w = self.post_proj(h_w) * x_mask
65
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
66
+ z_q = e_q
67
+ for flow in self.post_flows:
68
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
69
+ logdet_tot_q += logdet_q
70
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
71
+ u = torch.sigmoid(z_u) * x_mask
72
+ z0 = (w - u) * x_mask
73
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2])
74
+ logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q
75
+
76
+ logdet_tot = 0
77
+ z0, logdet = self.log_flow(z0, x_mask)
78
+ logdet_tot += logdet
79
+ z = torch.cat([z0, z1], 1)
80
+ for flow in flows:
81
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
82
+ logdet_tot = logdet_tot + logdet
83
+ nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot
84
+ return nll + logq # [b]
85
+ else:
86
+ flows = list(reversed(self.flows))
87
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
88
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
89
+ for flow in flows:
90
+ z = flow(z, x_mask, g=x, reverse=reverse)
91
+ z0, z1 = torch.split(z, [1, 1], 1)
92
+ logw = z0
93
+ return logw
94
+
95
+
96
+ class DurationPredictor(nn.Module):
97
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
98
+ super().__init__()
99
+
100
+ self.in_channels = in_channels
101
+ self.filter_channels = filter_channels
102
+ self.kernel_size = kernel_size
103
+ self.p_dropout = p_dropout
104
+ self.gin_channels = gin_channels
105
+
106
+ self.drop = nn.Dropout(p_dropout)
107
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
108
+ self.norm_1 = modules.LayerNorm(filter_channels)
109
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
110
+ self.norm_2 = modules.LayerNorm(filter_channels)
111
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
112
+
113
+ if gin_channels != 0:
114
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
115
+
116
+ def forward(self, x, x_mask, g=None):
117
+ x = torch.detach(x)
118
+ if g is not None:
119
+ g = torch.detach(g)
120
+ x = x + self.cond(g)
121
+ x = self.conv_1(x * x_mask)
122
+ x = torch.relu(x)
123
+ x = self.norm_1(x)
124
+ x = self.drop(x)
125
+ x = self.conv_2(x * x_mask)
126
+ x = torch.relu(x)
127
+ x = self.norm_2(x)
128
+ x = self.drop(x)
129
+ x = self.proj(x * x_mask)
130
+ return x * x_mask
131
+
132
+
133
+ class TextEncoder(nn.Module):
134
+ def __init__(self,
135
+ n_vocab,
136
+ out_channels,
137
+ hidden_channels,
138
+ filter_channels,
139
+ n_heads,
140
+ n_layers,
141
+ kernel_size,
142
+ p_dropout,
143
+ emotion_embedding):
144
+ super().__init__()
145
+ self.n_vocab = n_vocab
146
+ self.out_channels = out_channels
147
+ self.hidden_channels = hidden_channels
148
+ self.filter_channels = filter_channels
149
+ self.n_heads = n_heads
150
+ self.n_layers = n_layers
151
+ self.kernel_size = kernel_size
152
+ self.p_dropout = p_dropout
153
+ self.emotion_embedding = emotion_embedding
154
+
155
+ if self.n_vocab!=0:
156
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
157
+ if emotion_embedding:
158
+ self.emotion_emb = nn.Linear(1024, hidden_channels)
159
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
160
+
161
+ self.encoder = attentions.Encoder(
162
+ hidden_channels,
163
+ filter_channels,
164
+ n_heads,
165
+ n_layers,
166
+ kernel_size,
167
+ p_dropout)
168
+ self.proj= nn.Conv1d(hidden_channels, out_channels * 2, 1)
169
+
170
+ def forward(self, x, x_lengths, emotion_embedding=None):
171
+ if self.n_vocab!=0:
172
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
173
+ if emotion_embedding is not None:
174
+ x = x + self.emotion_emb(emotion_embedding.unsqueeze(1))
175
+ x = torch.transpose(x, 1, -1) # [b, h, t]
176
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
177
+
178
+ x = self.encoder(x * x_mask, x_mask)
179
+ stats = self.proj(x) * x_mask
180
+
181
+ m, logs = torch.split(stats, self.out_channels, dim=1)
182
+ return x, m, logs, x_mask
183
+
184
+
185
+ class ResidualCouplingBlock(nn.Module):
186
+ def __init__(self,
187
+ channels,
188
+ hidden_channels,
189
+ kernel_size,
190
+ dilation_rate,
191
+ n_layers,
192
+ n_flows=4,
193
+ gin_channels=0):
194
+ super().__init__()
195
+ self.channels = channels
196
+ self.hidden_channels = hidden_channels
197
+ self.kernel_size = kernel_size
198
+ self.dilation_rate = dilation_rate
199
+ self.n_layers = n_layers
200
+ self.n_flows = n_flows
201
+ self.gin_channels = gin_channels
202
+
203
+ self.flows = nn.ModuleList()
204
+ for i in range(n_flows):
205
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
206
+ self.flows.append(modules.Flip())
207
+
208
+ def forward(self, x, x_mask, g=None, reverse=False):
209
+ if not reverse:
210
+ for flow in self.flows:
211
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
212
+ else:
213
+ for flow in reversed(self.flows):
214
+ x = flow(x, x_mask, g=g, reverse=reverse)
215
+ return x
216
+
217
+
218
+ class PosteriorEncoder(nn.Module):
219
+ def __init__(self,
220
+ in_channels,
221
+ out_channels,
222
+ hidden_channels,
223
+ kernel_size,
224
+ dilation_rate,
225
+ n_layers,
226
+ gin_channels=0):
227
+ super().__init__()
228
+ self.in_channels = in_channels
229
+ self.out_channels = out_channels
230
+ self.hidden_channels = hidden_channels
231
+ self.kernel_size = kernel_size
232
+ self.dilation_rate = dilation_rate
233
+ self.n_layers = n_layers
234
+ self.gin_channels = gin_channels
235
+
236
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
237
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
238
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
239
+
240
+ def forward(self, x, x_lengths, g=None):
241
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
242
+ x = self.pre(x) * x_mask
243
+ x = self.enc(x, x_mask, g=g)
244
+ stats = self.proj(x) * x_mask
245
+ m, logs = torch.split(stats, self.out_channels, dim=1)
246
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
247
+ return z, m, logs, x_mask
248
+
249
+
250
+ class Generator(torch.nn.Module):
251
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
252
+ super(Generator, self).__init__()
253
+ self.num_kernels = len(resblock_kernel_sizes)
254
+ self.num_upsamples = len(upsample_rates)
255
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
256
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
257
+
258
+ self.ups = nn.ModuleList()
259
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
260
+ self.ups.append(weight_norm(
261
+ ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
262
+ k, u, padding=(k-u)//2)))
263
+
264
+ self.resblocks = nn.ModuleList()
265
+ for i in range(len(self.ups)):
266
+ ch = upsample_initial_channel//(2**(i+1))
267
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
268
+ self.resblocks.append(resblock(ch, k, d))
269
+
270
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
271
+ self.ups.apply(init_weights)
272
+
273
+ if gin_channels != 0:
274
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
275
+
276
+ def forward(self, x, g=None):
277
+ x = self.conv_pre(x)
278
+ if g is not None:
279
+ x = x + self.cond(g)
280
+
281
+ for i in range(self.num_upsamples):
282
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
283
+ x = self.ups[i](x)
284
+ xs = None
285
+ for j in range(self.num_kernels):
286
+ if xs is None:
287
+ xs = self.resblocks[i*self.num_kernels+j](x)
288
+ else:
289
+ xs += self.resblocks[i*self.num_kernels+j](x)
290
+ x = xs / self.num_kernels
291
+ x = F.leaky_relu(x)
292
+ x = self.conv_post(x)
293
+ x = torch.tanh(x)
294
+
295
+ return x
296
+
297
+ def remove_weight_norm(self):
298
+ print('Removing weight norm...')
299
+ for l in self.ups:
300
+ remove_weight_norm(l)
301
+ for l in self.resblocks:
302
+ l.remove_weight_norm()
303
+
304
+
305
+ class DiscriminatorP(torch.nn.Module):
306
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
307
+ super(DiscriminatorP, self).__init__()
308
+ self.period = period
309
+ self.use_spectral_norm = use_spectral_norm
310
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
311
+ self.convs = nn.ModuleList([
312
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
313
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
314
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
315
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
316
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
317
+ ])
318
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
319
+
320
+ def forward(self, x):
321
+ fmap = []
322
+
323
+ # 1d to 2d
324
+ b, c, t = x.shape
325
+ if t % self.period != 0: # pad first
326
+ n_pad = self.period - (t % self.period)
327
+ x = F.pad(x, (0, n_pad), "reflect")
328
+ t = t + n_pad
329
+ x = x.view(b, c, t // self.period, self.period)
330
+
331
+ for l in self.convs:
332
+ x = l(x)
333
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
334
+ fmap.append(x)
335
+ x = self.conv_post(x)
336
+ fmap.append(x)
337
+ x = torch.flatten(x, 1, -1)
338
+
339
+ return x, fmap
340
+
341
+
342
+ class DiscriminatorS(torch.nn.Module):
343
+ def __init__(self, use_spectral_norm=False):
344
+ super(DiscriminatorS, self).__init__()
345
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
346
+ self.convs = nn.ModuleList([
347
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
348
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
349
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
350
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
351
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
352
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
353
+ ])
354
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
355
+
356
+ def forward(self, x):
357
+ fmap = []
358
+
359
+ for l in self.convs:
360
+ x = l(x)
361
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
362
+ fmap.append(x)
363
+ x = self.conv_post(x)
364
+ fmap.append(x)
365
+ x = torch.flatten(x, 1, -1)
366
+
367
+ return x, fmap
368
+
369
+
370
+ class MultiPeriodDiscriminator(torch.nn.Module):
371
+ def __init__(self, use_spectral_norm=False):
372
+ super(MultiPeriodDiscriminator, self).__init__()
373
+ periods = [2,3,5,7,11]
374
+
375
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
376
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
377
+ self.discriminators = nn.ModuleList(discs)
378
+
379
+ def forward(self, y, y_hat):
380
+ y_d_rs = []
381
+ y_d_gs = []
382
+ fmap_rs = []
383
+ fmap_gs = []
384
+ for i, d in enumerate(self.discriminators):
385
+ y_d_r, fmap_r = d(y)
386
+ y_d_g, fmap_g = d(y_hat)
387
+ y_d_rs.append(y_d_r)
388
+ y_d_gs.append(y_d_g)
389
+ fmap_rs.append(fmap_r)
390
+ fmap_gs.append(fmap_g)
391
+
392
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
393
+
394
+
395
+
396
+ class SynthesizerTrn(nn.Module):
397
+ """
398
+ Synthesizer for Training
399
+ """
400
+
401
+ def __init__(self,
402
+ n_vocab,
403
+ spec_channels,
404
+ segment_size,
405
+ inter_channels,
406
+ hidden_channels,
407
+ filter_channels,
408
+ n_heads,
409
+ n_layers,
410
+ kernel_size,
411
+ p_dropout,
412
+ resblock,
413
+ resblock_kernel_sizes,
414
+ resblock_dilation_sizes,
415
+ upsample_rates,
416
+ upsample_initial_channel,
417
+ upsample_kernel_sizes,
418
+ n_speakers=0,
419
+ gin_channels=0,
420
+ use_sdp=True,
421
+ emotion_embedding=False,
422
+ **kwargs):
423
+
424
+ super().__init__()
425
+ self.n_vocab = n_vocab
426
+ self.spec_channels = spec_channels
427
+ self.inter_channels = inter_channels
428
+ self.hidden_channels = hidden_channels
429
+ self.filter_channels = filter_channels
430
+ self.n_heads = n_heads
431
+ self.n_layers = n_layers
432
+ self.kernel_size = kernel_size
433
+ self.p_dropout = p_dropout
434
+ self.resblock = resblock
435
+ self.resblock_kernel_sizes = resblock_kernel_sizes
436
+ self.resblock_dilation_sizes = resblock_dilation_sizes
437
+ self.upsample_rates = upsample_rates
438
+ self.upsample_initial_channel = upsample_initial_channel
439
+ self.upsample_kernel_sizes = upsample_kernel_sizes
440
+ self.segment_size = segment_size
441
+ self.n_speakers = n_speakers
442
+ self.gin_channels = gin_channels
443
+
444
+ self.use_sdp = use_sdp
445
+
446
+ self.enc_p = TextEncoder(n_vocab,
447
+ inter_channels,
448
+ hidden_channels,
449
+ filter_channels,
450
+ n_heads,
451
+ n_layers,
452
+ kernel_size,
453
+ p_dropout,
454
+ emotion_embedding)
455
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
456
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
457
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
458
+
459
+ if use_sdp:
460
+ self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
461
+ else:
462
+ self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
463
+
464
+ if n_speakers > 1:
465
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
466
+
467
+ def forward(self, x, x_lengths, y, y_lengths, sid=None):
468
+
469
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
470
+ if self.n_speakers > 0:
471
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
472
+ else:
473
+ g = None
474
+
475
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
476
+ z_p = self.flow(z, y_mask, g=g)
477
+
478
+ with torch.no_grad():
479
+ # negative cross-entropy
480
+ s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
481
+ neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s]
482
+ neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
483
+ neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
484
+ neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
485
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
486
+
487
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
488
+ attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
489
+
490
+ w = attn.sum(2)
491
+ if self.use_sdp:
492
+ l_length = self.dp(x, x_mask, w, g=g)
493
+ l_length = l_length / torch.sum(x_mask)
494
+ else:
495
+ logw_ = torch.log(w + 1e-6) * x_mask
496
+ logw = self.dp(x, x_mask, g=g)
497
+ l_length = torch.sum((logw - logw_)**2, [1,2]) / torch.sum(x_mask) # for averaging
498
+
499
+ # expand prior
500
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
501
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
502
+
503
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
504
+ o = self.dec(z_slice, g=g)
505
+ return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
506
+
507
+ def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None, emotion_embedding=None):
508
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, emotion_embedding)
509
+ if self.n_speakers > 0:
510
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
511
+ else:
512
+ g = None
513
+
514
+ if self.use_sdp:
515
+ logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
516
+ else:
517
+ logw = self.dp(x, x_mask, g=g)
518
+ w = torch.exp(logw) * x_mask * length_scale
519
+ w_ceil = torch.ceil(w)
520
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
521
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
522
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
523
+ attn = commons.generate_path(w_ceil, attn_mask)
524
+
525
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
526
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
527
+
528
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
529
+ z = self.flow(z_p, y_mask, g=g, reverse=True)
530
+ o = self.dec((z * y_mask)[:,:,:max_len], g=g)
531
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
532
+
533
+ def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
534
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
535
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
536
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
537
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
538
+ z_p = self.flow(z, y_mask, g=g_src)
539
+ z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
540
+ o_hat = self.dec(z_hat * y_mask, g=g_tgt)
541
+ return o_hat, y_mask, (z, z_p, z_hat)
542
+
Mutsumi-Chan/VITS-Umamusume-Voice/modules.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from torch.nn import Conv1d
7
+ from torch.nn.utils import weight_norm, remove_weight_norm
8
+
9
+ import commons
10
+ from commons import init_weights, get_padding
11
+ from transforms import piecewise_rational_quadratic_transform
12
+
13
+
14
+ LRELU_SLOPE = 0.1
15
+
16
+
17
+ class LayerNorm(nn.Module):
18
+ def __init__(self, channels, eps=1e-5):
19
+ super().__init__()
20
+ self.channels = channels
21
+ self.eps = eps
22
+
23
+ self.gamma = nn.Parameter(torch.ones(channels))
24
+ self.beta = nn.Parameter(torch.zeros(channels))
25
+
26
+ def forward(self, x):
27
+ x = x.transpose(1, -1)
28
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
29
+ return x.transpose(1, -1)
30
+
31
+
32
+ class ConvReluNorm(nn.Module):
33
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
34
+ super().__init__()
35
+ self.in_channels = in_channels
36
+ self.hidden_channels = hidden_channels
37
+ self.out_channels = out_channels
38
+ self.kernel_size = kernel_size
39
+ self.n_layers = n_layers
40
+ self.p_dropout = p_dropout
41
+ assert n_layers > 1, "Number of layers should be larger than 0."
42
+
43
+ self.conv_layers = nn.ModuleList()
44
+ self.norm_layers = nn.ModuleList()
45
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
46
+ self.norm_layers.append(LayerNorm(hidden_channels))
47
+ self.relu_drop = nn.Sequential(
48
+ nn.ReLU(),
49
+ nn.Dropout(p_dropout))
50
+ for _ in range(n_layers-1):
51
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
52
+ self.norm_layers.append(LayerNorm(hidden_channels))
53
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
54
+ self.proj.weight.data.zero_()
55
+ self.proj.bias.data.zero_()
56
+
57
+ def forward(self, x, x_mask):
58
+ x_org = x
59
+ for i in range(self.n_layers):
60
+ x = self.conv_layers[i](x * x_mask)
61
+ x = self.norm_layers[i](x)
62
+ x = self.relu_drop(x)
63
+ x = x_org + self.proj(x)
64
+ return x * x_mask
65
+
66
+
67
+ class DDSConv(nn.Module):
68
+ """
69
+ Dialted and Depth-Separable Convolution
70
+ """
71
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
72
+ super().__init__()
73
+ self.channels = channels
74
+ self.kernel_size = kernel_size
75
+ self.n_layers = n_layers
76
+ self.p_dropout = p_dropout
77
+
78
+ self.drop = nn.Dropout(p_dropout)
79
+ self.convs_sep = nn.ModuleList()
80
+ self.convs_1x1 = nn.ModuleList()
81
+ self.norms_1 = nn.ModuleList()
82
+ self.norms_2 = nn.ModuleList()
83
+ for i in range(n_layers):
84
+ dilation = kernel_size ** i
85
+ padding = (kernel_size * dilation - dilation) // 2
86
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
87
+ groups=channels, dilation=dilation, padding=padding
88
+ ))
89
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
90
+ self.norms_1.append(LayerNorm(channels))
91
+ self.norms_2.append(LayerNorm(channels))
92
+
93
+ def forward(self, x, x_mask, g=None):
94
+ if g is not None:
95
+ x = x + g
96
+ for i in range(self.n_layers):
97
+ y = self.convs_sep[i](x * x_mask)
98
+ y = self.norms_1[i](y)
99
+ y = F.gelu(y)
100
+ y = self.convs_1x1[i](y)
101
+ y = self.norms_2[i](y)
102
+ y = F.gelu(y)
103
+ y = self.drop(y)
104
+ x = x + y
105
+ return x * x_mask
106
+
107
+
108
+ class WN(torch.nn.Module):
109
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
110
+ super(WN, self).__init__()
111
+ assert(kernel_size % 2 == 1)
112
+ self.hidden_channels =hidden_channels
113
+ self.kernel_size = kernel_size,
114
+ self.dilation_rate = dilation_rate
115
+ self.n_layers = n_layers
116
+ self.gin_channels = gin_channels
117
+ self.p_dropout = p_dropout
118
+
119
+ self.in_layers = torch.nn.ModuleList()
120
+ self.res_skip_layers = torch.nn.ModuleList()
121
+ self.drop = nn.Dropout(p_dropout)
122
+
123
+ if gin_channels != 0:
124
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
125
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
126
+
127
+ for i in range(n_layers):
128
+ dilation = dilation_rate ** i
129
+ padding = int((kernel_size * dilation - dilation) / 2)
130
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
131
+ dilation=dilation, padding=padding)
132
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
133
+ self.in_layers.append(in_layer)
134
+
135
+ # last one is not necessary
136
+ if i < n_layers - 1:
137
+ res_skip_channels = 2 * hidden_channels
138
+ else:
139
+ res_skip_channels = hidden_channels
140
+
141
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
142
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
143
+ self.res_skip_layers.append(res_skip_layer)
144
+
145
+ def forward(self, x, x_mask, g=None, **kwargs):
146
+ output = torch.zeros_like(x)
147
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
148
+
149
+ if g is not None:
150
+ g = self.cond_layer(g)
151
+
152
+ for i in range(self.n_layers):
153
+ x_in = self.in_layers[i](x)
154
+ if g is not None:
155
+ cond_offset = i * 2 * self.hidden_channels
156
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
157
+ else:
158
+ g_l = torch.zeros_like(x_in)
159
+
160
+ acts = commons.fused_add_tanh_sigmoid_multiply(
161
+ x_in,
162
+ g_l,
163
+ n_channels_tensor)
164
+ acts = self.drop(acts)
165
+
166
+ res_skip_acts = self.res_skip_layers[i](acts)
167
+ if i < self.n_layers - 1:
168
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
169
+ x = (x + res_acts) * x_mask
170
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
171
+ else:
172
+ output = output + res_skip_acts
173
+ return output * x_mask
174
+
175
+ def remove_weight_norm(self):
176
+ if self.gin_channels != 0:
177
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
178
+ for l in self.in_layers:
179
+ torch.nn.utils.remove_weight_norm(l)
180
+ for l in self.res_skip_layers:
181
+ torch.nn.utils.remove_weight_norm(l)
182
+
183
+
184
+ class ResBlock1(torch.nn.Module):
185
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
186
+ super(ResBlock1, self).__init__()
187
+ self.convs1 = nn.ModuleList([
188
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
189
+ padding=get_padding(kernel_size, dilation[0]))),
190
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
191
+ padding=get_padding(kernel_size, dilation[1]))),
192
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
193
+ padding=get_padding(kernel_size, dilation[2])))
194
+ ])
195
+ self.convs1.apply(init_weights)
196
+
197
+ self.convs2 = nn.ModuleList([
198
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
199
+ padding=get_padding(kernel_size, 1))),
200
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
201
+ padding=get_padding(kernel_size, 1))),
202
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
203
+ padding=get_padding(kernel_size, 1)))
204
+ ])
205
+ self.convs2.apply(init_weights)
206
+
207
+ def forward(self, x, x_mask=None):
208
+ for c1, c2 in zip(self.convs1, self.convs2):
209
+ xt = F.leaky_relu(x, LRELU_SLOPE)
210
+ if x_mask is not None:
211
+ xt = xt * x_mask
212
+ xt = c1(xt)
213
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
214
+ if x_mask is not None:
215
+ xt = xt * x_mask
216
+ xt = c2(xt)
217
+ x = xt + x
218
+ if x_mask is not None:
219
+ x = x * x_mask
220
+ return x
221
+
222
+ def remove_weight_norm(self):
223
+ for l in self.convs1:
224
+ remove_weight_norm(l)
225
+ for l in self.convs2:
226
+ remove_weight_norm(l)
227
+
228
+
229
+ class ResBlock2(torch.nn.Module):
230
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
231
+ super(ResBlock2, self).__init__()
232
+ self.convs = nn.ModuleList([
233
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
234
+ padding=get_padding(kernel_size, dilation[0]))),
235
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
236
+ padding=get_padding(kernel_size, dilation[1])))
237
+ ])
238
+ self.convs.apply(init_weights)
239
+
240
+ def forward(self, x, x_mask=None):
241
+ for c in self.convs:
242
+ xt = F.leaky_relu(x, LRELU_SLOPE)
243
+ if x_mask is not None:
244
+ xt = xt * x_mask
245
+ xt = c(xt)
246
+ x = xt + x
247
+ if x_mask is not None:
248
+ x = x * x_mask
249
+ return x
250
+
251
+ def remove_weight_norm(self):
252
+ for l in self.convs:
253
+ remove_weight_norm(l)
254
+
255
+
256
+ class Log(nn.Module):
257
+ def forward(self, x, x_mask, reverse=False, **kwargs):
258
+ if not reverse:
259
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
260
+ logdet = torch.sum(-y, [1, 2])
261
+ return y, logdet
262
+ else:
263
+ x = torch.exp(x) * x_mask
264
+ return x
265
+
266
+
267
+ class Flip(nn.Module):
268
+ def forward(self, x, *args, reverse=False, **kwargs):
269
+ x = torch.flip(x, [1])
270
+ if not reverse:
271
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
272
+ return x, logdet
273
+ else:
274
+ return x
275
+
276
+
277
+ class ElementwiseAffine(nn.Module):
278
+ def __init__(self, channels):
279
+ super().__init__()
280
+ self.channels = channels
281
+ self.m = nn.Parameter(torch.zeros(channels,1))
282
+ self.logs = nn.Parameter(torch.zeros(channels,1))
283
+
284
+ def forward(self, x, x_mask, reverse=False, **kwargs):
285
+ if not reverse:
286
+ y = self.m + torch.exp(self.logs) * x
287
+ y = y * x_mask
288
+ logdet = torch.sum(self.logs * x_mask, [1,2])
289
+ return y, logdet
290
+ else:
291
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
292
+ return x
293
+
294
+
295
+ class ResidualCouplingLayer(nn.Module):
296
+ def __init__(self,
297
+ channels,
298
+ hidden_channels,
299
+ kernel_size,
300
+ dilation_rate,
301
+ n_layers,
302
+ p_dropout=0,
303
+ gin_channels=0,
304
+ mean_only=False):
305
+ assert channels % 2 == 0, "channels should be divisible by 2"
306
+ super().__init__()
307
+ self.channels = channels
308
+ self.hidden_channels = hidden_channels
309
+ self.kernel_size = kernel_size
310
+ self.dilation_rate = dilation_rate
311
+ self.n_layers = n_layers
312
+ self.half_channels = channels // 2
313
+ self.mean_only = mean_only
314
+
315
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
316
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
317
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
318
+ self.post.weight.data.zero_()
319
+ self.post.bias.data.zero_()
320
+
321
+ def forward(self, x, x_mask, g=None, reverse=False):
322
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
323
+ h = self.pre(x0) * x_mask
324
+ h = self.enc(h, x_mask, g=g)
325
+ stats = self.post(h) * x_mask
326
+ if not self.mean_only:
327
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
328
+ else:
329
+ m = stats
330
+ logs = torch.zeros_like(m)
331
+
332
+ if not reverse:
333
+ x1 = m + x1 * torch.exp(logs) * x_mask
334
+ x = torch.cat([x0, x1], 1)
335
+ logdet = torch.sum(logs, [1,2])
336
+ return x, logdet
337
+ else:
338
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
339
+ x = torch.cat([x0, x1], 1)
340
+ return x
341
+
342
+
343
+ class ConvFlow(nn.Module):
344
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
345
+ super().__init__()
346
+ self.in_channels = in_channels
347
+ self.filter_channels = filter_channels
348
+ self.kernel_size = kernel_size
349
+ self.n_layers = n_layers
350
+ self.num_bins = num_bins
351
+ self.tail_bound = tail_bound
352
+ self.half_channels = in_channels // 2
353
+
354
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
355
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
356
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
357
+ self.proj.weight.data.zero_()
358
+ self.proj.bias.data.zero_()
359
+
360
+ def forward(self, x, x_mask, g=None, reverse=False):
361
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
362
+ h = self.pre(x0)
363
+ h = self.convs(h, x_mask, g=g)
364
+ h = self.proj(h) * x_mask
365
+
366
+ b, c, t = x0.shape
367
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
368
+
369
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
370
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
371
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
372
+
373
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
374
+ unnormalized_widths,
375
+ unnormalized_heights,
376
+ unnormalized_derivatives,
377
+ inverse=reverse,
378
+ tails='linear',
379
+ tail_bound=self.tail_bound
380
+ )
381
+
382
+ x = torch.cat([x0, x1], 1) * x_mask
383
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
384
+ if not reverse:
385
+ return x, logdet
386
+ else:
387
+ return x
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from .monotonic_align.core import maximum_path_c
4
+
5
+
6
+ def maximum_path(neg_cent, mask):
7
+ """ Cython optimized version.
8
+ neg_cent: [b, t_t, t_s]
9
+ mask: [b, t_t, t_s]
10
+ """
11
+ device = neg_cent.device
12
+ dtype = neg_cent.dtype
13
+ neg_cent = neg_cent.data.cpu().numpy().astype(np.float32)
14
+ path = np.zeros(neg_cent.shape, dtype=np.int32)
15
+
16
+ t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(np.int32)
17
+ t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(np.int32)
18
+ maximum_path_c(path, neg_cent, t_t_max, t_s_max)
19
+ return torch.from_numpy(path).to(device=device, dtype=dtype)
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (765 Bytes). View file
 
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/lib.win-amd64-cpython-37/monotonic_align/core.cp37-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:133e16a41253706884ea03ccf642058d436e81b89f7e2c937ff804c36c65ca52
3
+ size 119808
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.exp ADDED
Binary file (697 Bytes). View file
 
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.lib ADDED
Binary file (1.94 kB). View file
 
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/build/temp.win-amd64-cpython-37/Release/core.obj ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71c71ef468312a844b18da92057709360141cad8f7423f4c36995b10046bad12
3
+ size 848249
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/core.c ADDED
The diff for this file is too large to render. See raw diff
 
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/core.pyx ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport cython
2
+ from cython.parallel import prange
3
+
4
+
5
+ @cython.boundscheck(False)
6
+ @cython.wraparound(False)
7
+ cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil:
8
+ cdef int x
9
+ cdef int y
10
+ cdef float v_prev
11
+ cdef float v_cur
12
+ cdef float tmp
13
+ cdef int index = t_x - 1
14
+
15
+ for y in range(t_y):
16
+ for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
17
+ if x == y:
18
+ v_cur = max_neg_val
19
+ else:
20
+ v_cur = value[y-1, x]
21
+ if x == 0:
22
+ if y == 0:
23
+ v_prev = 0.
24
+ else:
25
+ v_prev = max_neg_val
26
+ else:
27
+ v_prev = value[y-1, x-1]
28
+ value[y, x] += max(v_prev, v_cur)
29
+
30
+ for y in range(t_y - 1, -1, -1):
31
+ path[y, index] = 1
32
+ if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]):
33
+ index = index - 1
34
+
35
+
36
+ @cython.boundscheck(False)
37
+ @cython.wraparound(False)
38
+ cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil:
39
+ cdef int b = paths.shape[0]
40
+ cdef int i
41
+ for i in prange(b, nogil=True):
42
+ maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i])
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/monotonic_align/core.cp37-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:133e16a41253706884ea03ccf642058d436e81b89f7e2c937ff804c36c65ca52
3
+ size 119808
Mutsumi-Chan/VITS-Umamusume-Voice/monotonic_align/setup.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from distutils.core import setup
2
+ from Cython.Build import cythonize
3
+ import numpy
4
+
5
+ setup(
6
+ name = 'monotonic_align',
7
+ ext_modules = cythonize("core.pyx"),
8
+ include_dirs=[numpy.get_include()]
9
+ )
Mutsumi-Chan/VITS-Umamusume-Voice/packages.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ cmake
2
+ ffmpeg
3
+ libsm6
4
+ libxext6
5
+ espeak-ng
Mutsumi-Chan/VITS-Umamusume-Voice/pretrained_models/D_trilingual.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:920fb34bf3dc466e761996e787952a7bd53d4f6699561e9141bcbcf4f3f34092
3
+ size 187024867
Mutsumi-Chan/VITS-Umamusume-Voice/pretrained_models/G_jp.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a53f4eb6bf8226b3fb4a3b31436235f697692f5566039ce3491b80af9a9567a
3
+ size 158962765
Mutsumi-Chan/VITS-Umamusume-Voice/pretrained_models/G_trilingual.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:651381372bd0936fa90cdcfd75c8c4c231edd341a180466fc65dd3f75c5e4d70
3
+ size 159918157
Mutsumi-Chan/VITS-Umamusume-Voice/requirements.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build Tools & Core
2
+ setuptools
3
+ wheel
4
+ pip>=23.0
5
+
6
+ # Core Data & Math
7
+ numpy==1.26.4
8
+ scipy
9
+ numba
10
+ psutil
11
+
12
+ # Audio & Signal Processing
13
+ librosa
14
+ phonemizer
15
+ unidecode
16
+ pyopenjtalk-prebuilt
17
+ jamo
18
+ pypinyin
19
+ ko_pron
20
+ jieba
21
+ cn2an
22
+ inflect
23
+ eng_to_ipa
24
+ indic_transliteration
25
+ num_thai
26
+ opencc
27
+
28
+ # AI & Deep Learning
29
+ torch
30
+ torchvision
31
+ torchaudio
32
+ onnx
33
+ onnxruntime
34
+ tensorboard
35
+ protobuf
36
+ huggingface_hub==0.20.3
37
+
38
+ # UI Framework
39
+ gradio==4.19.2
40
+ matplotlib
Mutsumi-Chan/VITS-Umamusume-Voice/text/LICENSE.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2017 Keith Ito
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
Mutsumi-Chan/VITS-Umamusume-Voice/text/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+ from text import cleaners
3
+
4
+
5
+ def text_to_sequence(text, symbols, cleaner_names):
6
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
7
+ Args:
8
+ text: string to convert to a sequence
9
+ cleaner_names: names of the cleaner functions to run the text through
10
+ Returns:
11
+ List of integers corresponding to the symbols in the text
12
+ '''
13
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
14
+
15
+ sequence = []
16
+
17
+ clean_text = _clean_text(text, cleaner_names)
18
+ for symbol in clean_text:
19
+ if symbol not in _symbol_to_id.keys():
20
+ continue
21
+ symbol_id = _symbol_to_id[symbol]
22
+ sequence += [symbol_id]
23
+ return sequence
24
+
25
+
26
+ def _clean_text(text, cleaner_names):
27
+ for name in cleaner_names:
28
+ cleaner = getattr(cleaners, name)
29
+ if not cleaner:
30
+ raise Exception('Unknown cleaner: %s' % name)
31
+ text = cleaner(text)
32
+ return text