cymic Plachta commited on
Commit
021dd19
0 Parent(s):

Duplicate from Plachta/VITS-Umamusume-voice-synthesizer

Browse files

Co-authored-by: ElderFrog <[email protected]>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +34 -0
  2. ONNXVITS_infer.py +154 -0
  3. ONNXVITS_inference.py +36 -0
  4. ONNXVITS_models.py +509 -0
  5. ONNXVITS_modules.py +390 -0
  6. ONNXVITS_to_onnx.py +31 -0
  7. ONNXVITS_transforms.py +196 -0
  8. ONNXVITS_utils.py +19 -0
  9. ONNX_net/dec.onnx +3 -0
  10. ONNX_net/dp.onnx +3 -0
  11. ONNX_net/enc_p.onnx +3 -0
  12. ONNX_net/flow.onnx +3 -0
  13. README.md +13 -0
  14. app.py +363 -0
  15. attentions.py +300 -0
  16. commons.py +97 -0
  17. configs/uma87.json +142 -0
  18. data_utils.py +393 -0
  19. hubert_model.py +221 -0
  20. jieba/dict.txt +0 -0
  21. losses.py +61 -0
  22. mel_processing.py +101 -0
  23. models.py +542 -0
  24. modules.py +387 -0
  25. monotonic_align/__init__.py +19 -0
  26. monotonic_align/__pycache__/__init__.cpython-37.pyc +0 -0
  27. monotonic_align/build/lib.win-amd64-cpython-37/monotonic_align/core.cp37-win_amd64.pyd +0 -0
  28. monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.exp +0 -0
  29. monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.lib +0 -0
  30. monotonic_align/build/temp.win-amd64-cpython-37/Release/core.obj +0 -0
  31. monotonic_align/core.c +0 -0
  32. monotonic_align/core.pyx +42 -0
  33. monotonic_align/monotonic_align/core.cp37-win_amd64.pyd +0 -0
  34. monotonic_align/setup.py +9 -0
  35. pretrained_models/G_1153000.pth +3 -0
  36. pretrained_models/uma87_817000.pth +3 -0
  37. requirements.txt +22 -0
  38. text/LICENSE +19 -0
  39. text/__init__.py +32 -0
  40. text/__pycache__/__init__.cpython-37.pyc +0 -0
  41. text/__pycache__/cleaners.cpython-37.pyc +0 -0
  42. text/__pycache__/english.cpython-37.pyc +0 -0
  43. text/__pycache__/japanese.cpython-37.pyc +0 -0
  44. text/__pycache__/korean.cpython-37.pyc +0 -0
  45. text/__pycache__/mandarin.cpython-37.pyc +0 -0
  46. text/__pycache__/sanskrit.cpython-37.pyc +0 -0
  47. text/__pycache__/symbols.cpython-37.pyc +0 -0
  48. text/__pycache__/thai.cpython-37.pyc +0 -0
  49. text/cantonese.py +59 -0
  50. text/cleaners.py +146 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
ONNXVITS_infer.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import commons
3
+ import models
4
+ class SynthesizerTrn(models.SynthesizerTrn):
5
+ """
6
+ Synthesizer for Training
7
+ """
8
+
9
+ def __init__(self,
10
+ n_vocab,
11
+ spec_channels,
12
+ segment_size,
13
+ inter_channels,
14
+ hidden_channels,
15
+ filter_channels,
16
+ n_heads,
17
+ n_layers,
18
+ kernel_size,
19
+ p_dropout,
20
+ resblock,
21
+ resblock_kernel_sizes,
22
+ resblock_dilation_sizes,
23
+ upsample_rates,
24
+ upsample_initial_channel,
25
+ upsample_kernel_sizes,
26
+ n_speakers=0,
27
+ gin_channels=0,
28
+ use_sdp=True,
29
+ **kwargs):
30
+
31
+ super().__init__(
32
+ n_vocab,
33
+ spec_channels,
34
+ segment_size,
35
+ inter_channels,
36
+ hidden_channels,
37
+ filter_channels,
38
+ n_heads,
39
+ n_layers,
40
+ kernel_size,
41
+ p_dropout,
42
+ resblock,
43
+ resblock_kernel_sizes,
44
+ resblock_dilation_sizes,
45
+ upsample_rates,
46
+ upsample_initial_channel,
47
+ upsample_kernel_sizes,
48
+ n_speakers=n_speakers,
49
+ gin_channels=gin_channels,
50
+ use_sdp=use_sdp,
51
+ **kwargs
52
+ )
53
+
54
+ def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None):
55
+ from ONNXVITS_utils import runonnx
56
+
57
+ #x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
58
+ x, m_p, logs_p, x_mask = runonnx("ONNX_net/enc_p.onnx", x=x.numpy(), x_lengths=x_lengths.numpy())
59
+ x = torch.from_numpy(x)
60
+ m_p = torch.from_numpy(m_p)
61
+ logs_p = torch.from_numpy(logs_p)
62
+ x_mask = torch.from_numpy(x_mask)
63
+
64
+ if self.n_speakers > 0:
65
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
66
+ else:
67
+ g = None
68
+
69
+ #logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
70
+ logw = runonnx("ONNX_net/dp.onnx", x=x.numpy(), x_mask=x_mask.numpy(), g=g.numpy())
71
+ logw = torch.from_numpy(logw[0])
72
+
73
+ w = torch.exp(logw) * x_mask * length_scale
74
+ w_ceil = torch.ceil(w)
75
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
76
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
77
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
78
+ attn = commons.generate_path(w_ceil, attn_mask)
79
+
80
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
81
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
82
+
83
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
84
+
85
+ #z = self.flow(z_p, y_mask, g=g, reverse=True)
86
+ z = runonnx("ONNX_net/flow.onnx", z_p=z_p.numpy(), y_mask=y_mask.numpy(), g=g.numpy())
87
+ z = torch.from_numpy(z[0])
88
+
89
+ #o = self.dec((z * y_mask)[:,:,:max_len], g=g)
90
+ o = runonnx("ONNX_net/dec.onnx", z_in=(z * y_mask)[:,:,:max_len].numpy(), g=g.numpy())
91
+ o = torch.from_numpy(o[0])
92
+
93
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
94
+
95
+ def predict_duration(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None,
96
+ emotion_embedding=None):
97
+ from ONNXVITS_utils import runonnx
98
+
99
+ #x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
100
+ x, m_p, logs_p, x_mask = runonnx("ONNX_net/enc_p.onnx", x=x.numpy(), x_lengths=x_lengths.numpy())
101
+ x = torch.from_numpy(x)
102
+ m_p = torch.from_numpy(m_p)
103
+ logs_p = torch.from_numpy(logs_p)
104
+ x_mask = torch.from_numpy(x_mask)
105
+
106
+ if self.n_speakers > 0:
107
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
108
+ else:
109
+ g = None
110
+
111
+ #logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
112
+ logw = runonnx("ONNX_net/dp.onnx", x=x.numpy(), x_mask=x_mask.numpy(), g=g.numpy())
113
+ logw = torch.from_numpy(logw[0])
114
+
115
+ w = torch.exp(logw) * x_mask * length_scale
116
+ w_ceil = torch.ceil(w)
117
+ return list(w_ceil.squeeze())
118
+
119
+ def infer_with_duration(self, x, x_lengths, w_ceil, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None,
120
+ emotion_embedding=None):
121
+ from ONNXVITS_utils import runonnx
122
+
123
+ #x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
124
+ x, m_p, logs_p, x_mask = runonnx("ONNX_net/enc_p.onnx", x=x.numpy(), x_lengths=x_lengths.numpy())
125
+ x = torch.from_numpy(x)
126
+ m_p = torch.from_numpy(m_p)
127
+ logs_p = torch.from_numpy(logs_p)
128
+ x_mask = torch.from_numpy(x_mask)
129
+
130
+ if self.n_speakers > 0:
131
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
132
+ else:
133
+ g = None
134
+ assert len(w_ceil) == x.shape[2]
135
+ w_ceil = torch.FloatTensor(w_ceil).reshape(1, 1, -1)
136
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
137
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
138
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
139
+ attn = commons.generate_path(w_ceil, attn_mask)
140
+
141
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
142
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
143
+
144
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
145
+
146
+ #z = self.flow(z_p, y_mask, g=g, reverse=True)
147
+ z = runonnx("ONNX_net/flow.onnx", z_p=z_p.numpy(), y_mask=y_mask.numpy(), g=g.numpy())
148
+ z = torch.from_numpy(z[0])
149
+
150
+ #o = self.dec((z * y_mask)[:,:,:max_len], g=g)
151
+ o = runonnx("ONNX_net/dec.onnx", z_in=(z * y_mask)[:,:,:max_len].numpy(), g=g.numpy())
152
+ o = torch.from_numpy(o[0])
153
+
154
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
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)
ONNXVITS_models.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ import commons
8
+ import ONNXVITS_modules as modules
9
+ import attentions
10
+ import monotonic_align
11
+
12
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, 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 StochasticDurationPredictor(nn.Module):
18
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
19
+ super().__init__()
20
+ filter_channels = in_channels # it needs to be removed from future version.
21
+ self.in_channels = in_channels
22
+ self.filter_channels = filter_channels
23
+ self.kernel_size = kernel_size
24
+ self.p_dropout = p_dropout
25
+ self.n_flows = n_flows
26
+ self.gin_channels = gin_channels
27
+
28
+ self.log_flow = modules.Log()
29
+ self.flows = nn.ModuleList()
30
+ self.flows.append(modules.ElementwiseAffine(2))
31
+ for i in range(n_flows):
32
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
33
+ self.flows.append(modules.Flip())
34
+
35
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
36
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
37
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
38
+ self.post_flows = nn.ModuleList()
39
+ self.post_flows.append(modules.ElementwiseAffine(2))
40
+ for i in range(4):
41
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
42
+ self.post_flows.append(modules.Flip())
43
+
44
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
45
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
46
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
47
+ if gin_channels != 0:
48
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
49
+
50
+ self.w = None
51
+ self.reverse = None
52
+ self.noise_scale = None
53
+ def forward(self, x, x_mask, g=None):
54
+ w = self.w
55
+ reverse = self.reverse
56
+ noise_scale = self.noise_scale
57
+
58
+ x = torch.detach(x)
59
+ x = self.pre(x)
60
+ if g is not None:
61
+ g = torch.detach(g)
62
+ x = x + self.cond(g)
63
+ x = self.convs(x, x_mask)
64
+ x = self.proj(x) * x_mask
65
+
66
+ if not reverse:
67
+ flows = self.flows
68
+ assert w is not None
69
+
70
+ logdet_tot_q = 0
71
+ h_w = self.post_pre(w)
72
+ h_w = self.post_convs(h_w, x_mask)
73
+ h_w = self.post_proj(h_w) * x_mask
74
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
75
+ z_q = e_q
76
+ for flow in self.post_flows:
77
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
78
+ logdet_tot_q += logdet_q
79
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
80
+ u = torch.sigmoid(z_u) * x_mask
81
+ z0 = (w - u) * x_mask
82
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2])
83
+ logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q
84
+
85
+ logdet_tot = 0
86
+ z0, logdet = self.log_flow(z0, x_mask)
87
+ logdet_tot += logdet
88
+ z = torch.cat([z0, z1], 1)
89
+ for flow in flows:
90
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
91
+ logdet_tot = logdet_tot + logdet
92
+ nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot
93
+ return nll + logq # [b]
94
+ else:
95
+ flows = list(reversed(self.flows))
96
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
97
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
98
+ for flow in flows:
99
+ z = flow(z, x_mask, g=x, reverse=reverse)
100
+ z0, z1 = torch.split(z, [1, 1], 1)
101
+ logw = z0
102
+ return logw
103
+
104
+
105
+ class TextEncoder(nn.Module):
106
+ def __init__(self,
107
+ n_vocab,
108
+ out_channels,
109
+ hidden_channels,
110
+ filter_channels,
111
+ n_heads,
112
+ n_layers,
113
+ kernel_size,
114
+ p_dropout):
115
+ super().__init__()
116
+ self.n_vocab = n_vocab
117
+ self.out_channels = out_channels
118
+ self.hidden_channels = hidden_channels
119
+ self.filter_channels = filter_channels
120
+ self.n_heads = n_heads
121
+ self.n_layers = n_layers
122
+ self.kernel_size = kernel_size
123
+ self.p_dropout = p_dropout
124
+
125
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
126
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
127
+
128
+ self.encoder = attentions.Encoder(
129
+ hidden_channels,
130
+ filter_channels,
131
+ n_heads,
132
+ n_layers,
133
+ kernel_size,
134
+ p_dropout)
135
+ self.proj= nn.Conv1d(hidden_channels, out_channels * 2, 1)
136
+
137
+ def forward(self, x, x_lengths):
138
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
139
+ x = torch.transpose(x, 1, -1) # [b, h, t]
140
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
141
+
142
+ x = self.encoder(x * x_mask, x_mask)
143
+ stats = self.proj(x) * x_mask
144
+
145
+ m, logs = torch.split(stats, self.out_channels, dim=1)
146
+ return x, m, logs, x_mask
147
+
148
+
149
+ class ResidualCouplingBlock(nn.Module):
150
+ def __init__(self,
151
+ channels,
152
+ hidden_channels,
153
+ kernel_size,
154
+ dilation_rate,
155
+ n_layers,
156
+ n_flows=4,
157
+ gin_channels=0):
158
+ super().__init__()
159
+ self.channels = channels
160
+ self.hidden_channels = hidden_channels
161
+ self.kernel_size = kernel_size
162
+ self.dilation_rate = dilation_rate
163
+ self.n_layers = n_layers
164
+ self.n_flows = n_flows
165
+ self.gin_channels = gin_channels
166
+
167
+ self.flows = nn.ModuleList()
168
+ for i in range(n_flows):
169
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
170
+ self.flows.append(modules.Flip())
171
+
172
+ self.reverse = None
173
+ def forward(self, x, x_mask, g=None):
174
+ reverse = self.reverse
175
+ if not reverse:
176
+ for flow in self.flows:
177
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
178
+ else:
179
+ for flow in reversed(self.flows):
180
+ x = flow(x, x_mask, g=g, reverse=reverse)
181
+ return x
182
+
183
+
184
+ class PosteriorEncoder(nn.Module):
185
+ def __init__(self,
186
+ in_channels,
187
+ out_channels,
188
+ hidden_channels,
189
+ kernel_size,
190
+ dilation_rate,
191
+ n_layers,
192
+ gin_channels=0):
193
+ super().__init__()
194
+ self.in_channels = in_channels
195
+ self.out_channels = out_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.gin_channels = gin_channels
201
+
202
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
203
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
204
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
205
+
206
+ def forward(self, x, x_lengths, g=None):
207
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
208
+ x = self.pre(x) * x_mask # x_in : [b, c, t] -> [b, h, t]
209
+ x = self.enc(x, x_mask, g=g) # x_in : [b, h, t], g : [b, h, 1], x = x_in + g
210
+ stats = self.proj(x) * x_mask
211
+ m, logs = torch.split(stats, self.out_channels, dim=1)
212
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
213
+ return z, m, logs, x_mask # z, m, logs : [b, h, t]
214
+
215
+
216
+ class Generator(torch.nn.Module):
217
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
218
+ super(Generator, self).__init__()
219
+ self.num_kernels = len(resblock_kernel_sizes)
220
+ self.num_upsamples = len(upsample_rates)
221
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
222
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
223
+
224
+ self.ups = nn.ModuleList()
225
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
226
+ self.ups.append(weight_norm(
227
+ ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
228
+ k, u, padding=(k-u)//2)))
229
+
230
+ self.resblocks = nn.ModuleList()
231
+ for i in range(len(self.ups)):
232
+ ch = upsample_initial_channel//(2**(i+1))
233
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
234
+ self.resblocks.append(resblock(ch, k, d))
235
+
236
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
237
+ self.ups.apply(init_weights)
238
+
239
+ if gin_channels != 0:
240
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
241
+
242
+ def forward(self, x, g=None):
243
+ x = self.conv_pre(x)
244
+ if g is not None:
245
+ x = x + self.cond(g)
246
+
247
+ for i in range(self.num_upsamples):
248
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
249
+ x = self.ups[i](x)
250
+ xs = None
251
+ for j in range(self.num_kernels):
252
+ if xs is None:
253
+ xs = self.resblocks[i*self.num_kernels+j](x)
254
+ else:
255
+ xs += self.resblocks[i*self.num_kernels+j](x)
256
+ x = xs / self.num_kernels
257
+ x = F.leaky_relu(x)
258
+ x = self.conv_post(x)
259
+ x = torch.tanh(x)
260
+
261
+ return x
262
+
263
+ def remove_weight_norm(self):
264
+ print('Removing weight norm...')
265
+ for l in self.ups:
266
+ remove_weight_norm(l)
267
+ for l in self.resblocks:
268
+ l.remove_weight_norm()
269
+
270
+
271
+ class DiscriminatorP(torch.nn.Module):
272
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
273
+ super(DiscriminatorP, self).__init__()
274
+ self.period = period
275
+ self.use_spectral_norm = use_spectral_norm
276
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
277
+ self.convs = nn.ModuleList([
278
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
279
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
280
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
281
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
282
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
283
+ ])
284
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
285
+
286
+ def forward(self, x):
287
+ fmap = []
288
+
289
+ # 1d to 2d
290
+ b, c, t = x.shape
291
+ if t % self.period != 0: # pad first
292
+ n_pad = self.period - (t % self.period)
293
+ x = F.pad(x, (0, n_pad), "reflect")
294
+ t = t + n_pad
295
+ x = x.view(b, c, t // self.period, self.period)
296
+
297
+ for l in self.convs:
298
+ x = l(x)
299
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
300
+ fmap.append(x)
301
+ x = self.conv_post(x)
302
+ fmap.append(x)
303
+ x = torch.flatten(x, 1, -1)
304
+
305
+ return x, fmap
306
+
307
+
308
+ class DiscriminatorS(torch.nn.Module):
309
+ def __init__(self, use_spectral_norm=False):
310
+ super(DiscriminatorS, self).__init__()
311
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
312
+ self.convs = nn.ModuleList([
313
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
314
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
315
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
316
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
317
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
318
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
319
+ ])
320
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
321
+
322
+ def forward(self, x):
323
+ fmap = []
324
+
325
+ for l in self.convs:
326
+ x = l(x)
327
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
328
+ fmap.append(x)
329
+ x = self.conv_post(x)
330
+ fmap.append(x)
331
+ x = torch.flatten(x, 1, -1)
332
+
333
+ return x, fmap
334
+
335
+
336
+ class MultiPeriodDiscriminator(torch.nn.Module):
337
+ def __init__(self, use_spectral_norm=False):
338
+ super(MultiPeriodDiscriminator, self).__init__()
339
+ periods = [2,3,5,7,11]
340
+
341
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
342
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
343
+ self.discriminators = nn.ModuleList(discs)
344
+
345
+ def forward(self, y, y_hat):
346
+ y_d_rs = []
347
+ y_d_gs = []
348
+ fmap_rs = []
349
+ fmap_gs = []
350
+ for i, d in enumerate(self.discriminators):
351
+ y_d_r, fmap_r = d(y)
352
+ y_d_g, fmap_g = d(y_hat)
353
+ y_d_rs.append(y_d_r)
354
+ y_d_gs.append(y_d_g)
355
+ fmap_rs.append(fmap_r)
356
+ fmap_gs.append(fmap_g)
357
+
358
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
359
+
360
+
361
+
362
+ class SynthesizerTrn(nn.Module):
363
+ """
364
+ Synthesizer for Training
365
+ """
366
+
367
+ def __init__(self,
368
+ n_vocab,
369
+ spec_channels,
370
+ segment_size,
371
+ inter_channels,
372
+ hidden_channels,
373
+ filter_channels,
374
+ n_heads,
375
+ n_layers,
376
+ kernel_size,
377
+ p_dropout,
378
+ resblock,
379
+ resblock_kernel_sizes,
380
+ resblock_dilation_sizes,
381
+ upsample_rates,
382
+ upsample_initial_channel,
383
+ upsample_kernel_sizes,
384
+ n_speakers=0,
385
+ gin_channels=0,
386
+ use_sdp=True,
387
+ **kwargs):
388
+
389
+ super().__init__()
390
+ self.n_vocab = n_vocab
391
+ self.spec_channels = spec_channels
392
+ self.inter_channels = inter_channels
393
+ self.hidden_channels = hidden_channels
394
+ self.filter_channels = filter_channels
395
+ self.n_heads = n_heads
396
+ self.n_layers = n_layers
397
+ self.kernel_size = kernel_size
398
+ self.p_dropout = p_dropout
399
+ self.resblock = resblock
400
+ self.resblock_kernel_sizes = resblock_kernel_sizes
401
+ self.resblock_dilation_sizes = resblock_dilation_sizes
402
+ self.upsample_rates = upsample_rates
403
+ self.upsample_initial_channel = upsample_initial_channel
404
+ self.upsample_kernel_sizes = upsample_kernel_sizes
405
+ self.segment_size = segment_size
406
+ self.n_speakers = n_speakers
407
+ self.gin_channels = gin_channels
408
+
409
+ self.use_sdp = use_sdp
410
+
411
+ self.enc_p = TextEncoder(n_vocab,
412
+ inter_channels,
413
+ hidden_channels,
414
+ filter_channels,
415
+ n_heads,
416
+ n_layers,
417
+ kernel_size,
418
+ p_dropout)
419
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
420
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
421
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
422
+
423
+ self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
424
+
425
+ if n_speakers > 0:
426
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
427
+
428
+ def forward(self, x, x_lengths, sid=None, noise_scale=.667, length_scale=1, noise_scale_w=.8, max_len=None):
429
+ torch.onnx.export(
430
+ self.enc_p,
431
+ (x, x_lengths),
432
+ "ONNX_net/enc_p.onnx",
433
+ input_names=["x", "x_lengths"],
434
+ output_names=["xout", "m_p", "logs_p", "x_mask"],
435
+ dynamic_axes={
436
+ "x" : [1],
437
+ "xout" : [2],
438
+ "m_p" : [2],
439
+ "logs_p" : [2],
440
+ "x_mask" : [2]
441
+ },
442
+ verbose=True,
443
+ )
444
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
445
+
446
+ if self.n_speakers > 0:
447
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
448
+ else:
449
+ g = None
450
+
451
+ self.dp.reverse = True
452
+ self.dp.noise_scale = noise_scale_w
453
+ torch.onnx.export(
454
+ self.dp,
455
+ (x, x_mask, g),
456
+ "ONNX_net/dp.onnx",
457
+ input_names=["x", "x_mask", "g"],
458
+ output_names=["logw"],
459
+ dynamic_axes={
460
+ "x" : [2],
461
+ "x_mask" : [2],
462
+ "logw" : [2]
463
+ },
464
+ verbose=True,
465
+ )
466
+ logw = self.dp(x, x_mask, g=g)
467
+ w = torch.exp(logw) * x_mask * length_scale
468
+ w_ceil = torch.ceil(w)
469
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
470
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
471
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
472
+ attn = commons.generate_path(w_ceil, attn_mask)
473
+
474
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
475
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
476
+
477
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
478
+
479
+ self.flow.reverse = True
480
+ torch.onnx.export(
481
+ self.flow,
482
+ (z_p, y_mask, g),
483
+ "ONNX_net/flow.onnx",
484
+ input_names=["z_p", "y_mask", "g"],
485
+ output_names=["z"],
486
+ dynamic_axes={
487
+ "z_p" : [2],
488
+ "y_mask" : [2],
489
+ "z" : [2]
490
+ },
491
+ verbose=True,
492
+ )
493
+ z = self.flow(z_p, y_mask, g=g)
494
+ z_in = (z * y_mask)[:,:,:max_len]
495
+
496
+ torch.onnx.export(
497
+ self.dec,
498
+ (z_in, g),
499
+ "ONNX_net/dec.onnx",
500
+ input_names=["z_in", "g"],
501
+ output_names=["o"],
502
+ dynamic_axes={
503
+ "z_in" : [2],
504
+ "o" : [2]
505
+ },
506
+ verbose=True,
507
+ )
508
+ o = self.dec(z_in, g=g)
509
+ return o
ONNXVITS_modules.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import scipy
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
10
+ from torch.nn.utils import weight_norm, remove_weight_norm
11
+
12
+ import commons
13
+ from commons import init_weights, get_padding
14
+ from ONNXVITS_transforms import piecewise_rational_quadratic_transform
15
+
16
+
17
+ LRELU_SLOPE = 0.1
18
+
19
+
20
+ class LayerNorm(nn.Module):
21
+ def __init__(self, channels, eps=1e-5):
22
+ super().__init__()
23
+ self.channels = channels
24
+ self.eps = eps
25
+
26
+ self.gamma = nn.Parameter(torch.ones(channels))
27
+ self.beta = nn.Parameter(torch.zeros(channels))
28
+
29
+ def forward(self, x):
30
+ x = x.transpose(1, -1)
31
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
32
+ return x.transpose(1, -1)
33
+
34
+
35
+ class ConvReluNorm(nn.Module):
36
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
37
+ super().__init__()
38
+ self.in_channels = in_channels
39
+ self.hidden_channels = hidden_channels
40
+ self.out_channels = out_channels
41
+ self.kernel_size = kernel_size
42
+ self.n_layers = n_layers
43
+ self.p_dropout = p_dropout
44
+ assert n_layers > 1, "Number of layers should be larger than 0."
45
+
46
+ self.conv_layers = nn.ModuleList()
47
+ self.norm_layers = nn.ModuleList()
48
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
49
+ self.norm_layers.append(LayerNorm(hidden_channels))
50
+ self.relu_drop = nn.Sequential(
51
+ nn.ReLU(),
52
+ nn.Dropout(p_dropout))
53
+ for _ in range(n_layers-1):
54
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
55
+ self.norm_layers.append(LayerNorm(hidden_channels))
56
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
57
+ self.proj.weight.data.zero_()
58
+ self.proj.bias.data.zero_()
59
+
60
+ def forward(self, x, x_mask):
61
+ x_org = x
62
+ for i in range(self.n_layers):
63
+ x = self.conv_layers[i](x * x_mask)
64
+ x = self.norm_layers[i](x)
65
+ x = self.relu_drop(x)
66
+ x = x_org + self.proj(x)
67
+ return x * x_mask
68
+
69
+
70
+ class DDSConv(nn.Module):
71
+ """
72
+ Dialted and Depth-Separable Convolution
73
+ """
74
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
75
+ super().__init__()
76
+ self.channels = channels
77
+ self.kernel_size = kernel_size
78
+ self.n_layers = n_layers
79
+ self.p_dropout = p_dropout
80
+
81
+ self.drop = nn.Dropout(p_dropout)
82
+ self.convs_sep = nn.ModuleList()
83
+ self.convs_1x1 = nn.ModuleList()
84
+ self.norms_1 = nn.ModuleList()
85
+ self.norms_2 = nn.ModuleList()
86
+ for i in range(n_layers):
87
+ dilation = kernel_size ** i
88
+ padding = (kernel_size * dilation - dilation) // 2
89
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
90
+ groups=channels, dilation=dilation, padding=padding
91
+ ))
92
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
93
+ self.norms_1.append(LayerNorm(channels))
94
+ self.norms_2.append(LayerNorm(channels))
95
+
96
+ def forward(self, x, x_mask, g=None):
97
+ if g is not None:
98
+ x = x + g
99
+ for i in range(self.n_layers):
100
+ y = self.convs_sep[i](x * x_mask)
101
+ y = self.norms_1[i](y)
102
+ y = F.gelu(y)
103
+ y = self.convs_1x1[i](y)
104
+ y = self.norms_2[i](y)
105
+ y = F.gelu(y)
106
+ y = self.drop(y)
107
+ x = x + y
108
+ return x * x_mask
109
+
110
+
111
+ class WN(torch.nn.Module):
112
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
113
+ super(WN, self).__init__()
114
+ assert(kernel_size % 2 == 1)
115
+ self.hidden_channels =hidden_channels
116
+ self.kernel_size = kernel_size,
117
+ self.dilation_rate = dilation_rate
118
+ self.n_layers = n_layers
119
+ self.gin_channels = gin_channels
120
+ self.p_dropout = p_dropout
121
+
122
+ self.in_layers = torch.nn.ModuleList()
123
+ self.res_skip_layers = torch.nn.ModuleList()
124
+ self.drop = nn.Dropout(p_dropout)
125
+
126
+ if gin_channels != 0:
127
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
128
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
129
+
130
+ for i in range(n_layers):
131
+ dilation = dilation_rate ** i
132
+ padding = int((kernel_size * dilation - dilation) / 2)
133
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
134
+ dilation=dilation, padding=padding)
135
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
136
+ self.in_layers.append(in_layer)
137
+
138
+ # last one is not necessary
139
+ if i < n_layers - 1:
140
+ res_skip_channels = 2 * hidden_channels
141
+ else:
142
+ res_skip_channels = hidden_channels
143
+
144
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
145
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
146
+ self.res_skip_layers.append(res_skip_layer)
147
+
148
+ def forward(self, x, x_mask, g=None, **kwargs):
149
+ output = torch.zeros_like(x)
150
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
151
+
152
+ if g is not None:
153
+ g = self.cond_layer(g)
154
+
155
+ for i in range(self.n_layers):
156
+ x_in = self.in_layers[i](x)
157
+ if g is not None:
158
+ cond_offset = i * 2 * self.hidden_channels
159
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
160
+ else:
161
+ g_l = torch.zeros_like(x_in)
162
+
163
+ acts = commons.fused_add_tanh_sigmoid_multiply(
164
+ x_in,
165
+ g_l,
166
+ n_channels_tensor)
167
+ acts = self.drop(acts)
168
+
169
+ res_skip_acts = self.res_skip_layers[i](acts)
170
+ if i < self.n_layers - 1:
171
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
172
+ x = (x + res_acts) * x_mask
173
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
174
+ else:
175
+ output = output + res_skip_acts
176
+ return output * x_mask
177
+
178
+ def remove_weight_norm(self):
179
+ if self.gin_channels != 0:
180
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
181
+ for l in self.in_layers:
182
+ torch.nn.utils.remove_weight_norm(l)
183
+ for l in self.res_skip_layers:
184
+ torch.nn.utils.remove_weight_norm(l)
185
+
186
+
187
+ class ResBlock1(torch.nn.Module):
188
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
189
+ super(ResBlock1, self).__init__()
190
+ self.convs1 = nn.ModuleList([
191
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
192
+ padding=get_padding(kernel_size, dilation[0]))),
193
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
194
+ padding=get_padding(kernel_size, dilation[1]))),
195
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
196
+ padding=get_padding(kernel_size, dilation[2])))
197
+ ])
198
+ self.convs1.apply(init_weights)
199
+
200
+ self.convs2 = nn.ModuleList([
201
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
202
+ padding=get_padding(kernel_size, 1))),
203
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
204
+ padding=get_padding(kernel_size, 1))),
205
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
206
+ padding=get_padding(kernel_size, 1)))
207
+ ])
208
+ self.convs2.apply(init_weights)
209
+
210
+ def forward(self, x, x_mask=None):
211
+ for c1, c2 in zip(self.convs1, self.convs2):
212
+ xt = F.leaky_relu(x, LRELU_SLOPE)
213
+ if x_mask is not None:
214
+ xt = xt * x_mask
215
+ xt = c1(xt)
216
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
217
+ if x_mask is not None:
218
+ xt = xt * x_mask
219
+ xt = c2(xt)
220
+ x = xt + x
221
+ if x_mask is not None:
222
+ x = x * x_mask
223
+ return x
224
+
225
+ def remove_weight_norm(self):
226
+ for l in self.convs1:
227
+ remove_weight_norm(l)
228
+ for l in self.convs2:
229
+ remove_weight_norm(l)
230
+
231
+
232
+ class ResBlock2(torch.nn.Module):
233
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
234
+ super(ResBlock2, self).__init__()
235
+ self.convs = nn.ModuleList([
236
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
237
+ padding=get_padding(kernel_size, dilation[0]))),
238
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
239
+ padding=get_padding(kernel_size, dilation[1])))
240
+ ])
241
+ self.convs.apply(init_weights)
242
+
243
+ def forward(self, x, x_mask=None):
244
+ for c in self.convs:
245
+ xt = F.leaky_relu(x, LRELU_SLOPE)
246
+ if x_mask is not None:
247
+ xt = xt * x_mask
248
+ xt = c(xt)
249
+ x = xt + x
250
+ if x_mask is not None:
251
+ x = x * x_mask
252
+ return x
253
+
254
+ def remove_weight_norm(self):
255
+ for l in self.convs:
256
+ remove_weight_norm(l)
257
+
258
+
259
+ class Log(nn.Module):
260
+ def forward(self, x, x_mask, reverse=False, **kwargs):
261
+ if not reverse:
262
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
263
+ logdet = torch.sum(-y, [1, 2])
264
+ return y, logdet
265
+ else:
266
+ x = torch.exp(x) * x_mask
267
+ return x
268
+
269
+
270
+ class Flip(nn.Module):
271
+ def forward(self, x, *args, reverse=False, **kwargs):
272
+ x = torch.flip(x, [1])
273
+ if not reverse:
274
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
275
+ return x, logdet
276
+ else:
277
+ return x
278
+
279
+
280
+ class ElementwiseAffine(nn.Module):
281
+ def __init__(self, channels):
282
+ super().__init__()
283
+ self.channels = channels
284
+ self.m = nn.Parameter(torch.zeros(channels,1))
285
+ self.logs = nn.Parameter(torch.zeros(channels,1))
286
+
287
+ def forward(self, x, x_mask, reverse=False, **kwargs):
288
+ if not reverse:
289
+ y = self.m + torch.exp(self.logs) * x
290
+ y = y * x_mask
291
+ logdet = torch.sum(self.logs * x_mask, [1,2])
292
+ return y, logdet
293
+ else:
294
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
295
+ return x
296
+
297
+
298
+ class ResidualCouplingLayer(nn.Module):
299
+ def __init__(self,
300
+ channels,
301
+ hidden_channels,
302
+ kernel_size,
303
+ dilation_rate,
304
+ n_layers,
305
+ p_dropout=0,
306
+ gin_channels=0,
307
+ mean_only=False):
308
+ assert channels % 2 == 0, "channels should be divisible by 2"
309
+ super().__init__()
310
+ self.channels = channels
311
+ self.hidden_channels = hidden_channels
312
+ self.kernel_size = kernel_size
313
+ self.dilation_rate = dilation_rate
314
+ self.n_layers = n_layers
315
+ self.half_channels = channels // 2
316
+ self.mean_only = mean_only
317
+
318
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
319
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
320
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
321
+ self.post.weight.data.zero_()
322
+ self.post.bias.data.zero_()
323
+
324
+ def forward(self, x, x_mask, g=None, reverse=False):
325
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
326
+ h = self.pre(x0) * x_mask
327
+ h = self.enc(h, x_mask, g=g)
328
+ stats = self.post(h) * x_mask
329
+ if not self.mean_only:
330
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
331
+ else:
332
+ m = stats
333
+ logs = torch.zeros_like(m)
334
+
335
+ if not reverse:
336
+ x1 = m + x1 * torch.exp(logs) * x_mask
337
+ x = torch.cat([x0, x1], 1)
338
+ logdet = torch.sum(logs, [1,2])
339
+ return x, logdet
340
+ else:
341
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
342
+ x = torch.cat([x0, x1], 1)
343
+ return x
344
+
345
+
346
+ class ConvFlow(nn.Module):
347
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
348
+ super().__init__()
349
+ self.in_channels = in_channels
350
+ self.filter_channels = filter_channels
351
+ self.kernel_size = kernel_size
352
+ self.n_layers = n_layers
353
+ self.num_bins = num_bins
354
+ self.tail_bound = tail_bound
355
+ self.half_channels = in_channels // 2
356
+
357
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
358
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
359
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
360
+ self.proj.weight.data.zero_()
361
+ self.proj.bias.data.zero_()
362
+
363
+ def forward(self, x, x_mask, g=None, reverse=False):
364
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
365
+ h = self.pre(x0)
366
+ h = self.convs(h, x_mask, g=g)
367
+ h = self.proj(h) * x_mask
368
+
369
+ b, c, t = x0.shape
370
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
371
+
372
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
373
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
374
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
375
+
376
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
377
+ unnormalized_widths,
378
+ unnormalized_heights,
379
+ unnormalized_derivatives,
380
+ inverse=reverse,
381
+ tails='linear',
382
+ tail_bound=self.tail_bound
383
+ )
384
+
385
+ x = torch.cat([x0, x1], 1) * x_mask
386
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
387
+ if not reverse:
388
+ return x, logdet
389
+ else:
390
+ return x
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)
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
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
ONNX_net/dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f5b6cd61faabd9606d85dccf5a2b9720a95fc0d9f4a93c80b5be43764816a81
3
+ size 58183684
ONNX_net/dp.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06fd386f4d2c75fb54d0092db4fa35b64bc22741c1a9e5431fb99b24fa067fcd
3
+ size 7387023
ONNX_net/enc_p.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:270154c4d7d8f1a16480990cf08085526d39818aabd94bf5204efe7e9c5615d1
3
+ size 28510879
ONNX_net/flow.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10ec205d80f5dfbfe5ed8ef3a8aa4ffbe126b7e8fcf05e1eb64d73793aeec011
3
+ size 35707325
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Umamusume-VITS-TTS
3
+ emoji: 🐴
4
+ colorFrom: green
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 3.7
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: Plachta/VITS-Umamusume-voice-synthesizer
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import re
5
+ import tempfile
6
+ import logging
7
+ logging.getLogger('numba').setLevel(logging.WARNING)
8
+ import ONNXVITS_infer
9
+ import librosa
10
+ import numpy as np
11
+ import torch
12
+ from torch import no_grad, LongTensor
13
+ import commons
14
+ import utils
15
+ import gradio as gr
16
+ import gradio.utils as gr_utils
17
+ import gradio.processing_utils as gr_processing_utils
18
+ from models import SynthesizerTrn
19
+ from text import text_to_sequence, _clean_text
20
+ from text.symbols import symbols
21
+ from mel_processing import spectrogram_torch
22
+ import translators.server as tss
23
+ import psutil
24
+ from datetime import datetime
25
+ from text.cleaners import japanese_cleaners
26
+
27
+ def audio_postprocess(self, y):
28
+ if y is None:
29
+ return None
30
+
31
+ if gr_utils.validate_url(y):
32
+ file = gr_processing_utils.download_to_file(y, dir=self.temp_dir)
33
+ elif isinstance(y, tuple):
34
+ sample_rate, data = y
35
+ file = tempfile.NamedTemporaryFile(
36
+ suffix=".wav", dir=self.temp_dir, delete=False
37
+ )
38
+ gr_processing_utils.audio_to_file(sample_rate, data, file.name)
39
+ else:
40
+ file = gr_processing_utils.create_tmp_copy_of_file(y, dir=self.temp_dir)
41
+
42
+ return gr_processing_utils.encode_url_or_file_to_base64(file.name)
43
+
44
+
45
+ gr.Audio.postprocess = audio_postprocess
46
+
47
+ limitation = os.getenv("SYSTEM") == "spaces" # limit text and audio length in huggingface spaces
48
+ languages = ['日本語', '简体中文', 'English']
49
+ characters = ['0:特别周', '1:无声铃鹿', '2:东海帝王', '3:丸善斯基',
50
+ '4:富士奇迹', '5:小栗帽', '6:黄金船', '7:伏特加',
51
+ '8:大和赤骥', '9:大树快车', '10:草上飞', '11:菱亚马逊',
52
+ '12:目白麦昆', '13:神鹰', '14:好歌剧', '15:成田白仁',
53
+ '16:鲁道夫象征', '17:气槽', '18:爱丽数码', '19:青云天空',
54
+ '20:玉藻十字', '21:美妙姿势', '22:琵琶晨光', '23:重炮',
55
+ '24:曼城茶座', '25:美普波旁', '26:目白雷恩', '27:菱曙',
56
+ '28:雪之美人', '29:米浴', '30:艾尼斯风神', '31:爱丽速子',
57
+ '32:爱慕织姬', '33:稻荷一', '34:胜利奖券', '35:空中神宫',
58
+ '36:荣进闪耀', '37:真机伶', '38:川上公主', '39:黄金城市',
59
+ '40:樱花进王', '41:采珠', '42:新光风', '43:东商变革',
60
+ '44:超级小溪', '45:醒目飞鹰', '46:荒漠英雄', '47:东瀛佐敦',
61
+ '48:中山庆典', '49:成田大进', '50:西野花', '51:春乌拉拉',
62
+ '52:青竹回忆', '53:微光飞驹', '54:美丽周日', '55:待兼福来',
63
+ '56:Mr.C.B', '57:名将怒涛', '58:目白多伯', '59:优秀素质',
64
+ '60:帝王光环', '61:待兼诗歌剧', '62:生野狄杜斯', '63:目白善信',
65
+ '64:大拓太阳神', '65:双涡轮', '66:里见光钻', '67:北部玄驹',
66
+ '68:樱花千代王', '69:天狼星象征', '70:目白阿尔丹', '71:八重无敌',
67
+ '72:鹤丸刚志', '73:目白光明', '74:樱花桂冠', '75:成田路',
68
+ '76:也文摄辉', '77:吉兆', '78:谷野美酒', '79:第一红宝石',
69
+ '80:真弓快车', '81:骏川手纲', '82:凯斯奇迹', '83:小林历奇',
70
+ '84:北港火山', '85:奇锐骏', '86:秋川理事长']
71
+ def show_memory_info(hint):
72
+ pid = os.getpid()
73
+ p = psutil.Process(pid)
74
+ info = p.memory_info()
75
+ memory = info.rss / 1024.0 / 1024
76
+ print("{} 内存占用: {} MB".format(hint, memory))
77
+
78
+ def text_to_phoneme(text, symbols, is_symbol):
79
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
80
+
81
+ sequence = ""
82
+ if not is_symbol:
83
+ clean_text = japanese_cleaners(text)
84
+ else:
85
+ clean_text = text
86
+ for symbol in clean_text:
87
+ if symbol not in _symbol_to_id.keys():
88
+ continue
89
+ symbol_id = _symbol_to_id[symbol]
90
+ sequence += symbol
91
+ return sequence
92
+
93
+ def get_text(text, hps, is_symbol):
94
+ text_norm = text_to_sequence(text, hps.symbols, [] if is_symbol else hps.data.text_cleaners)
95
+ if hps.data.add_blank:
96
+ text_norm = commons.intersperse(text_norm, 0)
97
+ text_norm = LongTensor(text_norm)
98
+ return text_norm
99
+
100
+ hps = utils.get_hparams_from_file("./configs/uma87.json")
101
+ symbols = hps.symbols
102
+ net_g = ONNXVITS_infer.SynthesizerTrn(
103
+ len(hps.symbols),
104
+ hps.data.filter_length // 2 + 1,
105
+ hps.train.segment_size // hps.data.hop_length,
106
+ n_speakers=hps.data.n_speakers,
107
+ **hps.model)
108
+ _ = net_g.eval()
109
+
110
+ _ = utils.load_checkpoint("pretrained_models/G_1153000.pth", net_g)
111
+
112
+ def to_symbol_fn(is_symbol_input, input_text, temp_text):
113
+ return (_clean_text(input_text, hps.data.text_cleaners), input_text) if is_symbol_input \
114
+ else (temp_text, temp_text)
115
+
116
+ def infer(text_raw, character, language, duration, noise_scale, noise_scale_w, is_symbol):
117
+ # check character & duraction parameter
118
+ if language not in languages:
119
+ print("Error: No such language\n")
120
+ return "Error: No such language", None, None, None
121
+ if character not in characters:
122
+ print("Error: No such character\n")
123
+ return "Error: No such character", None, None, None
124
+ # check text length
125
+ if limitation:
126
+ text_len = len(text_raw) if is_symbol else len(re.sub("\[([A-Z]{2})\]", "", text_raw))
127
+ max_len = 150
128
+ if is_symbol:
129
+ max_len *= 3
130
+ if text_len > max_len:
131
+ print(f"Refused: Text too long ({text_len}).")
132
+ return "Error: Text is too long", None, None, None
133
+ if text_len == 0:
134
+ print("Refused: Text length is zero.")
135
+ return "Error: Please input text!", None, None, None
136
+ if is_symbol:
137
+ text = text_raw
138
+ elif language == '日本語':
139
+ text = text_raw
140
+ elif language == '简体中文':
141
+ text = tss.google(text_raw, from_language='zh', to_language='ja')
142
+ elif language == 'English':
143
+ text = tss.google(text_raw, from_language='en', to_language='ja')
144
+ char_id = int(character.split(':')[0])
145
+ stn_tst = get_text(text, hps, is_symbol)
146
+ with torch.no_grad():
147
+ x_tst = stn_tst.unsqueeze(0)
148
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)])
149
+ sid = torch.LongTensor([char_id])
150
+ try:
151
+ jp2phoneme = text_to_phoneme(text, hps.symbols, is_symbol)
152
+ durations = net_g.predict_duration(x_tst, x_tst_lengths, sid=sid, noise_scale=noise_scale,
153
+ noise_scale_w=noise_scale_w, length_scale=duration)
154
+ char_dur_list = []
155
+ for i, char in enumerate(jp2phoneme):
156
+ char_pos = i * 2 + 1
157
+ char_dur = durations[char_pos]
158
+ char_dur_list.append(char_dur)
159
+ except IndexError:
160
+ print("Refused: Phoneme input contains non-phoneme character.")
161
+ return "Error: You can only input phoneme under phoneme input model", None, None, None
162
+ char_spacing_dur_list = []
163
+ char_spacings = []
164
+ for i in range(len(durations)):
165
+ if i % 2 == 0: # spacing
166
+ char_spacings.append("spacing")
167
+ elif i % 2 == 1: # char
168
+ char_spacings.append(jp2phoneme[int((i - 1) / 2)])
169
+ char_spacing_dur_list.append(int(durations[i]))
170
+ # convert duration information to string
171
+ duration_info_str = ""
172
+ for i in range(len(char_spacings)):
173
+ if i == len(char_spacings) - 1:
174
+ duration_info_str += "(" + str(char_spacing_dur_list[i]) + ")"
175
+ elif char_spacings[i] == "spacing":
176
+ duration_info_str += "(" + str(char_spacing_dur_list[i]) + ")" + ", "
177
+ else:
178
+ duration_info_str += char_spacings[i] + ":" + str(char_spacing_dur_list[i])
179
+ audio = net_g.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=duration)[0][0,0].data.float().numpy()
180
+ currentDateAndTime = datetime.now()
181
+ print(f"\nCharacter {character} inference successful: {text}")
182
+ if language != '日本語':
183
+ print(f"translate from {language}: {text_raw}")
184
+ show_memory_info(str(currentDateAndTime) + " infer调用后")
185
+ return (text,(22050, audio), jp2phoneme, duration_info_str)
186
+
187
+ def infer_from_phoneme_dur(duration_info_str, character, duration, noise_scale, noise_scale_w):
188
+ try:
189
+ phonemes = duration_info_str.split(", ")
190
+ recons_durs = []
191
+ recons_phonemes = ""
192
+ for i, item in enumerate(phonemes):
193
+ if i == 0:
194
+ recons_durs.append(int(item.strip("()")))
195
+ else:
196
+ phoneme_n_dur, spacing_dur = item.split("(")
197
+ recons_phonemes += phoneme_n_dur.split(":")[0]
198
+ recons_durs.append(int(phoneme_n_dur.split(":")[1]))
199
+ recons_durs.append(int(spacing_dur.strip(")")))
200
+ except ValueError:
201
+ return ("Error: Format must not be changed!", None)
202
+ except AssertionError:
203
+ return ("Error: Format must not be changed!", None)
204
+ char_id = int(character.split(':')[0])
205
+ stn_tst = get_text(recons_phonemes, hps, is_symbol=True)
206
+ with torch.no_grad():
207
+ x_tst = stn_tst.unsqueeze(0)
208
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)])
209
+ sid = torch.LongTensor([char_id])
210
+ audio = net_g.infer_with_duration(x_tst, x_tst_lengths, w_ceil=recons_durs, sid=sid, noise_scale=noise_scale, noise_scale_w=noise_scale_w,
211
+ length_scale=duration)[0][0, 0].data.cpu().float().numpy()
212
+ print(f"\nCharacter {character} inference successful: {recons_phonemes}, from {duration_info_str}")
213
+ return (recons_phonemes, (22050, audio))
214
+
215
+ download_audio_js = """
216
+ () =>{{
217
+ let root = document.querySelector("body > gradio-app");
218
+ if (root.shadowRoot != null)
219
+ root = root.shadowRoot;
220
+ let audio = root.querySelector("#{audio_id}").querySelector("audio");
221
+ if (audio == undefined)
222
+ return;
223
+ audio = audio.src;
224
+ let oA = document.createElement("a");
225
+ oA.download = Math.floor(Math.random()*100000000)+'.wav';
226
+ oA.href = audio;
227
+ document.body.appendChild(oA);
228
+ oA.click();
229
+ oA.remove();
230
+ }}
231
+ """
232
+
233
+ if __name__ == "__main__":
234
+ parser = argparse.ArgumentParser()
235
+ parser.add_argument("--share", action="store_true", default=False, help="share gradio app")
236
+ args = parser.parse_args()
237
+ app = gr.Blocks()
238
+ with app:
239
+ gr.Markdown("# Umamusume voice synthesizer 赛马娘语音合成器\n\n"
240
+ "![visitor badge](https://visitor-badge.glitch.me/badge?page_id=Plachta.VITS-Umamusume-voice-synthesizer)\n\n"
241
+ "This synthesizer is created based on [VITS](https://arxiv.org/abs/2106.06103) model, trained on voice data extracted from mobile game Umamusume Pretty Derby \n\n"
242
+ "这个合成器是基于VITS文本到语音模型,在从手游《賽馬娘:Pretty Derby》解包的语音数据上训练得到。[Dataset Link](https://huggingface.co/datasets/Plachta/Umamusume-voice-text-pairs/tree/main)\n\n"
243
+ "[introduction video / 模型介绍视频](https://www.bilibili.com/video/BV1T84y1e7p5/?vd_source=6d5c00c796eff1cbbe25f1ae722c2f9f#reply607277701)\n\n"
244
+ "You may duplicate this space or [open in Colab](https://colab.research.google.com/drive/1J2Vm5dczTF99ckyNLXV0K-hQTxLwEaj5?usp=sharing) to run it privately and without any queue.\n\n"
245
+ "您可以复制该空间至私人空间运行或打开[Google Colab](https://colab.research.google.com/drive/1J2Vm5dczTF99ckyNLXV0K-hQTxLwEaj5?usp=sharing)在线运行。\n\n"
246
+ "If you have any suggestions or bug reports, feel free to open discussion in [Community](https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer/discussions).\n\n"
247
+ "若有bug反馈或建议,请在[Community](https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer/discussions)下开启一个新的Discussion。 \n\n"
248
+ "If your input language is not Japanese, it will be translated to Japanese by Google translator, but accuracy is not guaranteed.\n\n"
249
+ "如果您的输入语言不是日语,则会由谷歌翻译自动翻译为日语,但是准确性不能保证。\n\n"
250
+ )
251
+ with gr.Row():
252
+ with gr.Column():
253
+ # We instantiate the Textbox class
254
+ textbox = gr.TextArea(label="Text", placeholder="Type your sentence here (Maximum 150 words)", value="こんにちわ。", elem_id=f"tts-input")
255
+ with gr.Accordion(label="Phoneme Input", open=False):
256
+ temp_text_var = gr.Variable()
257
+ symbol_input = gr.Checkbox(value=False, label="Symbol input")
258
+ symbol_list = gr.Dataset(label="Symbol list", components=[textbox],
259
+ samples=[[x] for x in symbols],
260
+ elem_id=f"symbol-list")
261
+ symbol_list_json = gr.Json(value=symbols, visible=False)
262
+ symbol_input.change(to_symbol_fn,
263
+ [symbol_input, textbox, temp_text_var],
264
+ [textbox, temp_text_var])
265
+ symbol_list.click(None, [symbol_list, symbol_list_json], textbox,
266
+ _js=f"""
267
+ (i, symbols, text) => {{
268
+ let root = document.querySelector("body > gradio-app");
269
+ if (root.shadowRoot != null)
270
+ root = root.shadowRoot;
271
+ let text_input = root.querySelector("#tts-input").querySelector("textarea");
272
+ let startPos = text_input.selectionStart;
273
+ let endPos = text_input.selectionEnd;
274
+ let oldTxt = text_input.value;
275
+ let result = oldTxt.substring(0, startPos) + symbols[i] + oldTxt.substring(endPos);
276
+ text_input.value = result;
277
+ let x = window.scrollX, y = window.scrollY;
278
+ text_input.focus();
279
+ text_input.selectionStart = startPos + symbols[i].length;
280
+ text_input.selectionEnd = startPos + symbols[i].length;
281
+ text_input.blur();
282
+ window.scrollTo(x, y);
283
+
284
+ text = text_input.value;
285
+
286
+ return text;
287
+ }}""")
288
+ # select character
289
+ char_dropdown = gr.Dropdown(choices=characters, value = "0:特别周", label='character')
290
+ language_dropdown = gr.Dropdown(choices=languages, value = "日本語", label='language')
291
+
292
+
293
+ duration_slider = gr.Slider(minimum=0.1, maximum=5, value=1, step=0.1, label='时长 Duration')
294
+ noise_scale_slider = gr.Slider(minimum=0.1, maximum=5, value=0.667, step=0.001, label='噪声比例 noise_scale')
295
+ noise_scale_w_slider = gr.Slider(minimum=0.1, maximum=5, value=0.8, step=0.1, label='噪声偏差 noise_scale_w')
296
+
297
+
298
+
299
+ with gr.Column():
300
+ text_output = gr.Textbox(label="Output Text")
301
+ phoneme_output = gr.Textbox(label="Output Phonemes", interactive=False)
302
+ audio_output = gr.Audio(label="Output Audio", elem_id="tts-audio")
303
+ btn = gr.Button("Generate!")
304
+ cus_dur_gn_btn = gr.Button("Regenerate with custom phoneme durations")
305
+
306
+ download = gr.Button("Download Audio")
307
+ download.click(None, [], [], _js=download_audio_js.format(audio_id="tts-audio"))
308
+ with gr.Accordion(label="Speaking Pace Control", open=True):
309
+
310
+ duration_output = gr.Textbox(label="Duration of each phoneme", placeholder="After you generate a sentence, the detailed information of each phoneme's duration will be presented here.",
311
+ interactive = True)
312
+ gr.Markdown(
313
+ "The number after the : mark represents the length of each phoneme in the generated audio, while the number inside ( ) represents the lenght of spacing between each phoneme and its next phoneme. "
314
+ "You can manually change the numbers to adjust the length of each phoneme, so that speaking pace can be completely controlled. "
315
+ "Note that these numbers should be integers only. \n\n(1 represents a length of 0.01161 seconds)\n\n"
316
+ "音素冒号后的数字代表音素在生成音频中的长度,( )内的数字代表每个音素与下一个音素之间间隔的长度。"
317
+ "您可以手动修改这些数字来控制每个音素以及间隔的长度,从而完全控制合成音频的说话节奏。"
318
+ "注意这些数字只能是整数。 \n\n(1 代表 0.01161 秒的长度)\n\n"
319
+ )
320
+ btn.click(infer, inputs=[textbox, char_dropdown, language_dropdown, duration_slider, noise_scale_slider, noise_scale_w_slider, symbol_input],
321
+ outputs=[text_output, audio_output, phoneme_output, duration_output])
322
+ cus_dur_gn_btn.click(infer_from_phoneme_dur, inputs=[duration_output, char_dropdown, duration_slider, noise_scale_slider, noise_scale_w_slider],
323
+ outputs=[phoneme_output, audio_output])
324
+
325
+ examples = [['haa\u2193......haa\u2193......haa\u2193......haa\u2193......haa\u2193......haa\u2193......haa\u2193......haa\u2193......haa\u2193......haa\u2193......haa\u2193......haa\u2193......', '29:米浴', '日本語', 1, 0.667, 0.8, True],
326
+ ['お疲れ様です,トレーナーさん。', '1:无声铃鹿', '日本語', 1, 0.667, 0.8, False],
327
+ ['張り切っていこう!', '67:北部玄驹', '日本語', 1, 0.667, 0.8, False],
328
+ ['何でこんなに慣れでんのよ,私のほが先に好きだっだのに。', '10:草上飞', '日本語', 1, 0.667, 0.8, False],
329
+ ['授業中に出しだら,学校生活終わるですわ。', '12:目白麦昆', '日本語', 1, 0.667, 0.8, False],
330
+ ['お帰りなさい,お兄様!', '29:米浴', '日本語', 1, 0.667, 0.8, False],
331
+ ['私の処女をもらっでください!', '29:米浴', '日本語', 1, 0.667, 0.8, False]]
332
+ gr.Examples(
333
+ examples=examples,
334
+ inputs=[textbox, char_dropdown, language_dropdown,
335
+ duration_slider, noise_scale_slider,noise_scale_w_slider, symbol_input],
336
+ outputs=[text_output, audio_output],
337
+ fn=infer
338
+ )
339
+ gr.Markdown("# Updates Logs 更新日志:\n\n"
340
+ "2023/1/24:\n\n"
341
+ "Improved the format of phoneme length control.\n\n"
342
+ "改善了音素控制的格式。\n\n"
343
+ "2023/1/24:\n\n"
344
+ "Added more precise control on pace of speaking by modifying the duration of each phoneme.\n\n"
345
+ "增加了对说话节奏的音素级控制。\n\n"
346
+ "2023/1/13:\n\n"
347
+ "Added one example of phoneme input.\n\n"
348
+ "增加了音素输入的example(米浴喘气)\n\n"
349
+ "2023/1/12:\n\n"
350
+ "Added phoneme input, which enables more precise control on output audio.\n\n"
351
+ "增加了音素输入的功能,可以对语气和语调做到一定程度的精细控制。\n\n"
352
+ "Adjusted UI arrangements.\n\n"
353
+ "调整了UI的布局。\n\n"
354
+ "2023/1/10:\n\n"
355
+ "Dataset used for training is now uploaded to [here](https://huggingface.co/datasets/Plachta/Umamusume-voice-text-pairs/tree/main)\n\n"
356
+ "数据集已上传,您���以在[这里](https://huggingface.co/datasets/Plachta/Umamusume-voice-text-pairs/tree/main)下载。\n\n"
357
+ "2023/1/9:\n\n"
358
+ "Model inference has been fully converted to onnxruntime. There will be no more Runtime Error: Memory Limit Exceeded\n\n"
359
+ "模型推理已全面转为onnxruntime,现在不会出现Runtime Error: Memory Limit Exceeded了。\n\n"
360
+ "Now integrated to [Moe-tts](https://huggingface.co/spaces/skytnt/moe-tts) collection.\n\n"
361
+ "现已加入[Moe-tts](https://huggingface.co/spaces/skytnt/moe-tts)模型大全。\n\n"
362
+ )
363
+ app.queue(concurrency_count=3).launch(show_api=False, share=args.share)
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
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
configs/uma87.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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",
54
+ "Silence Suzuka",
55
+ "Tokai Teio",
56
+ "Maruzensky",
57
+ "Fuji Kiseki",
58
+ "Oguri Cap",
59
+ "Gold Ship",
60
+ "Vodka",
61
+ "Daiwa Scarlet",
62
+ "Taiki Shuttle",
63
+ "Grass Wonder",
64
+ "Hishi Amazon",
65
+ "Mejiro Mcqueen",
66
+ "El Condor Pasa",
67
+ "T.M. Opera O",
68
+ "Narita Brian",
69
+ "Symboli Rudolf",
70
+ "Air Groove",
71
+ "Agnes Digital",
72
+ "Seiun Sky",
73
+ "Tamamo Cross",
74
+ "Fine Motion",
75
+ "Biwa Hayahide",
76
+ "Mayano Topgun",
77
+ "Manhattan Cafe",
78
+ "Mihono Bourbon",
79
+ "Mejiro Ryan",
80
+ "Hishi Akebono",
81
+ "Yukino Bijin",
82
+ "Rice Shower",
83
+ "Ines Fujin",
84
+ "Agnes Tachyon",
85
+ "Admire Vega",
86
+ "Inari One",
87
+ "Winning Ticket",
88
+ "Air Shakur",
89
+ "Eishin Flash",
90
+ "Curren Chan",
91
+ "Kawakami Princess",
92
+ "Gold City",
93
+ "Sakura Bakushin O",
94
+ "Seeking the Pearl",
95
+ "Shinko Windy",
96
+ "Sweep Tosho",
97
+ "Super Creek",
98
+ "Smart Falcon",
99
+ "Zenno Rob Roy",
100
+ "Tosen Jordan",
101
+ "Nakayama Festa",
102
+ "Narita Taishin",
103
+ "Nishino Flower",
104
+ "Haru Urara",
105
+ "Bamboo Memory",
106
+ "Biko Pegasus",
107
+ "Marvelous Sunday",
108
+ "Matikane Fukukitaru",
109
+ "Mr. C.B.",
110
+ "Meisho Doto",
111
+ "Mejiro Dober",
112
+ "Nice Nature",
113
+ "King Halo",
114
+ "Matikane Tannhauser",
115
+ "Ikuno Dictus",
116
+ "Mejiro Palmer",
117
+ "Daitaku Helios",
118
+ "Twin Turbo",
119
+ "Satono Diamond",
120
+ "Kitasan Black",
121
+ "Sakura Chiyono O",
122
+ "Sirius Symboli",
123
+ "Mejiro Ardan",
124
+ "Yaeno Muteki",
125
+ "Tsurumaru Tsuyoshi",
126
+ "Mejiro Bright",
127
+ "Sakura Laurel",
128
+ "Narita Top Road",
129
+ "Yamanin Zephyr",
130
+ "Symboli Kris S",
131
+ "Tanino Gimlet",
132
+ "Daiichi Ruby",
133
+ "Aston Machan",
134
+ "Hayakawa Tazuna",
135
+ "KS Miracle",
136
+ "Kopano Rickey",
137
+ "Hoko Tarumae",
138
+ "Wonder Acute",
139
+ "President Akikawa"
140
+ ],
141
+ "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", " "]
142
+ }
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
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
jieba/dict.txt ADDED
The diff for this file is too large to render. See raw diff
 
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
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
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
+
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
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)
monotonic_align/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (765 Bytes). View file
 
monotonic_align/build/lib.win-amd64-cpython-37/monotonic_align/core.cp37-win_amd64.pyd ADDED
Binary file (120 kB). View file
 
monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.exp ADDED
Binary file (697 Bytes). View file
 
monotonic_align/build/temp.win-amd64-cpython-37/Release/core.cp37-win_amd64.lib ADDED
Binary file (1.94 kB). View file
 
monotonic_align/build/temp.win-amd64-cpython-37/Release/core.obj ADDED
Binary file (848 kB). View file
 
monotonic_align/core.c ADDED
The diff for this file is too large to render. See raw diff
 
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])
monotonic_align/monotonic_align/core.cp37-win_amd64.pyd ADDED
Binary file (120 kB). View file
 
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
+ )
pretrained_models/G_1153000.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8330f5b07b416844eee6446b6095cd8fadd996b19e0c3a0bd19846c2e646e87c
3
+ size 477053701
pretrained_models/uma87_817000.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad4ecf9786ab14385dbd5d223d13338228e3b17411ceaede4488705ee12e3ba4
3
+ size 477050267
requirements.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numba
2
+ librosa
3
+ matplotlib
4
+ numpy
5
+ phonemizer
6
+ scipy
7
+ tensorboard
8
+ torch
9
+ torchvision
10
+ torchaudio
11
+ unidecode
12
+ pyopenjtalk
13
+ jamo
14
+ pypinyin
15
+ protobuf
16
+ inflect
17
+ opencc
18
+ onnx
19
+ onnxruntime
20
+ psutil
21
+ translators
22
+ gradio
text/LICENSE 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.
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
text/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (1.19 kB). View file
 
text/__pycache__/cleaners.cpython-37.pyc ADDED
Binary file (7.74 kB). View file
 
text/__pycache__/english.cpython-37.pyc ADDED
Binary file (4.93 kB). View file
 
text/__pycache__/japanese.cpython-37.pyc ADDED
Binary file (4.61 kB). View file
 
text/__pycache__/korean.cpython-37.pyc ADDED
Binary file (5.75 kB). View file
 
text/__pycache__/mandarin.cpython-37.pyc ADDED
Binary file (7.51 kB). View file
 
text/__pycache__/sanskrit.cpython-37.pyc ADDED
Binary file (1.63 kB). View file
 
text/__pycache__/symbols.cpython-37.pyc ADDED
Binary file (357 Bytes). View file
 
text/__pycache__/thai.cpython-37.pyc ADDED
Binary file (1.41 kB). View file
 
text/cantonese.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import cn2an
3
+ import opencc
4
+
5
+
6
+ converter = opencc.OpenCC('jyutjyu')
7
+
8
+ # List of (Latin alphabet, ipa) pairs:
9
+ _latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
10
+ ('A', 'ei˥'),
11
+ ('B', 'biː˥'),
12
+ ('C', 'siː˥'),
13
+ ('D', 'tiː˥'),
14
+ ('E', 'iː˥'),
15
+ ('F', 'e˥fuː˨˩'),
16
+ ('G', 'tsiː˥'),
17
+ ('H', 'ɪk̚˥tsʰyː˨˩'),
18
+ ('I', 'ɐi˥'),
19
+ ('J', 'tsei˥'),
20
+ ('K', 'kʰei˥'),
21
+ ('L', 'e˥llou˨˩'),
22
+ ('M', 'ɛːm˥'),
23
+ ('N', 'ɛːn˥'),
24
+ ('O', 'ou˥'),
25
+ ('P', 'pʰiː˥'),
26
+ ('Q', 'kʰiːu˥'),
27
+ ('R', 'aː˥lou˨˩'),
28
+ ('S', 'ɛː˥siː˨˩'),
29
+ ('T', 'tʰiː˥'),
30
+ ('U', 'juː˥'),
31
+ ('V', 'wiː˥'),
32
+ ('W', 'tʊk̚˥piː˥juː˥'),
33
+ ('X', 'ɪk̚˥siː˨˩'),
34
+ ('Y', 'waːi˥'),
35
+ ('Z', 'iː˨sɛːt̚˥')
36
+ ]]
37
+
38
+
39
+ def number_to_cantonese(text):
40
+ return re.sub(r'\d+(?:\.?\d+)?', lambda x: cn2an.an2cn(x.group()), text)
41
+
42
+
43
+ def latin_to_ipa(text):
44
+ for regex, replacement in _latin_to_ipa:
45
+ text = re.sub(regex, replacement, text)
46
+ return text
47
+
48
+
49
+ def cantonese_to_ipa(text):
50
+ text = number_to_cantonese(text.upper())
51
+ text = converter.convert(text).replace('-','').replace('$',' ')
52
+ text = re.sub(r'[A-Z]', lambda x: latin_to_ipa(x.group())+' ', text)
53
+ text = re.sub(r'[、;:]', ',', text)
54
+ text = re.sub(r'\s*,\s*', ', ', text)
55
+ text = re.sub(r'\s*。\s*', '. ', text)
56
+ text = re.sub(r'\s*?\s*', '? ', text)
57
+ text = re.sub(r'\s*!\s*', '! ', text)
58
+ text = re.sub(r'\s*$', '', text)
59
+ return text
text/cleaners.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+
4
+ def japanese_cleaners(text):
5
+ from text.japanese import japanese_to_romaji_with_accent
6
+ text = japanese_to_romaji_with_accent(text)
7
+ text = re.sub(r'([A-Za-z])$', r'\1.', text)
8
+ return text
9
+
10
+
11
+ def japanese_cleaners2(text):
12
+ return japanese_cleaners(text).replace('ts', 'ʦ').replace('...', '…')
13
+
14
+
15
+ def korean_cleaners(text):
16
+ '''Pipeline for Korean text'''
17
+ from text.korean import latin_to_hangul, number_to_hangul, divide_hangul
18
+ text = latin_to_hangul(text)
19
+ text = number_to_hangul(text)
20
+ text = divide_hangul(text)
21
+ text = re.sub(r'([\u3131-\u3163])$', r'\1.', text)
22
+ return text
23
+
24
+
25
+ def chinese_cleaners(text):
26
+ '''Pipeline for Chinese text'''
27
+ from text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo
28
+ text = number_to_chinese(text)
29
+ text = chinese_to_bopomofo(text)
30
+ text = latin_to_bopomofo(text)
31
+ text = re.sub(r'([ˉˊˇˋ˙])$', r'\1。', text)
32
+ return text
33
+
34
+
35
+ def zh_ja_mixture_cleaners(text):
36
+ from text.mandarin import chinese_to_romaji
37
+ from text.japanese import japanese_to_romaji_with_accent
38
+ text = re.sub(r'\[ZH\](.*?)\[ZH\]',
39
+ lambda x: chinese_to_romaji(x.group(1))+' ', text)
40
+ text = re.sub(r'\[JA\](.*?)\[JA\]', lambda x: japanese_to_romaji_with_accent(
41
+ x.group(1)).replace('ts', 'ʦ').replace('u', 'ɯ').replace('...', '…')+' ', text)
42
+ text = re.sub(r'\s+$', '', text)
43
+ text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
44
+ return text
45
+
46
+
47
+ def sanskrit_cleaners(text):
48
+ text = text.replace('॥', '।').replace('ॐ', 'ओम्')
49
+ if text[-1] != '।':
50
+ text += ' ।'
51
+ return text
52
+
53
+
54
+ def cjks_cleaners(text):
55
+ from text.mandarin import chinese_to_lazy_ipa
56
+ from text.japanese import japanese_to_ipa
57
+ from text.korean import korean_to_lazy_ipa
58
+ from text.sanskrit import devanagari_to_ipa
59
+ from text.english import english_to_lazy_ipa
60
+ text = re.sub(r'\[ZH\](.*?)\[ZH\]',
61
+ lambda x: chinese_to_lazy_ipa(x.group(1))+' ', text)
62
+ text = re.sub(r'\[JA\](.*?)\[JA\]',
63
+ lambda x: japanese_to_ipa(x.group(1))+' ', text)
64
+ text = re.sub(r'\[KO\](.*?)\[KO\]',
65
+ lambda x: korean_to_lazy_ipa(x.group(1))+' ', text)
66
+ text = re.sub(r'\[SA\](.*?)\[SA\]',
67
+ lambda x: devanagari_to_ipa(x.group(1))+' ', text)
68
+ text = re.sub(r'\[EN\](.*?)\[EN\]',
69
+ lambda x: english_to_lazy_ipa(x.group(1))+' ', text)
70
+ text = re.sub(r'\s+$', '', text)
71
+ text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
72
+ return text
73
+
74
+
75
+ def cjke_cleaners(text):
76
+ from text.mandarin import chinese_to_lazy_ipa
77
+ from text.japanese import japanese_to_ipa
78
+ from text.korean import korean_to_ipa
79
+ from text.english import english_to_ipa2
80
+ text = re.sub(r'\[ZH\](.*?)\[ZH\]', lambda x: chinese_to_lazy_ipa(x.group(1)).replace(
81
+ 'ʧ', 'tʃ').replace('ʦ', 'ts').replace('ɥan', 'ɥæn')+' ', text)
82
+ text = re.sub(r'\[JA\](.*?)\[JA\]', lambda x: japanese_to_ipa(x.group(1)).replace('ʧ', 'tʃ').replace(
83
+ 'ʦ', 'ts').replace('ɥan', 'ɥæn').replace('ʥ', 'dz')+' ', text)
84
+ text = re.sub(r'\[KO\](.*?)\[KO\]',
85
+ lambda x: korean_to_ipa(x.group(1))+' ', text)
86
+ text = re.sub(r'\[EN\](.*?)\[EN\]', lambda x: english_to_ipa2(x.group(1)).replace('ɑ', 'a').replace(
87
+ 'ɔ', 'o').replace('ɛ', 'e').replace('ɪ', 'i').replace('ʊ', 'u')+' ', text)
88
+ text = re.sub(r'\s+$', '', text)
89
+ text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
90
+ return text
91
+
92
+
93
+ def cjke_cleaners2(text):
94
+ from text.mandarin import chinese_to_ipa
95
+ from text.japanese import japanese_to_ipa2
96
+ from text.korean import korean_to_ipa
97
+ from text.english import english_to_ipa2
98
+ text = re.sub(r'\[ZH\](.*?)\[ZH\]',
99
+ lambda x: chinese_to_ipa(x.group(1))+' ', text)
100
+ text = re.sub(r'\[JA\](.*?)\[JA\]',
101
+ lambda x: japanese_to_ipa2(x.group(1))+' ', text)
102
+ text = re.sub(r'\[KO\](.*?)\[KO\]',
103
+ lambda x: korean_to_ipa(x.group(1))+' ', text)
104
+ text = re.sub(r'\[EN\](.*?)\[EN\]',
105
+ lambda x: english_to_ipa2(x.group(1))+' ', text)
106
+ text = re.sub(r'\s+$', '', text)
107
+ text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
108
+ return text
109
+
110
+
111
+ def thai_cleaners(text):
112
+ from text.thai import num_to_thai, latin_to_thai
113
+ text = num_to_thai(text)
114
+ text = latin_to_thai(text)
115
+ return text
116
+
117
+
118
+ def shanghainese_cleaners(text):
119
+ from text.shanghainese import shanghainese_to_ipa
120
+ text = shanghainese_to_ipa(text)
121
+ text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
122
+ return text
123
+
124
+
125
+ def chinese_dialect_cleaners(text):
126
+ from text.mandarin import chinese_to_ipa2
127
+ from text.japanese import japanese_to_ipa3
128
+ from text.shanghainese import shanghainese_to_ipa
129
+ from text.cantonese import cantonese_to_ipa
130
+ from text.english import english_to_lazy_ipa2
131
+ from text.ngu_dialect import ngu_dialect_to_ipa
132
+ text = re.sub(r'\[ZH\](.*?)\[ZH\]',
133
+ lambda x: chinese_to_ipa2(x.group(1))+' ', text)
134
+ text = re.sub(r'\[JA\](.*?)\[JA\]',
135
+ lambda x: japanese_to_ipa3(x.group(1)).replace('Q', 'ʔ')+' ', text)
136
+ text = re.sub(r'\[SH\](.*?)\[SH\]', lambda x: shanghainese_to_ipa(x.group(1)).replace('1', '˥˧').replace('5',
137
+ '˧˧˦').replace('6', '˩˩˧').replace('7', '˥').replace('8', '˩˨').replace('ᴀ', 'ɐ').replace('ᴇ', 'e')+' ', text)
138
+ text = re.sub(r'\[GD\](.*?)\[GD\]',
139
+ lambda x: cantonese_to_ipa(x.group(1))+' ', text)
140
+ text = re.sub(r'\[EN\](.*?)\[EN\]',
141
+ lambda x: english_to_lazy_ipa2(x.group(1))+' ', text)
142
+ text = re.sub(r'\[([A-Z]{2})\](.*?)\[\1\]', lambda x: ngu_dialect_to_ipa(x.group(2), x.group(
143
+ 1)).replace('ʣ', 'dz').replace('ʥ', 'dʑ').replace('ʦ', 'ts').replace('ʨ', 'tɕ')+' ', text)
144
+ text = re.sub(r'\s+$', '', text)
145
+ text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text)
146
+ return text