PatnaikAshish commited on
Commit
5bdbe49
·
verified ·
1 Parent(s): ed1d80b

Upload 22 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ logo.png filter=lfs diff=lfs merge=lfs -text
audiobook.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import torch
4
+ import numpy as np
5
+ from scipy.io.wavfile import write
6
+ from tts import commons
7
+ from tts import utils
8
+ from tts.models import SynthesizerTrn
9
+ from text.symbols import symbols
10
+ from text import text_to_sequence
11
+ from phonemizer.backend.espeak.wrapper import EspeakWrapper
12
+ from safetensors.torch import load_file
13
+
14
+ _ESPEAK_LIBRARY = r"C:\Program Files\eSpeak NG\libespeak-ng.dll"
15
+ if os.path.exists(_ESPEAK_LIBRARY):
16
+ EspeakWrapper.set_library(_ESPEAK_LIBRARY)
17
+ print(f"✅ Found eSpeak-ng: {_ESPEAK_LIBRARY}")
18
+ else:
19
+ print("⚠️ eSpeak-ng not found (ok if already working)")
20
+
21
+
22
+ MODEL_PATH = "checkpoints/sonya-tts.safetensors"
23
+ CONFIG_PATH = "checkpoints/config.json"
24
+
25
+ OUTPUT_WAV_SHORT = "output.wav"
26
+ OUTPUT_WAV_LONG = "audiobook.wav"
27
+
28
+ USE_LONG_FORM = True # ← change to False for short text
29
+
30
+ TEXT = """
31
+ You’re 100 percent right. LeetCode solutions should be simple, readable,
32
+ and teachable. This long form inference mode allows narration of long
33
+ paragraphs without instability. The audio remains smooth and natural.
34
+ without breaking audio quality. It works smoothly. The Problem: VITS crashes or creates garbage audio if you feed it a whole paragraph or page of text. The Solution: A script that automatically splits text into sentences, generates audio for each, and stitches them together with natural pauses.
35
+ Why it stands out: It allows you to convert entire PDF chapters or articles into audio files automatically. Since the architectural changes for zero-shot cloning adding embeddings require retraining, let’s focus on inference-side features you can add right now to your existing G_10400.pth model.
36
+ These features will turn your simple "Text-to-WAV" script into a powerful Audiobook & Content Creation Tool.
37
+ """
38
+
39
+ def save_wav_int16(path, audio, sample_rate):
40
+ audio = np.clip(audio, -1.0, 1.0)
41
+ audio = (audio * 32767).astype(np.int16)
42
+ write(path, sample_rate, audio)
43
+
44
+
45
+ def clean_text_for_vits(text):
46
+ text = text.strip()
47
+
48
+
49
+ text = text.replace("’", "'")
50
+ text = text.replace("“", '"').replace("”", '"')
51
+ text = text.replace("–", "-").replace("—", "-")
52
+
53
+
54
+ text = re.sub(r"[()\[\]{}<>]", "", text)
55
+
56
+
57
+ text = re.sub(r"[^a-zA-Z0-9\s.,!?'\-]", "", text)
58
+
59
+ text = re.sub(r"\s+", " ", text)
60
+
61
+ return text
62
+
63
+ def get_text(text, hps):
64
+ text = clean_text_for_vits(text)
65
+ text_norm = text_to_sequence(text, hps.data.text_cleaners)
66
+ if hps.data.add_blank:
67
+ text_norm = commons.intersperse(text_norm, 0)
68
+ return torch.LongTensor(text_norm)
69
+
70
+
71
+ def split_sentences(text):
72
+ text = clean_text_for_vits(text)
73
+ if not text:
74
+ return []
75
+ return re.split(r'(?<=[.!?])\s+', text)
76
+
77
+
78
+ def generate_audiobook(
79
+ net_g,
80
+ hps,
81
+ text,
82
+ device,
83
+ output_file,
84
+ noise_scale=0.5,
85
+ noise_scale_w=0.6,
86
+ length_scale=1.0,
87
+ base_pause=0.4,
88
+ ):
89
+ print("📖 Long-form audiobook mode enabled")
90
+
91
+ sentences = split_sentences(text)
92
+ print(f"🔹 Sentences: {len(sentences)}")
93
+
94
+ audio_chunks = []
95
+
96
+ for i, sent in enumerate(sentences):
97
+ sent = sent.strip()
98
+ if not sent:
99
+ continue
100
+
101
+ stn_tst = get_text(sent, hps)
102
+
103
+ with torch.no_grad():
104
+ x = stn_tst.to(device).unsqueeze(0)
105
+ x_len = torch.LongTensor([stn_tst.size(0)]).to(device)
106
+
107
+ audio = net_g.infer(
108
+ x,
109
+ x_len,
110
+ noise_scale=noise_scale,
111
+ noise_scale_w=noise_scale_w,
112
+ length_scale=length_scale,
113
+ )[0][0, 0].cpu().numpy()
114
+
115
+ if sent.endswith("?"):
116
+ pause = base_pause + 0.15
117
+ elif sent.endswith("!"):
118
+ pause = base_pause
119
+ else:
120
+ pause = base_pause + 0.05
121
+
122
+ silence = np.zeros(int(hps.data.sampling_rate * pause))
123
+
124
+ audio_chunks.append(audio)
125
+ audio_chunks.append(silence)
126
+
127
+ print(f" ✅ Sentence {i+1}/{len(sentences)} done")
128
+
129
+ final_audio = np.concatenate(audio_chunks)
130
+ save_wav_int16(output_file, final_audio, hps.data.sampling_rate)
131
+
132
+ print(f"🎉 Audiobook saved: {os.path.abspath(output_file)}")
133
+
134
+
135
+ def main():
136
+ if not os.path.exists(CONFIG_PATH):
137
+ print("❌ Config file not found")
138
+ return
139
+
140
+ hps = utils.get_hparams_from_file(CONFIG_PATH)
141
+
142
+ device = "cuda" if torch.cuda.is_available() else "cpu"
143
+ print(f"🚀 Using device: {device}")
144
+
145
+ # Load model
146
+ net_g = SynthesizerTrn(
147
+ len(symbols),
148
+ hps.data.filter_length // 2 + 1,
149
+ hps.train.segment_size // hps.data.hop_length,
150
+ **hps.model,
151
+ ).to(device)
152
+ net_g.eval()
153
+
154
+ # Load checkpoint
155
+ state_dict = load_file(MODEL_PATH, device=device)
156
+ net_g.load_state_dict(state_dict)
157
+ print(f"✅ Loaded model: {MODEL_PATH}")
158
+
159
+
160
+ if USE_LONG_FORM:
161
+ generate_audiobook(
162
+ net_g,
163
+ hps,
164
+ TEXT,
165
+ device,
166
+ OUTPUT_WAV_LONG,
167
+ )
168
+ else:
169
+ print("🗣️ Short-text inference")
170
+
171
+ stn_tst = get_text(TEXT, hps)
172
+ with torch.no_grad():
173
+ x = stn_tst.to(device).unsqueeze(0)
174
+ x_len = torch.LongTensor([stn_tst.size(0)]).to(device)
175
+
176
+ audio = net_g.infer(
177
+ x,
178
+ x_len,
179
+ noise_scale=0.5,
180
+ noise_scale_w=0.6,
181
+ length_scale=1.0,
182
+ )[0][0, 0].cpu().numpy()
183
+
184
+ save_wav_int16(OUTPUT_WAV_SHORT, audio, hps.data.sampling_rate)
185
+ print(f"💾 Saved audio: {os.path.abspath(OUTPUT_WAV_SHORT)}")
186
+
187
+ if __name__ == "__main__":
188
+ main()
checkpoints/config.json ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "finetune": true,
4
+ "wandb_resume": true,
5
+ "log_interval": 10,
6
+ "eval_interval": 400,
7
+ "seed": 1234,
8
+ "epochs": 1000,
9
+ "learning_rate": 0.0002,
10
+ "betas": [
11
+ 0.8,
12
+ 0.99
13
+ ],
14
+ "eps": 1e-09,
15
+ "batch_size": 16,
16
+ "fp16_run": true,
17
+ "lr_decay": 0.999875,
18
+ "segment_size": 8192,
19
+ "init_lr_ratio": 1,
20
+ "warmup_epochs": 0,
21
+ "c_mel": 45,
22
+ "c_kl": 1.0
23
+ },
24
+ "data": {
25
+ "name": "optimusPrime",
26
+ "training_files": "resources/elise_data/train.txt.cleaned",
27
+ "validation_files": "resources/elise_data/val.txt.cleaned",
28
+ "text_cleaners": [
29
+ "english_cleaners2"
30
+ ],
31
+ "max_wav_value": 32768.0,
32
+ "sampling_rate": 22050,
33
+ "filter_length": 1024,
34
+ "hop_length": 256,
35
+ "win_length": 1024,
36
+ "n_mel_channels": 80,
37
+ "mel_fmin": 0.0,
38
+ "mel_fmax": null,
39
+ "add_blank": true,
40
+ "n_speakers": 0,
41
+ "cleaned_text": true
42
+ },
43
+ "model": {
44
+ "inter_channels": 192,
45
+ "hidden_channels": 192,
46
+ "filter_channels": 768,
47
+ "n_heads": 2,
48
+ "n_layers": 6,
49
+ "kernel_size": 3,
50
+ "p_dropout": 0.1,
51
+ "resblock": "1",
52
+ "resblock_kernel_sizes": [
53
+ 3,
54
+ 7,
55
+ 11
56
+ ],
57
+ "resblock_dilation_sizes": [
58
+ [
59
+ 1,
60
+ 3,
61
+ 5
62
+ ],
63
+ [
64
+ 1,
65
+ 3,
66
+ 5
67
+ ],
68
+ [
69
+ 1,
70
+ 3,
71
+ 5
72
+ ]
73
+ ],
74
+ "upsample_rates": [
75
+ 8,
76
+ 8,
77
+ 2,
78
+ 2
79
+ ],
80
+ "upsample_initial_channel": 512,
81
+ "upsample_kernel_sizes": [
82
+ 16,
83
+ 16,
84
+ 4,
85
+ 4
86
+ ],
87
+ "n_layers_q": 3,
88
+ "use_spectral_norm": false
89
+ }
90
+ }
checkpoints/sonya-tts.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1099cb7d4f85f972ceb999608e01db6833eaf38867cc97944cd058e9a7484607
3
+ size 145371080
infer.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+ import numpy as np
7
+ from scipy.io.wavfile import write
8
+ from phonemizer.backend.espeak.wrapper import EspeakWrapper
9
+ from safetensors.torch import load_file
10
+ from tts import commons
11
+ from tts import utils
12
+ from tts.models import SynthesizerTrn
13
+
14
+ from text.symbols import symbols
15
+ from text import text_to_sequence
16
+
17
+
18
+ _ESPEAK_LIBRARY = r"C:\Program Files\eSpeak NG\libespeak-ng.dll"
19
+ if os.path.exists(_ESPEAK_LIBRARY):
20
+ EspeakWrapper.set_library(_ESPEAK_LIBRARY)
21
+ print(f"✅ Found eSpeak at: {_ESPEAK_LIBRARY}")
22
+ else:
23
+ print("⚠️ WARNING: eSpeak-ng not found (ok if already working)")
24
+
25
+ # --- CONFIGURATION ---
26
+ MODEL_PATH = "checkpoints/sonya-tts.safetensors"
27
+ CONFIG_PATH = "checkpoints/config.json"
28
+ OUTPUT_WAV = "output.wav"
29
+
30
+ TEXT = "Hello I am Sonya, an expressive Text to Speech model that can run fast in edge devices."
31
+
32
+ # --- CONTROLLABLE INFERENCE PARAMETERS ---
33
+ ns = 0.5 # noise_scale
34
+ nsw = 0.6 # noise_scale_w
35
+ ls = 1.0 # length_scale
36
+
37
+
38
+ def clean_text_for_vits(text):
39
+ text = text.strip()
40
+
41
+ text = text.replace("’", "'")
42
+ text = text.replace("“", '"').replace("”", '"')
43
+ text = text.replace("–", "-").replace("—", "-")
44
+
45
+ text = re.sub(r"[()\[\]{}<>]", "", text)
46
+
47
+ text = re.sub(r"[^a-zA-Z0-9\s.,!?'\-]", "", text)
48
+
49
+ text = re.sub(r"\s+", " ", text)
50
+
51
+ return text
52
+
53
+ def get_text(text, hps):
54
+ text = clean_text_for_vits(text)
55
+ text_norm = text_to_sequence(text, hps.data.text_cleaners)
56
+ if hps.data.add_blank:
57
+ text_norm = commons.intersperse(text_norm, 0)
58
+ return torch.LongTensor(text_norm)
59
+
60
+ def save_wav_int16(path, audio, sample_rate):
61
+ audio = np.clip(audio, -1.0, 1.0)
62
+ audio = (audio * 32767).astype(np.int16)
63
+ write(path, sample_rate, audio)
64
+
65
+ def main():
66
+ # 1. Load Config
67
+ if not os.path.exists(CONFIG_PATH):
68
+ print("❌ Config file not found!")
69
+ return
70
+
71
+ hps = utils.get_hparams_from_file(CONFIG_PATH)
72
+
73
+ # 2. Load Model
74
+ print("🔄 Loading Model...")
75
+ device = "cuda" if torch.cuda.is_available() else "cpu"
76
+ print(f" Using device: {device}")
77
+
78
+ net_g = SynthesizerTrn(
79
+ len(symbols),
80
+ hps.data.filter_length // 2 + 1,
81
+ hps.train.segment_size // hps.data.hop_length,
82
+ **hps.model
83
+ ).to(device)
84
+
85
+ net_g.eval()
86
+
87
+ # 3. Load Checkpoint
88
+ if os.path.exists(MODEL_PATH):
89
+ state_dict = load_file(MODEL_PATH, device=device)
90
+ net_g.load_state_dict(state_dict)
91
+ print(f"✅ Loaded weights from {MODEL_PATH}")
92
+ else:
93
+ print(f"❌ Model file not found at {MODEL_PATH}")
94
+ return
95
+
96
+ # 4. Inference
97
+ print(f"🗣️ Generating: '{TEXT}'")
98
+ stn_tst = get_text(TEXT, hps)
99
+
100
+ with torch.no_grad():
101
+ x_tst = stn_tst.to(device).unsqueeze(0)
102
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(device)
103
+
104
+ audio = net_g.infer(
105
+ x_tst,
106
+ x_tst_lengths,
107
+ noise_scale=0.5,
108
+ noise_scale_w=0.6,
109
+ length_scale=1.0
110
+ )[0][0, 0].cpu().float().numpy()
111
+
112
+ save_wav_int16(OUTPUT_WAV, audio, hps.data.sampling_rate)
113
+ print(f"💾 Saved audio to: {os.path.abspath(OUTPUT_WAV)}")
114
+
115
+ if __name__ == "__main__":
116
+ main()
logo.png ADDED

Git LFS Details

  • SHA256: b39e8df4cf82088fd464e67fb077c9332cdf19cf8b131c8b41aa6d757592ebd9
  • Pointer size: 132 Bytes
  • Size of remote file: 1.37 MB
requirements.txt ADDED
Binary file (628 Bytes). View file
 
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,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+ from text import cleaners
3
+ from text.symbols import symbols
4
+
5
+
6
+ # Mappings from symbol to numeric ID and vice versa:
7
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
8
+ _id_to_symbol = {i: s for i, s in enumerate(symbols)}
9
+
10
+
11
+ def text_to_sequence(text, cleaner_names):
12
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
13
+ Args:
14
+ text: string to convert to a sequence
15
+ cleaner_names: names of the cleaner functions to run the text through
16
+ Returns:
17
+ List of integers corresponding to the symbols in the text
18
+ '''
19
+ sequence = []
20
+
21
+ clean_text = _clean_text(text, cleaner_names)
22
+ for symbol in clean_text:
23
+ symbol_id = _symbol_to_id[symbol]
24
+ sequence += [symbol_id]
25
+ return sequence
26
+
27
+
28
+ def cleaned_text_to_sequence(cleaned_text):
29
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
30
+ Args:
31
+ text: string to convert to a sequence
32
+ Returns:
33
+ List of integers corresponding to the symbols in the text
34
+ '''
35
+ sequence = [_symbol_to_id[symbol] for symbol in cleaned_text]
36
+ return sequence
37
+
38
+
39
+ def sequence_to_text(sequence):
40
+ '''Converts a sequence of IDs back to a string'''
41
+ result = ''
42
+ for symbol_id in sequence:
43
+ s = _id_to_symbol[symbol_id]
44
+ result += s
45
+ return result
46
+
47
+
48
+ def _clean_text(text, cleaner_names):
49
+ for name in cleaner_names:
50
+ cleaner = getattr(cleaners, name)
51
+ if not cleaner:
52
+ raise Exception('Unknown cleaner: %s' % name)
53
+ text = cleaner(text)
54
+ return text
text/cleaners.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+
3
+ '''
4
+ Cleaners are transformations that run over the input text at both training and eval time.
5
+
6
+ Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
7
+ hyperparameter. Some cleaners are English-specific. You'll typically want to use:
8
+ 1. "english_cleaners" for English text
9
+ 2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
10
+ the Unidecode library (https://pypi.python.org/pypi/Unidecode)
11
+ 3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
12
+ the symbols in symbols.py to match your data).
13
+ '''
14
+
15
+ import re
16
+ from unidecode import unidecode
17
+ from phonemizer import phonemize
18
+
19
+
20
+ # Regular expression matching whitespace:
21
+ _whitespace_re = re.compile(r'\s+')
22
+
23
+ # List of (regular expression, replacement) pairs for abbreviations:
24
+ _abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
25
+ ('mrs', 'misess'),
26
+ ('mr', 'mister'),
27
+ ('dr', 'doctor'),
28
+ ('st', 'saint'),
29
+ ('co', 'company'),
30
+ ('jr', 'junior'),
31
+ ('maj', 'major'),
32
+ ('gen', 'general'),
33
+ ('drs', 'doctors'),
34
+ ('rev', 'reverend'),
35
+ ('lt', 'lieutenant'),
36
+ ('hon', 'honorable'),
37
+ ('sgt', 'sergeant'),
38
+ ('capt', 'captain'),
39
+ ('esq', 'esquire'),
40
+ ('ltd', 'limited'),
41
+ ('col', 'colonel'),
42
+ ('ft', 'fort'),
43
+ ]]
44
+
45
+
46
+ def expand_abbreviations(text):
47
+ for regex, replacement in _abbreviations:
48
+ text = re.sub(regex, replacement, text)
49
+ return text
50
+
51
+
52
+ def expand_numbers(text):
53
+ return normalize_numbers(text)
54
+
55
+
56
+ def lowercase(text):
57
+ return text.lower()
58
+
59
+
60
+ def collapse_whitespace(text):
61
+ return re.sub(_whitespace_re, ' ', text)
62
+
63
+
64
+ def convert_to_ascii(text):
65
+ return unidecode(text)
66
+
67
+
68
+ def basic_cleaners(text):
69
+ '''Basic pipeline that lowercases and collapses whitespace without transliteration.'''
70
+ text = lowercase(text)
71
+ text = collapse_whitespace(text)
72
+ return text
73
+
74
+
75
+ def transliteration_cleaners(text):
76
+ '''Pipeline for non-English text that transliterates to ASCII.'''
77
+ text = convert_to_ascii(text)
78
+ text = lowercase(text)
79
+ text = collapse_whitespace(text)
80
+ return text
81
+
82
+
83
+ def english_cleaners(text):
84
+ '''Pipeline for English text, including abbreviation expansion.'''
85
+ text = convert_to_ascii(text)
86
+ text = lowercase(text)
87
+ text = expand_abbreviations(text)
88
+ phonemes = phonemize(text, language='en-us', backend='espeak', strip=True)
89
+ phonemes = collapse_whitespace(phonemes)
90
+ return phonemes
91
+
92
+
93
+ def english_cleaners2(text):
94
+ '''Pipeline for English text, including abbreviation expansion. + punctuation + stress'''
95
+ text = convert_to_ascii(text)
96
+ text = lowercase(text)
97
+ text = expand_abbreviations(text)
98
+ phonemes = phonemize(text, language='en-us', backend='espeak', strip=True, preserve_punctuation=True, with_stress=True)
99
+ phonemes = collapse_whitespace(phonemes)
100
+ return phonemes
text/symbols.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+
3
+ '''
4
+ Defines the set of symbols used in text input to the model.
5
+ '''
6
+ _pad = '_'
7
+ _punctuation = ';:,.!?¡¿—…"«»“” '
8
+ _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
9
+ _letters_ipa = "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
10
+
11
+
12
+ # Export all symbols:
13
+ symbols = [_pad] + list(_punctuation) + list(_letters) + list(_letters_ipa)
14
+
15
+ # Special symbol ids
16
+ SPACE_ID = symbols.index(" ")
tts/__init__.py ADDED
File without changes
tts/attentions.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+
9
+ from . import commons
10
+ from . import modules
11
+
12
+ from .modules import LayerNorm
13
+
14
+
15
+ class Encoder(nn.Module):
16
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
17
+ super().__init__()
18
+ self.hidden_channels = hidden_channels
19
+ self.filter_channels = filter_channels
20
+ self.n_heads = n_heads
21
+ self.n_layers = n_layers
22
+ self.kernel_size = kernel_size
23
+ self.p_dropout = p_dropout
24
+ self.window_size = window_size
25
+
26
+ self.drop = nn.Dropout(p_dropout)
27
+ self.attn_layers = nn.ModuleList()
28
+ self.norm_layers_1 = nn.ModuleList()
29
+ self.ffn_layers = nn.ModuleList()
30
+ self.norm_layers_2 = nn.ModuleList()
31
+ for i in range(self.n_layers):
32
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
33
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
34
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
35
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
36
+
37
+ def forward(self, x, x_mask):
38
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
39
+ x = x * x_mask
40
+ for i in range(self.n_layers):
41
+ y = self.attn_layers[i](x, x, attn_mask)
42
+ y = self.drop(y)
43
+ x = self.norm_layers_1[i](x + y)
44
+
45
+ y = self.ffn_layers[i](x, x_mask)
46
+ y = self.drop(y)
47
+ x = self.norm_layers_2[i](x + y)
48
+ x = x * x_mask
49
+ return x
50
+
51
+
52
+ class Decoder(nn.Module):
53
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
54
+ super().__init__()
55
+ self.hidden_channels = hidden_channels
56
+ self.filter_channels = filter_channels
57
+ self.n_heads = n_heads
58
+ self.n_layers = n_layers
59
+ self.kernel_size = kernel_size
60
+ self.p_dropout = p_dropout
61
+ self.proximal_bias = proximal_bias
62
+ self.proximal_init = proximal_init
63
+
64
+ self.drop = nn.Dropout(p_dropout)
65
+ self.self_attn_layers = nn.ModuleList()
66
+ self.norm_layers_0 = nn.ModuleList()
67
+ self.encdec_attn_layers = nn.ModuleList()
68
+ self.norm_layers_1 = nn.ModuleList()
69
+ self.ffn_layers = nn.ModuleList()
70
+ self.norm_layers_2 = nn.ModuleList()
71
+ for i in range(self.n_layers):
72
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
73
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
74
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
75
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
76
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
77
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
78
+
79
+ def forward(self, x, x_mask, h, h_mask):
80
+ """
81
+ x: decoder input
82
+ h: encoder output
83
+ """
84
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
85
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
86
+ x = x * x_mask
87
+ for i in range(self.n_layers):
88
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
89
+ y = self.drop(y)
90
+ x = self.norm_layers_0[i](x + y)
91
+
92
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
93
+ y = self.drop(y)
94
+ x = self.norm_layers_1[i](x + y)
95
+
96
+ y = self.ffn_layers[i](x, x_mask)
97
+ y = self.drop(y)
98
+ x = self.norm_layers_2[i](x + y)
99
+ x = x * x_mask
100
+ return x
101
+
102
+
103
+ class MultiHeadAttention(nn.Module):
104
+ 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):
105
+ super().__init__()
106
+ assert channels % n_heads == 0
107
+
108
+ self.channels = channels
109
+ self.out_channels = out_channels
110
+ self.n_heads = n_heads
111
+ self.p_dropout = p_dropout
112
+ self.window_size = window_size
113
+ self.heads_share = heads_share
114
+ self.block_length = block_length
115
+ self.proximal_bias = proximal_bias
116
+ self.proximal_init = proximal_init
117
+ self.attn = None
118
+
119
+ self.k_channels = channels // n_heads
120
+
121
+ self.conv_q = nn.Conv1d(channels, channels, 1)
122
+
123
+ self.conv_k = nn.Conv1d(channels, channels, 1)
124
+
125
+ self.conv_v = nn.Conv1d(channels, channels, 1)
126
+
127
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
128
+ self.drop = nn.Dropout(p_dropout)
129
+
130
+ if window_size is not None:
131
+ n_heads_rel = 1 if heads_share else n_heads
132
+ rel_stddev = self.k_channels**-0.5
133
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
134
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
135
+
136
+ nn.init.xavier_uniform_(self.conv_q.weight)
137
+ nn.init.xavier_uniform_(self.conv_k.weight)
138
+ nn.init.xavier_uniform_(self.conv_v.weight)
139
+ if proximal_init:
140
+ with torch.no_grad():
141
+ self.conv_k.weight.copy_(self.conv_q.weight)
142
+ self.conv_k.bias.copy_(self.conv_q.bias)
143
+
144
+ def forward(self, x, c, attn_mask=None):
145
+ q = self.conv_q(x)
146
+ k = self.conv_k(c)
147
+ v = self.conv_v(c)
148
+
149
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
150
+
151
+ x = self.conv_o(x)
152
+ return x
153
+
154
+ def attention(self, query, key, value, mask=None):
155
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
156
+ b, d, t_s, t_t = (*key.size(), query.size(2))
157
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
158
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
159
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
160
+
161
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
162
+ if self.window_size is not None:
163
+ assert t_s == t_t, "Relative attention is only available for self-attention."
164
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
165
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
166
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
167
+ scores = scores + scores_local
168
+ if self.proximal_bias:
169
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
170
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
171
+ if mask is not None:
172
+ scores = scores.masked_fill(mask == 0, -1e4)
173
+ if self.block_length is not None:
174
+ assert t_s == t_t, "Local attention is only available for self-attention."
175
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
176
+ scores = scores.masked_fill(block_mask == 0, -1e4)
177
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
178
+ p_attn = self.drop(p_attn)
179
+ output = torch.matmul(p_attn, value)
180
+ if self.window_size is not None:
181
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
182
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
183
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
184
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
185
+ return output, p_attn
186
+
187
+ def _matmul_with_relative_values(self, x, y):
188
+ """
189
+ x: [b, h, l, m]
190
+ y: [h or 1, m, d]
191
+ ret: [b, h, l, d]
192
+ """
193
+ ret = torch.matmul(x, y.unsqueeze(0))
194
+ return ret
195
+
196
+ def _matmul_with_relative_keys(self, x, y):
197
+ """
198
+ x: [b, h, l, d]
199
+ y: [h or 1, m, d]
200
+ ret: [b, h, l, m]
201
+ """
202
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
203
+ return ret
204
+
205
+ def _get_relative_embeddings(self, relative_embeddings, length):
206
+ max_relative_position = 2 * self.window_size + 1
207
+ # Pad first before slice to avoid using cond ops.
208
+ pad_length = max(length - (self.window_size + 1), 0)
209
+ slice_start_position = max((self.window_size + 1) - length, 0)
210
+ slice_end_position = slice_start_position + 2 * length - 1
211
+ if pad_length > 0:
212
+ padded_relative_embeddings = F.pad(
213
+ relative_embeddings,
214
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
215
+ else:
216
+ padded_relative_embeddings = relative_embeddings
217
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
218
+ return used_relative_embeddings
219
+
220
+ def _relative_position_to_absolute_position(self, x):
221
+ """
222
+ x: [b, h, l, 2*l-1]
223
+ ret: [b, h, l, l]
224
+ """
225
+ batch, heads, length, _ = x.size()
226
+ # Concat columns of pad to shift from relative to absolute indexing.
227
+ x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
228
+
229
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
230
+ x_flat = x.view([batch, heads, length * 2 * length])
231
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
232
+
233
+ # Reshape and slice out the padded elements.
234
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
235
+ return x_final
236
+
237
+ def _absolute_position_to_relative_position(self, x):
238
+ """
239
+ x: [b, h, l, l]
240
+ ret: [b, h, l, 2*l-1]
241
+ """
242
+ batch, heads, length, _ = x.size()
243
+ # padd along column
244
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
245
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
246
+ # add 0's in the beginning that will skew the elements after reshape
247
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
248
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
249
+ return x_final
250
+
251
+ def _attention_bias_proximal(self, length):
252
+ """Bias for self-attention to encourage attention to close positions.
253
+ Args:
254
+ length: an integer scalar.
255
+ Returns:
256
+ a Tensor with shape [1, 1, length, length]
257
+ """
258
+ r = torch.arange(length, dtype=torch.float32)
259
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
260
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
261
+
262
+ class FFN(nn.Module):
263
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
264
+ super().__init__()
265
+ self.in_channels = in_channels
266
+ self.out_channels = out_channels
267
+ self.filter_channels = filter_channels
268
+ self.kernel_size = kernel_size
269
+ self.p_dropout = p_dropout
270
+ self.activation = activation
271
+ self.causal = causal
272
+
273
+ if causal:
274
+ self.padding = self._causal_padding
275
+ else:
276
+ self.padding = self._same_padding
277
+
278
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
279
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
280
+ self.drop = nn.Dropout(p_dropout)
281
+
282
+ def forward(self, x, x_mask):
283
+ x = self.conv_1(self.padding(x * x_mask))
284
+ if self.activation == "gelu":
285
+ x = x * torch.sigmoid(1.702 * x)
286
+ else:
287
+ x = torch.relu(x)
288
+ x = self.drop(x)
289
+ x = self.conv_2(self.padding(x * x_mask))
290
+ return x * x_mask
291
+
292
+ def _causal_padding(self, x):
293
+ if self.kernel_size == 1:
294
+ return x
295
+ pad_l = self.kernel_size - 1
296
+ pad_r = 0
297
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
298
+ x = F.pad(x, commons.convert_pad_shape(padding))
299
+ return x
300
+
301
+ def _same_padding(self, x):
302
+ if self.kernel_size == 1:
303
+ return x
304
+ pad_l = (self.kernel_size - 1) // 2
305
+ pad_r = self.kernel_size // 2
306
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
307
+ x = F.pad(x, commons.convert_pad_shape(padding))
308
+ return x
tts/commons.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+
8
+ def init_weights(m, mean=0.0, std=0.01):
9
+ classname = m.__class__.__name__
10
+ if classname.find("Conv") != -1:
11
+ m.weight.data.normal_(mean, std)
12
+
13
+
14
+ def get_padding(kernel_size, dilation=1):
15
+ return int((kernel_size*dilation - dilation)/2)
16
+
17
+
18
+ def convert_pad_shape(pad_shape):
19
+ l = pad_shape[::-1]
20
+ pad_shape = [item for sublist in l for item in sublist]
21
+ return pad_shape
22
+
23
+
24
+ def intersperse(lst, item):
25
+ result = [item] * (len(lst) * 2 + 1)
26
+ result[1::2] = lst
27
+ return result
28
+
29
+
30
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
31
+ """KL(P||Q)"""
32
+ kl = (logs_q - logs_p) - 0.5
33
+ kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
34
+ return kl
35
+
36
+
37
+ def rand_gumbel(shape):
38
+ """Sample from the Gumbel distribution, protect from overflows."""
39
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
40
+ return -torch.log(-torch.log(uniform_samples))
41
+
42
+
43
+ def rand_gumbel_like(x):
44
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
45
+ return g
46
+
47
+
48
+ def slice_segments(x, ids_str, segment_size=4):
49
+ ret = torch.zeros_like(x[:, :, :segment_size])
50
+ for i in range(x.size(0)):
51
+ idx_str = ids_str[i]
52
+ idx_end = idx_str + segment_size
53
+ ret[i] = x[i, :, idx_str:idx_end]
54
+ return ret
55
+
56
+
57
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
58
+ b, d, t = x.size()
59
+ if x_lengths is None:
60
+ x_lengths = t
61
+ ids_str_max = x_lengths - segment_size + 1
62
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
63
+ ret = slice_segments(x, ids_str, segment_size)
64
+ return ret, ids_str
65
+
66
+
67
+ def get_timing_signal_1d(
68
+ length, channels, min_timescale=1.0, max_timescale=1.0e4):
69
+ position = torch.arange(length, dtype=torch.float)
70
+ num_timescales = channels // 2
71
+ log_timescale_increment = (
72
+ math.log(float(max_timescale) / float(min_timescale)) /
73
+ (num_timescales - 1))
74
+ inv_timescales = min_timescale * torch.exp(
75
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
76
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
77
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
78
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
79
+ signal = signal.view(1, channels, length)
80
+ return signal
81
+
82
+
83
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
84
+ b, channels, length = x.size()
85
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
86
+ return x + signal.to(dtype=x.dtype, device=x.device)
87
+
88
+
89
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
90
+ b, channels, length = x.size()
91
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
92
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
93
+
94
+
95
+ def subsequent_mask(length):
96
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
97
+ return mask
98
+
99
+
100
+ @torch.jit.script
101
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
102
+ n_channels_int = n_channels[0]
103
+ in_act = input_a + input_b
104
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
105
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
106
+ acts = t_act * s_act
107
+ return acts
108
+
109
+
110
+ def convert_pad_shape(pad_shape):
111
+ l = pad_shape[::-1]
112
+ pad_shape = [item for sublist in l for item in sublist]
113
+ return pad_shape
114
+
115
+
116
+ def shift_1d(x):
117
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
118
+ return x
119
+
120
+
121
+ def sequence_mask(length, max_length=None):
122
+ if max_length is None:
123
+ max_length = length.max()
124
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
125
+ return x.unsqueeze(0) < length.unsqueeze(1)
126
+
127
+
128
+ def generate_path(duration, mask):
129
+ """
130
+ duration: [b, 1, t_x]
131
+ mask: [b, 1, t_y, t_x]
132
+ """
133
+ device = duration.device
134
+
135
+ b, _, t_y, t_x = mask.shape
136
+ cum_duration = torch.cumsum(duration, -1)
137
+
138
+ cum_duration_flat = cum_duration.view(b * t_x)
139
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
140
+ path = path.view(b, t_x, t_y)
141
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
142
+ path = path.unsqueeze(1).transpose(2,3) * mask
143
+ return path
144
+
145
+
146
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
147
+ if isinstance(parameters, torch.Tensor):
148
+ parameters = [parameters]
149
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
150
+ norm_type = float(norm_type)
151
+ if clip_value is not None:
152
+ clip_value = float(clip_value)
153
+
154
+ total_norm = 0
155
+ for p in parameters:
156
+ param_norm = p.grad.data.norm(norm_type)
157
+ total_norm += param_norm.item() ** norm_type
158
+ if clip_value is not None:
159
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
160
+ total_norm = total_norm ** (1. / norm_type)
161
+ return total_norm
tts/data_utils.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+
8
+ from . import commons
9
+ from . import mel_processing
10
+ from .mel_processing import spectrogram_torch
11
+ from .utils import load_wav_to_torch, load_filepaths_and_text
12
+ from text import text_to_sequence, cleaned_text_to_sequence
13
+
14
+
15
+ class TextAudioLoader(torch.utils.data.Dataset):
16
+ """
17
+ 1) loads audio, text pairs
18
+ 2) normalizes text and converts them to sequences of integers
19
+ 3) computes spectrograms from audio files.
20
+ """
21
+ def __init__(self, audiopaths_and_text, hparams):
22
+ self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
23
+ self.text_cleaners = hparams.text_cleaners
24
+ self.max_wav_value = hparams.max_wav_value
25
+ self.sampling_rate = hparams.sampling_rate
26
+ self.filter_length = hparams.filter_length
27
+ self.hop_length = hparams.hop_length
28
+ self.win_length = hparams.win_length
29
+ self.sampling_rate = hparams.sampling_rate
30
+
31
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
32
+
33
+ self.add_blank = hparams.add_blank
34
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
35
+ self.max_text_len = getattr(hparams, "max_text_len", 190)
36
+
37
+ random.seed(1234)
38
+ random.shuffle(self.audiopaths_and_text)
39
+ self._filter()
40
+
41
+
42
+ def _filter(self):
43
+ """
44
+ Filter text & store spec lengths
45
+ """
46
+ # Store spectrogram lengths for Bucketing
47
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
48
+ # spec_length = wav_length // hop_length
49
+
50
+ audiopaths_and_text_new = []
51
+ lengths = []
52
+ for audiopath, text in self.audiopaths_and_text:
53
+ if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
54
+ audiopaths_and_text_new.append([audiopath, text])
55
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
56
+ self.audiopaths_and_text = audiopaths_and_text_new
57
+ self.lengths = lengths
58
+
59
+ def get_audio_text_pair(self, audiopath_and_text):
60
+ # separate filename and text
61
+ audiopath, text = audiopath_and_text[0], audiopath_and_text[1]
62
+ text = self.get_text(text)
63
+ spec, wav = self.get_audio(audiopath)
64
+ return (text, spec, wav)
65
+
66
+ def get_audio(self, filename):
67
+ audio, sampling_rate = load_wav_to_torch(filename)
68
+ if sampling_rate != self.sampling_rate:
69
+ raise ValueError("{} {} SR doesn't match target {} SR".format(
70
+ sampling_rate, self.sampling_rate))
71
+ audio_norm = audio / self.max_wav_value
72
+ audio_norm = audio_norm.unsqueeze(0)
73
+ spec_filename = filename.replace(".wav", ".spec.pt")
74
+ if os.path.exists(spec_filename):
75
+ spec = torch.load(spec_filename)
76
+ else:
77
+ spec = spectrogram_torch(audio_norm, self.filter_length,
78
+ self.sampling_rate, self.hop_length, self.win_length,
79
+ center=False)
80
+ spec = torch.squeeze(spec, 0)
81
+ torch.save(spec, spec_filename)
82
+ return spec, audio_norm
83
+
84
+ def get_text(self, text):
85
+ if self.cleaned_text:
86
+ text_norm = cleaned_text_to_sequence(text)
87
+ else:
88
+ text_norm = text_to_sequence(text, self.text_cleaners)
89
+ if self.add_blank:
90
+ text_norm = commons.intersperse(text_norm, 0)
91
+ text_norm = torch.LongTensor(text_norm)
92
+ return text_norm
93
+
94
+ def __getitem__(self, index):
95
+ return self.get_audio_text_pair(self.audiopaths_and_text[index])
96
+
97
+ def __len__(self):
98
+ return len(self.audiopaths_and_text)
99
+
100
+
101
+ class TextAudioCollate():
102
+ """ Zero-pads model inputs and targets
103
+ """
104
+ def __init__(self, return_ids=False):
105
+ self.return_ids = return_ids
106
+
107
+ def __call__(self, batch):
108
+ """Collate's training batch from normalized text and aduio
109
+ PARAMS
110
+ ------
111
+ batch: [text_normalized, spec_normalized, wav_normalized]
112
+ """
113
+ # Right zero-pad all one-hot text sequences to max input length
114
+ _, ids_sorted_decreasing = torch.sort(
115
+ torch.LongTensor([x[1].size(1) for x in batch]),
116
+ dim=0, descending=True)
117
+
118
+ max_text_len = max([len(x[0]) for x in batch])
119
+ max_spec_len = max([x[1].size(1) for x in batch])
120
+ max_wav_len = max([x[2].size(1) for x in batch])
121
+
122
+ text_lengths = torch.LongTensor(len(batch))
123
+ spec_lengths = torch.LongTensor(len(batch))
124
+ wav_lengths = torch.LongTensor(len(batch))
125
+
126
+ text_padded = torch.LongTensor(len(batch), max_text_len)
127
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
128
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
129
+ text_padded.zero_()
130
+ spec_padded.zero_()
131
+ wav_padded.zero_()
132
+ for i in range(len(ids_sorted_decreasing)):
133
+ row = batch[ids_sorted_decreasing[i]]
134
+
135
+ text = row[0]
136
+ text_padded[i, :text.size(0)] = text
137
+ text_lengths[i] = text.size(0)
138
+
139
+ spec = row[1]
140
+ spec_padded[i, :, :spec.size(1)] = spec
141
+ spec_lengths[i] = spec.size(1)
142
+
143
+ wav = row[2]
144
+ wav_padded[i, :, :wav.size(1)] = wav
145
+ wav_lengths[i] = wav.size(1)
146
+
147
+ if self.return_ids:
148
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing
149
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths
150
+
151
+
152
+ """Multi speaker version"""
153
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
154
+ """
155
+ 1) loads audio, speaker_id, text pairs
156
+ 2) normalizes text and converts them to sequences of integers
157
+ 3) computes spectrograms from audio files.
158
+ """
159
+ def __init__(self, audiopaths_sid_text, hparams):
160
+ self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
161
+ self.text_cleaners = hparams.text_cleaners
162
+ self.max_wav_value = hparams.max_wav_value
163
+ self.sampling_rate = hparams.sampling_rate
164
+ self.filter_length = hparams.filter_length
165
+ self.hop_length = hparams.hop_length
166
+ self.win_length = hparams.win_length
167
+ self.sampling_rate = hparams.sampling_rate
168
+
169
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
170
+
171
+ self.add_blank = hparams.add_blank
172
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
173
+ self.max_text_len = getattr(hparams, "max_text_len", 190)
174
+
175
+ random.seed(1234)
176
+ random.shuffle(self.audiopaths_sid_text)
177
+ self._filter()
178
+
179
+ def _filter(self):
180
+ """
181
+ Filter text & store spec lengths
182
+ """
183
+ # Store spectrogram lengths for Bucketing
184
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
185
+ # spec_length = wav_length // hop_length
186
+
187
+ audiopaths_sid_text_new = []
188
+ lengths = []
189
+ for audiopath, sid, text in self.audiopaths_sid_text:
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
+ if len_bucket != 0:
355
+ ids_bucket = indices[i]
356
+ num_samples_bucket = self.num_samples_per_bucket[i]
357
+
358
+ # add extra samples to make it evenly divisible
359
+ rem = num_samples_bucket - len_bucket
360
+ ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
361
+
362
+ # subsample
363
+ ids_bucket = ids_bucket[self.rank::self.num_replicas]
364
+
365
+ # batching
366
+ for j in range(len(ids_bucket) // self.batch_size):
367
+ batch = [bucket[idx] for idx in ids_bucket[j*self.batch_size:(j+1)*self.batch_size]]
368
+ batches.append(batch)
369
+
370
+ if self.shuffle:
371
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
372
+ batches = [batches[i] for i in batch_ids]
373
+ self.batches = batches
374
+
375
+ assert len(self.batches) * self.batch_size == self.num_samples
376
+ return iter(self.batches)
377
+
378
+ def _bisect(self, x, lo=0, hi=None):
379
+ if hi is None:
380
+ hi = len(self.boundaries) - 1
381
+
382
+ if hi > lo:
383
+ mid = (hi + lo) // 2
384
+ if self.boundaries[mid] < x and x <= self.boundaries[mid+1]:
385
+ return mid
386
+ elif x <= self.boundaries[mid]:
387
+ return self._bisect(x, lo, mid)
388
+ else:
389
+ return self._bisect(x, mid + 1, hi)
390
+ else:
391
+ return -1
392
+
393
+ def __len__(self):
394
+ return self.num_samples // self.batch_size
tts/losses.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ from . 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
tts/mel_processing.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+ import torch.utils.data
8
+ import numpy as np
9
+ import librosa
10
+ import librosa.util as librosa_util
11
+ from librosa.util import normalize, pad_center, tiny
12
+ from scipy.signal import get_window
13
+ from scipy.io.wavfile import read
14
+ from librosa.filters import mel as librosa_mel_fn
15
+ from . import commons
16
+
17
+
18
+ MAX_WAV_VALUE = 32768.0
19
+
20
+
21
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
22
+ """
23
+ PARAMS
24
+ ------
25
+ C: compression factor
26
+ """
27
+ return torch.log(torch.clamp(x, min=clip_val) * C)
28
+
29
+
30
+ def dynamic_range_decompression_torch(x, C=1):
31
+ """
32
+ PARAMS
33
+ ------
34
+ C: compression factor used to compress
35
+ """
36
+ return torch.exp(x) / C
37
+
38
+
39
+ def spectral_normalize_torch(magnitudes):
40
+ output = dynamic_range_compression_torch(magnitudes)
41
+ return output
42
+
43
+
44
+ def spectral_de_normalize_torch(magnitudes):
45
+ output = dynamic_range_decompression_torch(magnitudes)
46
+ return output
47
+
48
+
49
+ mel_basis = {}
50
+ hann_window = {}
51
+
52
+
53
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
54
+ if torch.min(y) < -1.:
55
+ print('min value is ', torch.min(y))
56
+ if torch.max(y) > 1.:
57
+ print('max value is ', torch.max(y))
58
+
59
+ global hann_window
60
+ dtype_device = str(y.dtype) + '_' + str(y.device)
61
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
62
+ if wnsize_dtype_device not in hann_window:
63
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
64
+
65
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
66
+ y = y.squeeze(1)
67
+
68
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
69
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
70
+
71
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
72
+ return spec
73
+
74
+
75
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
76
+ global mel_basis
77
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
78
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
79
+ if fmax_dtype_device not in mel_basis:
80
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
81
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
82
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
83
+ spec = spectral_normalize_torch(spec)
84
+ return spec
85
+
86
+
87
+ def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
88
+ if torch.min(y) < -1.:
89
+ print('min value is ', torch.min(y))
90
+ if torch.max(y) > 1.:
91
+ print('max value is ', torch.max(y))
92
+
93
+ global mel_basis, hann_window
94
+ dtype_device = str(y.dtype) + '_' + str(y.device)
95
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
96
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
97
+ if fmax_dtype_device not in mel_basis:
98
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
99
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
100
+ if wnsize_dtype_device not in hann_window:
101
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
102
+
103
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
104
+ y = y.squeeze(1)
105
+
106
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
107
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
108
+
109
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
110
+
111
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
112
+ spec = spectral_normalize_torch(spec)
113
+
114
+ return spec
tts/models.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ from . import commons
8
+ from . import modules
9
+ from . import attentions
10
+
11
+ import monotonic_align
12
+
13
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
14
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
15
+ from .commons import init_weights, get_padding
16
+
17
+
18
+ class StochasticDurationPredictor(nn.Module):
19
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
20
+ super().__init__()
21
+ filter_channels = in_channels # it needs to be removed from future version.
22
+ self.in_channels = in_channels
23
+ self.filter_channels = filter_channels
24
+ self.kernel_size = kernel_size
25
+ self.p_dropout = p_dropout
26
+ self.n_flows = n_flows
27
+ self.gin_channels = gin_channels
28
+
29
+ self.log_flow = modules.Log()
30
+ self.flows = nn.ModuleList()
31
+ self.flows.append(modules.ElementwiseAffine(2))
32
+ for i in range(n_flows):
33
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
34
+ self.flows.append(modules.Flip())
35
+
36
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
37
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
38
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
39
+ self.post_flows = nn.ModuleList()
40
+ self.post_flows.append(modules.ElementwiseAffine(2))
41
+ for i in range(4):
42
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
43
+ self.post_flows.append(modules.Flip())
44
+
45
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
46
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
47
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
48
+ if gin_channels != 0:
49
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
50
+
51
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
52
+ x = torch.detach(x)
53
+ x = self.pre(x)
54
+ if g is not None:
55
+ g = torch.detach(g)
56
+ x = x + self.cond(g)
57
+ x = self.convs(x, x_mask)
58
+ x = self.proj(x) * x_mask
59
+
60
+ if not reverse:
61
+ flows = self.flows
62
+ assert w is not None
63
+
64
+ logdet_tot_q = 0
65
+ h_w = self.post_pre(w)
66
+ h_w = self.post_convs(h_w, x_mask)
67
+ h_w = self.post_proj(h_w) * x_mask
68
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
69
+ z_q = e_q
70
+ for flow in self.post_flows:
71
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
72
+ logdet_tot_q += logdet_q
73
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
74
+ u = torch.sigmoid(z_u) * x_mask
75
+ z0 = (w - u) * x_mask
76
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1,2])
77
+ logq = torch.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - logdet_tot_q
78
+
79
+ logdet_tot = 0
80
+ z0, logdet = self.log_flow(z0, x_mask)
81
+ logdet_tot += logdet
82
+ z = torch.cat([z0, z1], 1)
83
+ for flow in flows:
84
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
85
+ logdet_tot = logdet_tot + logdet
86
+ nll = torch.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - logdet_tot
87
+ return nll + logq # [b]
88
+ else:
89
+ flows = list(reversed(self.flows))
90
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
91
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
92
+ for flow in flows:
93
+ z = flow(z, x_mask, g=x, reverse=reverse)
94
+ z0, z1 = torch.split(z, [1, 1], 1)
95
+ logw = z0
96
+ return logw
97
+
98
+
99
+ class DurationPredictor(nn.Module):
100
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
101
+ super().__init__()
102
+
103
+ self.in_channels = in_channels
104
+ self.filter_channels = filter_channels
105
+ self.kernel_size = kernel_size
106
+ self.p_dropout = p_dropout
107
+ self.gin_channels = gin_channels
108
+
109
+ self.drop = nn.Dropout(p_dropout)
110
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
111
+ self.norm_1 = modules.LayerNorm(filter_channels)
112
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
113
+ self.norm_2 = modules.LayerNorm(filter_channels)
114
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
115
+
116
+ if gin_channels != 0:
117
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
118
+
119
+ def forward(self, x, x_mask, g=None):
120
+ x = torch.detach(x)
121
+ if g is not None:
122
+ g = torch.detach(g)
123
+ x = x + self.cond(g)
124
+ x = self.conv_1(x * x_mask)
125
+ x = torch.relu(x)
126
+ x = self.norm_1(x)
127
+ x = self.drop(x)
128
+ x = self.conv_2(x * x_mask)
129
+ x = torch.relu(x)
130
+ x = self.norm_2(x)
131
+ x = self.drop(x)
132
+ x = self.proj(x * x_mask)
133
+ return x * x_mask
134
+
135
+
136
+ class TextEncoder(nn.Module):
137
+ def __init__(self,
138
+ n_vocab,
139
+ out_channels,
140
+ hidden_channels,
141
+ filter_channels,
142
+ n_heads,
143
+ n_layers,
144
+ kernel_size,
145
+ p_dropout):
146
+ super().__init__()
147
+ self.n_vocab = n_vocab
148
+ self.out_channels = out_channels
149
+ self.hidden_channels = hidden_channels
150
+ self.filter_channels = filter_channels
151
+ self.n_heads = n_heads
152
+ self.n_layers = n_layers
153
+ self.kernel_size = kernel_size
154
+ self.p_dropout = p_dropout
155
+
156
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
157
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
158
+
159
+ self.encoder = attentions.Encoder(
160
+ hidden_channels,
161
+ filter_channels,
162
+ n_heads,
163
+ n_layers,
164
+ kernel_size,
165
+ p_dropout)
166
+ self.proj= nn.Conv1d(hidden_channels, out_channels * 2, 1)
167
+
168
+ def forward(self, x, x_lengths):
169
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
170
+ x = torch.transpose(x, 1, -1) # [b, h, t]
171
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
172
+
173
+ x = self.encoder(x * x_mask, x_mask)
174
+ stats = self.proj(x) * x_mask
175
+
176
+ m, logs = torch.split(stats, self.out_channels, dim=1)
177
+ return x, m, logs, x_mask
178
+
179
+
180
+
181
+
182
+ class ResidualCouplingBlock(nn.Module):
183
+ def __init__(self,
184
+ channels,
185
+ hidden_channels,
186
+ kernel_size,
187
+ dilation_rate,
188
+ n_layers,
189
+ n_flows=4,
190
+ gin_channels=0):
191
+ super().__init__()
192
+ self.channels = channels
193
+ self.hidden_channels = hidden_channels
194
+ self.kernel_size = kernel_size
195
+ self.dilation_rate = dilation_rate
196
+ self.n_layers = n_layers
197
+ self.n_flows = n_flows
198
+ self.gin_channels = gin_channels
199
+
200
+ self.flows = nn.ModuleList()
201
+ for i in range(n_flows):
202
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
203
+ self.flows.append(modules.Flip())
204
+
205
+ def forward(self, x, x_mask, g=None, reverse=False):
206
+ if not reverse:
207
+ for flow in self.flows:
208
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
209
+ else:
210
+ for flow in reversed(self.flows):
211
+ x = flow(x, x_mask, g=g, reverse=reverse)
212
+ return x
213
+
214
+
215
+ class PosteriorEncoder(nn.Module):
216
+ def __init__(self,
217
+ in_channels,
218
+ out_channels,
219
+ hidden_channels,
220
+ kernel_size,
221
+ dilation_rate,
222
+ n_layers,
223
+ gin_channels=0):
224
+ super().__init__()
225
+ self.in_channels = in_channels
226
+ self.out_channels = out_channels
227
+ self.hidden_channels = hidden_channels
228
+ self.kernel_size = kernel_size
229
+ self.dilation_rate = dilation_rate
230
+ self.n_layers = n_layers
231
+ self.gin_channels = gin_channels
232
+
233
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
234
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
235
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
236
+
237
+ def forward(self, x, x_lengths, g=None):
238
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
239
+ x = self.pre(x) * x_mask
240
+ x = self.enc(x, x_mask, g=g)
241
+ stats = self.proj(x) * x_mask
242
+ m, logs = torch.split(stats, self.out_channels, dim=1)
243
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
244
+ return z, m, logs, x_mask
245
+
246
+
247
+ class Generator(torch.nn.Module):
248
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
249
+ super(Generator, self).__init__()
250
+ self.num_kernels = len(resblock_kernel_sizes)
251
+ self.num_upsamples = len(upsample_rates)
252
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
253
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
254
+
255
+ self.ups = nn.ModuleList()
256
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
257
+ self.ups.append(weight_norm(
258
+ ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)),
259
+ k, u, padding=(k-u)//2)))
260
+
261
+ self.resblocks = nn.ModuleList()
262
+ for i in range(len(self.ups)):
263
+ ch = upsample_initial_channel//(2**(i+1))
264
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
265
+ self.resblocks.append(resblock(ch, k, d))
266
+
267
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
268
+ self.ups.apply(init_weights)
269
+
270
+ if gin_channels != 0:
271
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
272
+
273
+ def forward(self, x, g=None):
274
+ x = self.conv_pre(x)
275
+ if g is not None:
276
+ x = x + self.cond(g)
277
+
278
+ for i in range(self.num_upsamples):
279
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
280
+ x = self.ups[i](x)
281
+ xs = None
282
+ for j in range(self.num_kernels):
283
+ if xs is None:
284
+ xs = self.resblocks[i*self.num_kernels+j](x)
285
+ else:
286
+ xs += self.resblocks[i*self.num_kernels+j](x)
287
+ x = xs / self.num_kernels
288
+ x = F.leaky_relu(x)
289
+ x = self.conv_post(x)
290
+ x = torch.tanh(x)
291
+
292
+ return x
293
+
294
+ def remove_weight_norm(self):
295
+ print('Removing weight norm...')
296
+ for l in self.ups:
297
+ remove_weight_norm(l)
298
+ for l in self.resblocks:
299
+ l.remove_weight_norm()
300
+
301
+
302
+ class DiscriminatorP(torch.nn.Module):
303
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
304
+ super(DiscriminatorP, self).__init__()
305
+ self.period = period
306
+ self.use_spectral_norm = use_spectral_norm
307
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
308
+ self.convs = nn.ModuleList([
309
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
310
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
311
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
312
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
313
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
314
+ ])
315
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
316
+
317
+ def forward(self, x):
318
+ fmap = []
319
+
320
+ # 1d to 2d
321
+ b, c, t = x.shape
322
+ if t % self.period != 0: # pad first
323
+ n_pad = self.period - (t % self.period)
324
+ x = F.pad(x, (0, n_pad), "reflect")
325
+ t = t + n_pad
326
+ x = x.view(b, c, t // self.period, self.period)
327
+
328
+ for l in self.convs:
329
+ x = l(x)
330
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
331
+ fmap.append(x)
332
+ x = self.conv_post(x)
333
+ fmap.append(x)
334
+ x = torch.flatten(x, 1, -1)
335
+
336
+ return x, fmap
337
+
338
+
339
+ class DiscriminatorS(torch.nn.Module):
340
+ def __init__(self, use_spectral_norm=False):
341
+ super(DiscriminatorS, self).__init__()
342
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
343
+ self.convs = nn.ModuleList([
344
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
345
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
346
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
347
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
348
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
349
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
350
+ ])
351
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
352
+
353
+ def forward(self, x):
354
+ fmap = []
355
+
356
+ for l in self.convs:
357
+ x = l(x)
358
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
359
+ fmap.append(x)
360
+ x = self.conv_post(x)
361
+ fmap.append(x)
362
+ x = torch.flatten(x, 1, -1)
363
+
364
+ return x, fmap
365
+
366
+
367
+ class MultiPeriodDiscriminator(torch.nn.Module):
368
+ def __init__(self, use_spectral_norm=False):
369
+ super(MultiPeriodDiscriminator, self).__init__()
370
+ self.discriminators = nn.ModuleList([
371
+ DiscriminatorP(2),
372
+ DiscriminatorP(3),
373
+ DiscriminatorP(5),
374
+ DiscriminatorP(7),
375
+ DiscriminatorP(11),
376
+ ])
377
+
378
+ def forward(self, y, y_hat):
379
+ y_d_rs = []
380
+ y_d_gs = []
381
+ fmap_rs = []
382
+ fmap_gs = []
383
+ for i, d in enumerate(self.discriminators):
384
+ y_d_r, fmap_r = d(y)
385
+ y_d_g, fmap_g = d(y_hat)
386
+ y_d_rs.append(y_d_r)
387
+ y_d_gs.append(y_d_g)
388
+ fmap_rs.append(fmap_r)
389
+ fmap_gs.append(fmap_g)
390
+
391
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
392
+
393
+
394
+
395
+ class SynthesizerTrn(nn.Module):
396
+ """
397
+ Synthesizer for Training
398
+ """
399
+
400
+ def __init__(self,
401
+ n_vocab,
402
+ spec_channels,
403
+ segment_size,
404
+ inter_channels,
405
+ hidden_channels,
406
+ filter_channels,
407
+ n_heads,
408
+ n_layers,
409
+ kernel_size,
410
+ p_dropout,
411
+ resblock,
412
+ resblock_kernel_sizes,
413
+ resblock_dilation_sizes,
414
+ upsample_rates,
415
+ upsample_initial_channel,
416
+ upsample_kernel_sizes,
417
+ n_speakers=0,
418
+ gin_channels=0,
419
+ use_sdp=True,
420
+ **kwargs):
421
+
422
+ super().__init__()
423
+ self.n_vocab = n_vocab
424
+ self.spec_channels = spec_channels
425
+ self.inter_channels = inter_channels
426
+ self.hidden_channels = hidden_channels
427
+ self.filter_channels = filter_channels
428
+ self.n_heads = n_heads
429
+ self.n_layers = n_layers
430
+ self.kernel_size = kernel_size
431
+ self.p_dropout = p_dropout
432
+ self.resblock = resblock
433
+ self.resblock_kernel_sizes = resblock_kernel_sizes
434
+ self.resblock_dilation_sizes = resblock_dilation_sizes
435
+ self.upsample_rates = upsample_rates
436
+ self.upsample_initial_channel = upsample_initial_channel
437
+ self.upsample_kernel_sizes = upsample_kernel_sizes
438
+ self.segment_size = segment_size
439
+ self.n_speakers = n_speakers
440
+ self.gin_channels = gin_channels
441
+
442
+ self.use_sdp = use_sdp
443
+
444
+ self.enc_p = TextEncoder(n_vocab,
445
+ inter_channels,
446
+ hidden_channels,
447
+ filter_channels,
448
+ n_heads,
449
+ n_layers,
450
+ kernel_size,
451
+ p_dropout)
452
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
453
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
454
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
455
+
456
+ if use_sdp:
457
+ self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
458
+ else:
459
+ self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
460
+
461
+ if n_speakers > 1:
462
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
463
+
464
+ def forward(self, x, x_lengths, y, y_lengths, sid=None):
465
+
466
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
467
+ if self.n_speakers > 0:
468
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
469
+ else:
470
+ g = None
471
+
472
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
473
+ z_p = self.flow(z, y_mask, g=g)
474
+
475
+ with torch.no_grad():
476
+ # negative cross-entropy
477
+ s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
478
+ neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s]
479
+ 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]
480
+ 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]
481
+ neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
482
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
483
+
484
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
485
+ attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
486
+
487
+ w = attn.sum(2)
488
+ if self.use_sdp:
489
+ l_length = self.dp(x, x_mask, w, g=g)
490
+ l_length = l_length / torch.sum(x_mask)
491
+ else:
492
+ logw_ = torch.log(w + 1e-6) * x_mask
493
+ logw = self.dp(x, x_mask, g=g)
494
+ l_length = torch.sum((logw - logw_)**2, [1,2]) / torch.sum(x_mask) # for averaging
495
+
496
+ # expand prior
497
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
498
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
499
+
500
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
501
+ o = self.dec(z_slice, g=g)
502
+ return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
503
+
504
+ def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None):
505
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
506
+ if self.n_speakers > 0:
507
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
508
+ else:
509
+ g = None
510
+
511
+ if self.use_sdp:
512
+ logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w)
513
+ else:
514
+ logw = self.dp(x, x_mask, g=g)
515
+ w = torch.exp(logw) * x_mask * length_scale
516
+ w_ceil = torch.ceil(w)
517
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
518
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
519
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
520
+ attn = commons.generate_path(w_ceil, attn_mask)
521
+
522
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
523
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
524
+
525
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
526
+ z = self.flow(z_p, y_mask, g=g, reverse=True)
527
+ o = self.dec((z * y_mask)[:,:,:max_len], g=g)
528
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
529
+
530
+ def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
531
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
532
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
533
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
534
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
535
+ z_p = self.flow(z, y_mask, g=g_src)
536
+ z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
537
+ o_hat = self.dec(z_hat * y_mask, g=g_tgt)
538
+ return o_hat, y_mask, (z, z_p, z_hat)
tts/modules.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from . import commons
9
+
10
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
11
+ from torch.nn.utils import weight_norm, remove_weight_norm
12
+
13
+ from . import commons
14
+ from .commons import init_weights, get_padding
15
+ from .transforms import piecewise_rational_quadratic_transform
16
+
17
+
18
+ LRELU_SLOPE = 0.1
19
+
20
+
21
+ class LayerNorm(nn.Module):
22
+ def __init__(self, channels, eps=1e-5):
23
+ super().__init__()
24
+ self.channels = channels
25
+ self.eps = eps
26
+
27
+ self.gamma = nn.Parameter(torch.ones(channels))
28
+ self.beta = nn.Parameter(torch.zeros(channels))
29
+
30
+ def forward(self, x):
31
+ x = x.transpose(1, -1)
32
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
33
+ return x.transpose(1, -1)
34
+
35
+
36
+ class ConvReluNorm(nn.Module):
37
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
38
+ super().__init__()
39
+ self.in_channels = in_channels
40
+ self.hidden_channels = hidden_channels
41
+ self.out_channels = out_channels
42
+ self.kernel_size = kernel_size
43
+ self.n_layers = n_layers
44
+ self.p_dropout = p_dropout
45
+ assert n_layers > 1, "Number of layers should be larger than 0."
46
+
47
+ self.conv_layers = nn.ModuleList()
48
+ self.norm_layers = nn.ModuleList()
49
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
50
+ self.norm_layers.append(LayerNorm(hidden_channels))
51
+ self.relu_drop = nn.Sequential(
52
+ nn.ReLU(),
53
+ nn.Dropout(p_dropout))
54
+ for _ in range(n_layers-1):
55
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
56
+ self.norm_layers.append(LayerNorm(hidden_channels))
57
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
58
+ self.proj.weight.data.zero_()
59
+ self.proj.bias.data.zero_()
60
+
61
+ def forward(self, x, x_mask):
62
+ x_org = x
63
+ for i in range(self.n_layers):
64
+ x = self.conv_layers[i](x * x_mask)
65
+ x = self.norm_layers[i](x)
66
+ x = self.relu_drop(x)
67
+ x = x_org + self.proj(x)
68
+ return x * x_mask
69
+
70
+
71
+ class DDSConv(nn.Module):
72
+ """
73
+ Dialted and Depth-Separable Convolution
74
+ """
75
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
76
+ super().__init__()
77
+ self.channels = channels
78
+ self.kernel_size = kernel_size
79
+ self.n_layers = n_layers
80
+ self.p_dropout = p_dropout
81
+
82
+ self.drop = nn.Dropout(p_dropout)
83
+ self.convs_sep = nn.ModuleList()
84
+ self.convs_1x1 = nn.ModuleList()
85
+ self.norms_1 = nn.ModuleList()
86
+ self.norms_2 = nn.ModuleList()
87
+ for i in range(n_layers):
88
+ dilation = kernel_size ** i
89
+ padding = (kernel_size * dilation - dilation) // 2
90
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
91
+ groups=channels, dilation=dilation, padding=padding
92
+ ))
93
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
94
+ self.norms_1.append(LayerNorm(channels))
95
+ self.norms_2.append(LayerNorm(channels))
96
+
97
+ def forward(self, x, x_mask, g=None):
98
+ if g is not None:
99
+ x = x + g
100
+ for i in range(self.n_layers):
101
+ y = self.convs_sep[i](x * x_mask)
102
+ y = self.norms_1[i](y)
103
+ y = F.gelu(y)
104
+ y = self.convs_1x1[i](y)
105
+ y = self.norms_2[i](y)
106
+ y = F.gelu(y)
107
+ y = self.drop(y)
108
+ x = x + y
109
+ return x * x_mask
110
+
111
+
112
+ class WN(torch.nn.Module):
113
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
114
+ super(WN, self).__init__()
115
+ assert(kernel_size % 2 == 1)
116
+ self.hidden_channels =hidden_channels
117
+ self.kernel_size = kernel_size,
118
+ self.dilation_rate = dilation_rate
119
+ self.n_layers = n_layers
120
+ self.gin_channels = gin_channels
121
+ self.p_dropout = p_dropout
122
+
123
+ self.in_layers = torch.nn.ModuleList()
124
+ self.res_skip_layers = torch.nn.ModuleList()
125
+ self.drop = nn.Dropout(p_dropout)
126
+
127
+ if gin_channels != 0:
128
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
129
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
130
+
131
+ for i in range(n_layers):
132
+ dilation = dilation_rate ** i
133
+ padding = int((kernel_size * dilation - dilation) / 2)
134
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
135
+ dilation=dilation, padding=padding)
136
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
137
+ self.in_layers.append(in_layer)
138
+
139
+ # last one is not necessary
140
+ if i < n_layers - 1:
141
+ res_skip_channels = 2 * hidden_channels
142
+ else:
143
+ res_skip_channels = hidden_channels
144
+
145
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
146
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
147
+ self.res_skip_layers.append(res_skip_layer)
148
+
149
+ def forward(self, x, x_mask, g=None, **kwargs):
150
+ output = torch.zeros_like(x)
151
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
152
+
153
+ if g is not None:
154
+ g = self.cond_layer(g)
155
+
156
+ for i in range(self.n_layers):
157
+ x_in = self.in_layers[i](x)
158
+ if g is not None:
159
+ cond_offset = i * 2 * self.hidden_channels
160
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
161
+ else:
162
+ g_l = torch.zeros_like(x_in)
163
+
164
+ acts = commons.fused_add_tanh_sigmoid_multiply(
165
+ x_in,
166
+ g_l,
167
+ n_channels_tensor)
168
+ acts = self.drop(acts)
169
+
170
+ res_skip_acts = self.res_skip_layers[i](acts)
171
+ if i < self.n_layers - 1:
172
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
173
+ x = (x + res_acts) * x_mask
174
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
175
+ else:
176
+ output = output + res_skip_acts
177
+ return output * x_mask
178
+
179
+ def remove_weight_norm(self):
180
+ if self.gin_channels != 0:
181
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
182
+ for l in self.in_layers:
183
+ torch.nn.utils.remove_weight_norm(l)
184
+ for l in self.res_skip_layers:
185
+ torch.nn.utils.remove_weight_norm(l)
186
+
187
+
188
+ class ResBlock1(torch.nn.Module):
189
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
190
+ super(ResBlock1, self).__init__()
191
+ self.convs1 = nn.ModuleList([
192
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
193
+ padding=get_padding(kernel_size, dilation[0]))),
194
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
195
+ padding=get_padding(kernel_size, dilation[1]))),
196
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
197
+ padding=get_padding(kernel_size, dilation[2])))
198
+ ])
199
+ self.convs1.apply(init_weights)
200
+
201
+ self.convs2 = nn.ModuleList([
202
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
203
+ padding=get_padding(kernel_size, 1))),
204
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
205
+ padding=get_padding(kernel_size, 1))),
206
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
207
+ padding=get_padding(kernel_size, 1)))
208
+ ])
209
+ self.convs2.apply(init_weights)
210
+
211
+ def forward(self, x, x_mask=None):
212
+ for c1, c2 in zip(self.convs1, self.convs2):
213
+ xt = F.leaky_relu(x, LRELU_SLOPE)
214
+ if x_mask is not None:
215
+ xt = xt * x_mask
216
+ xt = c1(xt)
217
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
218
+ if x_mask is not None:
219
+ xt = xt * x_mask
220
+ xt = c2(xt)
221
+ x = xt + x
222
+ if x_mask is not None:
223
+ x = x * x_mask
224
+ return x
225
+
226
+ def remove_weight_norm(self):
227
+ for l in self.convs1:
228
+ remove_weight_norm(l)
229
+ for l in self.convs2:
230
+ remove_weight_norm(l)
231
+
232
+
233
+ class ResBlock2(torch.nn.Module):
234
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
235
+ super(ResBlock2, self).__init__()
236
+ self.convs = nn.ModuleList([
237
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
238
+ padding=get_padding(kernel_size, dilation[0]))),
239
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
240
+ padding=get_padding(kernel_size, dilation[1])))
241
+ ])
242
+ self.convs.apply(init_weights)
243
+
244
+ def forward(self, x, x_mask=None):
245
+ for c in self.convs:
246
+ xt = F.leaky_relu(x, LRELU_SLOPE)
247
+ if x_mask is not None:
248
+ xt = xt * x_mask
249
+ xt = c(xt)
250
+ x = xt + x
251
+ if x_mask is not None:
252
+ x = x * x_mask
253
+ return x
254
+
255
+ def remove_weight_norm(self):
256
+ for l in self.convs:
257
+ remove_weight_norm(l)
258
+
259
+
260
+ class Log(nn.Module):
261
+ def forward(self, x, x_mask, reverse=False, **kwargs):
262
+ if not reverse:
263
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
264
+ logdet = torch.sum(-y, [1, 2])
265
+ return y, logdet
266
+ else:
267
+ x = torch.exp(x) * x_mask
268
+ return x
269
+
270
+
271
+ class Flip(nn.Module):
272
+ def forward(self, x, *args, reverse=False, **kwargs):
273
+ x = torch.flip(x, [1])
274
+ if not reverse:
275
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
276
+ return x, logdet
277
+ else:
278
+ return x
279
+
280
+
281
+ class ElementwiseAffine(nn.Module):
282
+ def __init__(self, channels):
283
+ super().__init__()
284
+ self.channels = channels
285
+ self.m = nn.Parameter(torch.zeros(channels,1))
286
+ self.logs = nn.Parameter(torch.zeros(channels,1))
287
+
288
+ def forward(self, x, x_mask, reverse=False, **kwargs):
289
+ if not reverse:
290
+ y = self.m + torch.exp(self.logs) * x
291
+ y = y * x_mask
292
+ logdet = torch.sum(self.logs * x_mask, [1,2])
293
+ return y, logdet
294
+ else:
295
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
296
+ return x
297
+
298
+
299
+ class ResidualCouplingLayer(nn.Module):
300
+ def __init__(self,
301
+ channels,
302
+ hidden_channels,
303
+ kernel_size,
304
+ dilation_rate,
305
+ n_layers,
306
+ p_dropout=0,
307
+ gin_channels=0,
308
+ mean_only=False):
309
+ assert channels % 2 == 0, "channels should be divisible by 2"
310
+ super().__init__()
311
+ self.channels = channels
312
+ self.hidden_channels = hidden_channels
313
+ self.kernel_size = kernel_size
314
+ self.dilation_rate = dilation_rate
315
+ self.n_layers = n_layers
316
+ self.half_channels = channels // 2
317
+ self.mean_only = mean_only
318
+
319
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
320
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
321
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
322
+ self.post.weight.data.zero_()
323
+ self.post.bias.data.zero_()
324
+
325
+ def forward(self, x, x_mask, g=None, reverse=False):
326
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
327
+ h = self.pre(x0) * x_mask
328
+ h = self.enc(h, x_mask, g=g)
329
+ stats = self.post(h) * x_mask
330
+ if not self.mean_only:
331
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
332
+ else:
333
+ m = stats
334
+ logs = torch.zeros_like(m)
335
+
336
+ if not reverse:
337
+ x1 = m + x1 * torch.exp(logs) * x_mask
338
+ x = torch.cat([x0, x1], 1)
339
+ logdet = torch.sum(logs, [1,2])
340
+ return x, logdet
341
+ else:
342
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
343
+ x = torch.cat([x0, x1], 1)
344
+ return x
345
+
346
+
347
+ class ConvFlow(nn.Module):
348
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
349
+ super().__init__()
350
+ self.in_channels = in_channels
351
+ self.filter_channels = filter_channels
352
+ self.kernel_size = kernel_size
353
+ self.n_layers = n_layers
354
+ self.num_bins = num_bins
355
+ self.tail_bound = tail_bound
356
+ self.half_channels = in_channels // 2
357
+
358
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
359
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
360
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
361
+ self.proj.weight.data.zero_()
362
+ self.proj.bias.data.zero_()
363
+
364
+ def forward(self, x, x_mask, g=None, reverse=False):
365
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
366
+ h = self.pre(x0)
367
+ h = self.convs(h, x_mask, g=g)
368
+ h = self.proj(h) * x_mask
369
+
370
+ b, c, t = x0.shape
371
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
372
+
373
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
374
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
375
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
376
+
377
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
378
+ unnormalized_widths,
379
+ unnormalized_heights,
380
+ unnormalized_derivatives,
381
+ inverse=reverse,
382
+ tails='linear',
383
+ tail_bound=self.tail_bound
384
+ )
385
+
386
+ x = torch.cat([x0, x1], 1) * x_mask
387
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
388
+ if not reverse:
389
+ return x, logdet
390
+ else:
391
+ return x
tts/preprocess.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import text
3
+ from .utils import load_filepaths_and_text
4
+
5
+ if __name__ == '__main__':
6
+ parser = argparse.ArgumentParser()
7
+ parser.add_argument("--out_extension", default="cleaned")
8
+ parser.add_argument("--text_index", default=1, type=int)
9
+ parser.add_argument("--filelists", nargs="+", default=["filelists/ljs_audio_text_val_filelist.txt", "filelists/ljs_audio_text_test_filelist.txt"])
10
+ parser.add_argument("--text_cleaners", nargs="+", default=["english_cleaners2"])
11
+
12
+ args = parser.parse_args()
13
+
14
+
15
+ for filelist in args.filelists:
16
+ print("START:", filelist)
17
+ filepaths_and_text = load_filepaths_and_text(filelist)
18
+ for i in range(len(filepaths_and_text)):
19
+ original_text = filepaths_and_text[i][args.text_index]
20
+ cleaned_text = text._clean_text(original_text, args.text_cleaners)
21
+ filepaths_and_text[i][args.text_index] = cleaned_text
22
+
23
+ new_filelist = filelist + "." + args.out_extension
24
+ with open(new_filelist, "w", encoding="utf-8") as f:
25
+ f.writelines(["|".join(x) + "\n" for x in filepaths_and_text])
tts/transforms.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ constant = np.log(np.exp(1 - min_derivative) - 1)
74
+ unnormalized_derivatives[..., 0] = constant
75
+ unnormalized_derivatives[..., -1] = constant
76
+
77
+ outputs[outside_interval_mask] = inputs[outside_interval_mask]
78
+ logabsdet[outside_interval_mask] = 0
79
+ else:
80
+ raise RuntimeError('{} tails are not implemented.'.format(tails))
81
+
82
+ outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(
83
+ inputs=inputs[inside_interval_mask],
84
+ unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
85
+ unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
86
+ unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
87
+ inverse=inverse,
88
+ left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,
89
+ min_bin_width=min_bin_width,
90
+ min_bin_height=min_bin_height,
91
+ min_derivative=min_derivative
92
+ )
93
+
94
+ return outputs, logabsdet
95
+
96
+ def rational_quadratic_spline(inputs,
97
+ unnormalized_widths,
98
+ unnormalized_heights,
99
+ unnormalized_derivatives,
100
+ inverse=False,
101
+ left=0., right=1., bottom=0., top=1.,
102
+ min_bin_width=DEFAULT_MIN_BIN_WIDTH,
103
+ min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
104
+ min_derivative=DEFAULT_MIN_DERIVATIVE):
105
+ if torch.min(inputs) < left or torch.max(inputs) > right:
106
+ raise ValueError('Input to a transform is not within its domain')
107
+
108
+ num_bins = unnormalized_widths.shape[-1]
109
+
110
+ if min_bin_width * num_bins > 1.0:
111
+ raise ValueError('Minimal bin width too large for the number of bins')
112
+ if min_bin_height * num_bins > 1.0:
113
+ raise ValueError('Minimal bin height too large for the number of bins')
114
+
115
+ widths = F.softmax(unnormalized_widths, dim=-1)
116
+ widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
117
+ cumwidths = torch.cumsum(widths, dim=-1)
118
+ cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)
119
+ cumwidths = (right - left) * cumwidths + left
120
+ cumwidths[..., 0] = left
121
+ cumwidths[..., -1] = right
122
+ widths = cumwidths[..., 1:] - cumwidths[..., :-1]
123
+
124
+ derivatives = min_derivative + F.softplus(unnormalized_derivatives)
125
+
126
+ heights = F.softmax(unnormalized_heights, dim=-1)
127
+ heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
128
+ cumheights = torch.cumsum(heights, dim=-1)
129
+ cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)
130
+ cumheights = (top - bottom) * cumheights + bottom
131
+ cumheights[..., 0] = bottom
132
+ cumheights[..., -1] = top
133
+ heights = cumheights[..., 1:] - cumheights[..., :-1]
134
+
135
+ if inverse:
136
+ bin_idx = searchsorted(cumheights, inputs)[..., None]
137
+ else:
138
+ bin_idx = searchsorted(cumwidths, inputs)[..., None]
139
+
140
+ input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
141
+ input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
142
+
143
+ input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
144
+ delta = heights / widths
145
+ input_delta = delta.gather(-1, bin_idx)[..., 0]
146
+
147
+ input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
148
+ input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
149
+
150
+ input_heights = heights.gather(-1, bin_idx)[..., 0]
151
+
152
+ if inverse:
153
+ a = (((inputs - input_cumheights) * (input_derivatives
154
+ + input_derivatives_plus_one
155
+ - 2 * input_delta)
156
+ + input_heights * (input_delta - input_derivatives)))
157
+ b = (input_heights * input_derivatives
158
+ - (inputs - input_cumheights) * (input_derivatives
159
+ + input_derivatives_plus_one
160
+ - 2 * input_delta))
161
+ c = - input_delta * (inputs - input_cumheights)
162
+
163
+ discriminant = b.pow(2) - 4 * a * c
164
+ assert (discriminant >= 0).all()
165
+
166
+ root = (2 * c) / (-b - torch.sqrt(discriminant))
167
+ outputs = root * input_bin_widths + input_cumwidths
168
+
169
+ theta_one_minus_theta = root * (1 - root)
170
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
171
+ * theta_one_minus_theta)
172
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)
173
+ + 2 * input_delta * theta_one_minus_theta
174
+ + input_derivatives * (1 - root).pow(2))
175
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
176
+
177
+ return outputs, -logabsdet
178
+ else:
179
+ theta = (inputs - input_cumwidths) / input_bin_widths
180
+ theta_one_minus_theta = theta * (1 - theta)
181
+
182
+ numerator = input_heights * (input_delta * theta.pow(2)
183
+ + input_derivatives * theta_one_minus_theta)
184
+ denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)
185
+ * theta_one_minus_theta)
186
+ outputs = input_cumheights + numerator / denominator
187
+
188
+ derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)
189
+ + 2 * input_delta * theta_one_minus_theta
190
+ + input_derivatives * (1 - theta).pow(2))
191
+ logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
192
+
193
+ return outputs, logabsdet
tts/utils.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import sys
4
+ import argparse
5
+ import logging
6
+ import json
7
+ import subprocess
8
+ import numpy as np
9
+ from scipy.io.wavfile import read
10
+ import torch
11
+
12
+ MATPLOTLIB_FLAG = False
13
+
14
+ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
15
+ logger = logging
16
+
17
+ def load_checkpoint(checkpoint_path, model, optimizer=None):
18
+ assert os.path.isfile(checkpoint_path)
19
+ checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
20
+ iteration = checkpoint_dict['iteration']
21
+ learning_rate = checkpoint_dict['learning_rate']
22
+ if optimizer is not None:
23
+ optimizer.load_state_dict(checkpoint_dict['optimizer'])
24
+ saved_state_dict = checkpoint_dict['model']
25
+ if hasattr(model, 'module'):
26
+ state_dict = model.module.state_dict()
27
+ else:
28
+ state_dict = model.state_dict()
29
+ new_state_dict= {}
30
+ for k, v in state_dict.items():
31
+ try:
32
+ new_state_dict[k] = saved_state_dict[k]
33
+ except:
34
+ logger.info("%s is not in the checkpoint" % k)
35
+ new_state_dict[k] = v
36
+ if hasattr(model, 'module'):
37
+ model.module.load_state_dict(new_state_dict)
38
+ else:
39
+ model.load_state_dict(new_state_dict)
40
+ logger.info("Loaded checkpoint '{}' (iteration {})" .format(
41
+ checkpoint_path, iteration))
42
+ return model, optimizer, learning_rate, iteration
43
+
44
+
45
+ def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
46
+ logger.info("Saving model and optimizer state at iteration {} to {}".format(
47
+ iteration, checkpoint_path))
48
+ if hasattr(model, 'module'):
49
+ state_dict = model.module.state_dict()
50
+ else:
51
+ state_dict = model.state_dict()
52
+ torch.save({'model': state_dict,
53
+ 'iteration': iteration,
54
+ 'optimizer': optimizer.state_dict(),
55
+ 'learning_rate': learning_rate}, checkpoint_path)
56
+
57
+
58
+ def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
59
+ for k, v in scalars.items():
60
+ writer.add_scalar(k, v, global_step)
61
+ for k, v in histograms.items():
62
+ writer.add_histogram(k, v, global_step)
63
+ for k, v in images.items():
64
+ writer.add_image(k, v, global_step, dataformats='HWC')
65
+ for k, v in audios.items():
66
+ writer.add_audio(k, v, global_step, audio_sampling_rate)
67
+
68
+
69
+ def latest_checkpoint_path(dir_path, regex="G_*.pth"):
70
+ f_list = glob.glob(os.path.join(dir_path, regex))
71
+ f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
72
+ x = f_list[-1]
73
+ print(x)
74
+ return x
75
+
76
+
77
+ def plot_spectrogram_to_numpy(spectrogram):
78
+ global MATPLOTLIB_FLAG
79
+ if not MATPLOTLIB_FLAG:
80
+ import matplotlib
81
+ matplotlib.use("Agg")
82
+ MATPLOTLIB_FLAG = True
83
+ mpl_logger = logging.getLogger('matplotlib')
84
+ mpl_logger.setLevel(logging.WARNING)
85
+ import matplotlib.pylab as plt
86
+ import numpy as np
87
+
88
+ fig, ax = plt.subplots(figsize=(10,2))
89
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower",
90
+ interpolation='none')
91
+ plt.colorbar(im, ax=ax)
92
+ plt.xlabel("Frames")
93
+ plt.ylabel("Channels")
94
+ plt.tight_layout()
95
+
96
+ fig.canvas.draw()
97
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
98
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
99
+ plt.close()
100
+ return data
101
+
102
+
103
+ def plot_alignment_to_numpy(alignment, info=None):
104
+ global MATPLOTLIB_FLAG
105
+ if not MATPLOTLIB_FLAG:
106
+ import matplotlib
107
+ matplotlib.use("Agg")
108
+ MATPLOTLIB_FLAG = True
109
+ mpl_logger = logging.getLogger('matplotlib')
110
+ mpl_logger.setLevel(logging.WARNING)
111
+ import matplotlib.pylab as plt
112
+ import numpy as np
113
+
114
+ fig, ax = plt.subplots(figsize=(6, 4))
115
+ im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
116
+ interpolation='none')
117
+ fig.colorbar(im, ax=ax)
118
+ xlabel = 'Decoder timestep'
119
+ if info is not None:
120
+ xlabel += '\n\n' + info
121
+ plt.xlabel(xlabel)
122
+ plt.ylabel('Encoder timestep')
123
+ plt.tight_layout()
124
+
125
+ fig.canvas.draw()
126
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
127
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
128
+ plt.close()
129
+ return data
130
+
131
+
132
+ def load_wav_to_torch(full_path):
133
+ sampling_rate, data = read(full_path)
134
+ return torch.FloatTensor(data.astype(np.float32)), sampling_rate
135
+
136
+
137
+ def load_filepaths_and_text(filename, split="|"):
138
+ with open(filename, encoding='utf-8') as f:
139
+ filepaths_and_text = [line.strip().split(split) for line in f]
140
+ return filepaths_and_text
141
+
142
+
143
+ def get_hparams(init=True):
144
+ parser = argparse.ArgumentParser()
145
+ parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
146
+ help='JSON file for configuration')
147
+ parser.add_argument('-m', '--model', type=str, required=True,
148
+ help='Model name')
149
+
150
+ args = parser.parse_args()
151
+ model_dir = os.path.join("./logs", args.model)
152
+
153
+ if not os.path.exists(model_dir):
154
+ os.makedirs(model_dir)
155
+
156
+ config_path = args.config
157
+ config_save_path = os.path.join(model_dir, "config.json")
158
+ if init:
159
+ with open(config_path, "r") as f:
160
+ data = f.read()
161
+ with open(config_save_path, "w") as f:
162
+ f.write(data)
163
+ else:
164
+ with open(config_save_path, "r") as f:
165
+ data = f.read()
166
+ config = json.loads(data)
167
+
168
+ hparams = HParams(**config)
169
+ hparams.model_dir = model_dir
170
+ return hparams
171
+
172
+
173
+ def get_hparams_from_dir(model_dir):
174
+ config_save_path = os.path.join(model_dir, "config.json")
175
+ with open(config_save_path, "r") as f:
176
+ data = f.read()
177
+ config = json.loads(data)
178
+
179
+ hparams =HParams(**config)
180
+ hparams.model_dir = model_dir
181
+ return hparams
182
+
183
+
184
+ def get_hparams_from_file(config_path):
185
+ with open(config_path, "r") as f:
186
+ data = f.read()
187
+ config = json.loads(data)
188
+
189
+ hparams =HParams(**config)
190
+ return hparams
191
+
192
+
193
+ def check_git_hash(model_dir):
194
+ source_dir = os.path.dirname(os.path.realpath(__file__))
195
+ if not os.path.exists(os.path.join(source_dir, ".git")):
196
+ logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
197
+ source_dir
198
+ ))
199
+ return
200
+
201
+ cur_hash = subprocess.getoutput("git rev-parse HEAD")
202
+
203
+ path = os.path.join(model_dir, "githash")
204
+ if os.path.exists(path):
205
+ saved_hash = open(path).read()
206
+ if saved_hash != cur_hash:
207
+ logger.warn("git hash values are different. {}(saved) != {}(current)".format(
208
+ saved_hash[:8], cur_hash[:8]))
209
+ else:
210
+ open(path, "w").write(cur_hash)
211
+
212
+
213
+ def get_logger(model_dir, filename="train.log"):
214
+ global logger
215
+ logger = logging.getLogger(os.path.basename(model_dir))
216
+ logger.setLevel(logging.DEBUG)
217
+
218
+ formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
219
+ if not os.path.exists(model_dir):
220
+ os.makedirs(model_dir)
221
+ h = logging.FileHandler(os.path.join(model_dir, filename))
222
+ h.setLevel(logging.DEBUG)
223
+ h.setFormatter(formatter)
224
+ logger.addHandler(h)
225
+ return logger
226
+
227
+
228
+ class HParams():
229
+ def __init__(self, **kwargs):
230
+ for k, v in kwargs.items():
231
+ if type(v) == dict:
232
+ v = HParams(**v)
233
+ self[k] = v
234
+
235
+ def keys(self):
236
+ return self.__dict__.keys()
237
+
238
+ def items(self):
239
+ return self.__dict__.items()
240
+
241
+ def values(self):
242
+ return self.__dict__.values()
243
+
244
+ def __len__(self):
245
+ return len(self.__dict__)
246
+
247
+ def __getitem__(self, key):
248
+ return getattr(self, key)
249
+
250
+ def __setitem__(self, key, value):
251
+ return setattr(self, key, value)
252
+
253
+ def __contains__(self, key):
254
+ return key in self.__dict__
255
+
256
+ def __repr__(self):
257
+ return self.__dict__.__repr__()
webui.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import re
4
+ import torch
5
+ import numpy as np
6
+ from scipy.io.wavfile import write
7
+ from phonemizer.backend.espeak.wrapper import EspeakWrapper
8
+ from safetensors.torch import load_file
9
+ from tts import commons
10
+ from tts import utils
11
+ from tts.models import SynthesizerTrn
12
+ from text.symbols import symbols
13
+ from text import text_to_sequence
14
+
15
+ _ESPEAK_LIBRARY = r"C:\Program Files\eSpeak NG\libespeak-ng.dll"
16
+ if os.path.exists(_ESPEAK_LIBRARY):
17
+ EspeakWrapper.set_library(_ESPEAK_LIBRARY)
18
+ print(f"✅ Found eSpeak-ng: {_ESPEAK_LIBRARY}")
19
+
20
+ MODEL_PATH = "checkpoints/sonya-tts.safetensors"
21
+ CONFIG_PATH = "checkpoints/config.json"
22
+ device = "cuda" if torch.cuda.is_available() else "cpu"
23
+
24
+
25
+ def clean_text_for_vits(text):
26
+ text = text.strip()
27
+ text = text.replace("'", "'")
28
+ text = text.replace(""", '"').replace(""", '"')
29
+ text = text.replace("–", "-").replace("—", "-")
30
+ text = re.sub(r"[()\[\]{}<>]", "", text)
31
+ text = re.sub(r"[^a-zA-Z0-9\s.,!?'\-]", "", text)
32
+ text = re.sub(r"\s+", " ", text)
33
+ return text
34
+
35
+ def get_text(text, hps):
36
+ text = clean_text_for_vits(text)
37
+ text_norm = text_to_sequence(text, hps.data.text_cleaners)
38
+ if hps.data.add_blank:
39
+ text_norm = commons.intersperse(text_norm, 0)
40
+ return torch.LongTensor(text_norm)
41
+
42
+ def split_sentences(text):
43
+ text = clean_text_for_vits(text)
44
+ if not text:
45
+ return []
46
+ return re.split(r'(?<=[.!?])\s+', text)
47
+
48
+
49
+ print("🔄 Loading Sonya TTS Model...")
50
+ hps = utils.get_hparams_from_file(CONFIG_PATH)
51
+
52
+ net_g = SynthesizerTrn(
53
+ len(symbols),
54
+ hps.data.filter_length // 2 + 1,
55
+ hps.train.segment_size // hps.data.hop_length,
56
+ **hps.model
57
+ ).to(device)
58
+
59
+ net_g.eval()
60
+
61
+ if os.path.exists(MODEL_PATH):
62
+ state_dict = load_file(MODEL_PATH, device=device)
63
+ net_g.load_state_dict(state_dict)
64
+ print(f"✅ Loaded weights from {MODEL_PATH}")
65
+ else:
66
+ raise FileNotFoundError(f"Could not find model at {MODEL_PATH}")
67
+
68
+ def infer_short(text, noise_scale, noise_scale_w, length_scale):
69
+ if not text.strip():
70
+ return None
71
+
72
+ stn_tst = get_text(text, hps)
73
+
74
+ with torch.no_grad():
75
+ x_tst = stn_tst.to(device).unsqueeze(0)
76
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(device)
77
+
78
+ audio = net_g.infer(
79
+ x_tst,
80
+ x_tst_lengths,
81
+ noise_scale=noise_scale,
82
+ noise_scale_w=noise_scale_w,
83
+ length_scale=length_scale
84
+ )[0][0,0].data.cpu().float().numpy()
85
+
86
+ return (hps.data.sampling_rate, audio)
87
+
88
+ def infer_long(text, length_scale, noise_scale):
89
+ if not text.strip():
90
+ return None
91
+
92
+ sentences = split_sentences(text)
93
+ audio_chunks = []
94
+
95
+ fixed_noise_w = 0.6
96
+ base_pause = 0.3
97
+
98
+ for sent in sentences:
99
+ if len(sent.strip()) < 2: continue
100
+
101
+ stn_tst = get_text(sent, hps)
102
+ with torch.no_grad():
103
+ x_tst = stn_tst.to(device).unsqueeze(0)
104
+ x_tst_lengths = torch.LongTensor([stn_tst.size(0)]).to(device)
105
+
106
+ audio = net_g.infer(
107
+ x_tst,
108
+ x_tst_lengths,
109
+ noise_scale=noise_scale,
110
+ noise_scale_w=fixed_noise_w,
111
+ length_scale=length_scale
112
+ )[0][0,0].data.cpu().float().numpy()
113
+
114
+ if sent.endswith("?"):
115
+ pause_dur = base_pause + 0.2
116
+ elif sent.endswith("!"):
117
+ pause_dur = base_pause + 0.1
118
+ else:
119
+ pause_dur = base_pause
120
+
121
+ silence = np.zeros(int(hps.data.sampling_rate * pause_dur))
122
+
123
+ audio_chunks.append(audio)
124
+ audio_chunks.append(silence)
125
+
126
+ final_audio = np.concatenate(audio_chunks)
127
+ return (hps.data.sampling_rate, final_audio)
128
+
129
+
130
+ theme = gr.themes.Soft(
131
+ primary_hue="pink",
132
+ secondary_hue="rose",
133
+ neutral_hue="slate"
134
+ ).set(
135
+ button_primary_background_fill="linear-gradient(90deg, #ff69b4, #ff1493)",
136
+ button_primary_background_fill_hover="linear-gradient(90deg, #ff1493, #c71585)",
137
+ button_primary_text_color="white",
138
+ )
139
+
140
+ custom_css = """
141
+ .banner-container {
142
+ width: 100%;
143
+ max-width: 100%;
144
+ margin: 0 auto 20px auto;
145
+ display: flex;
146
+ justify-content: center;
147
+ align-items: center;
148
+ }
149
+
150
+ .banner-container img {
151
+ width: 100%;
152
+ max-width: 1800px;
153
+ max-height: 120px;
154
+ height: auto;
155
+ object-fit: scale-down;
156
+ object-position: center;
157
+ border-radius: 8px;
158
+ }
159
+
160
+ .main-title {
161
+ text-align: center;
162
+ color: #ff1493;
163
+ font-size: 2em;
164
+ font-weight: 700;
165
+ margin: 15px 0 8px 0;
166
+ }
167
+
168
+ .subtitle {
169
+ text-align: center;
170
+ color: white;
171
+ font-size: 1.1em;
172
+ margin-bottom: 25px;
173
+ font-weight: 400;
174
+ }
175
+
176
+ footer {
177
+ display: none !important;
178
+ }
179
+ """
180
+
181
+ with gr.Blocks(theme=theme, css=custom_css, title="Sonya TTS") as app:
182
+
183
+
184
+ with gr.Row(elem_classes="banner-container"):
185
+ if os.path.exists("logo.png"):
186
+ gr.Image("logo.png", show_label=False, container=False, elem_classes="banner-img")
187
+
188
+
189
+ gr.HTML("""
190
+ <h1 class="main-title">✨ Sonya TTS — A Beautiful, Expressive Neural Voice Engine</h1>
191
+ <p class="subtitle">High-fidelity AI speech with emotion, rhythm, and audiobook mode</p>
192
+ """)
193
+
194
+ with gr.Tabs():
195
+
196
+
197
+ with gr.TabItem("🎛️ Studio Mode"):
198
+ with gr.Row():
199
+ with gr.Column(scale=2):
200
+ inp_short = gr.Textbox(
201
+ label="💬 Input Text",
202
+ placeholder="Type something for Sonya to say...",
203
+ lines=4,
204
+ value="Hello! I am Sonya, your AI voice."
205
+ )
206
+
207
+ with gr.Accordion("⚙️ Voice Controls", open=True):
208
+ slider_ns = gr.Slider(0.1, 1.0, value=0.4, label="🎭 Emotion", info="Higher = more expressive")
209
+ slider_nsw = gr.Slider(0.1, 1.0, value=0.5, label="🎵 Rhythm", info="Higher = looser timing")
210
+ slider_ls = gr.Slider(0.5, 1.5, value=0.97, label="⏱ Speed", info="Lower = faster, Higher = slower")
211
+
212
+ btn_short = gr.Button("✨ Generate Voice", variant="primary", size="lg")
213
+
214
+ with gr.Column(scale=1):
215
+ out_short = gr.Audio(label="🔊 Sonya's Voice", type="numpy")
216
+
217
+ btn_short.click(
218
+ infer_short,
219
+ inputs=[inp_short, slider_ns, slider_nsw, slider_ls],
220
+ outputs=[out_short]
221
+ )
222
+
223
+
224
+ with gr.TabItem("📖 Audiobook Mode"):
225
+ gr.Markdown(
226
+ """<p style='text-align: center; color: #666; font-size: 1.05em;'>
227
+ Paste long text. Sonya will read it beautifully with natural pauses.
228
+ </p>""",
229
+ elem_classes="audiobook-description"
230
+ )
231
+
232
+ with gr.Row():
233
+ with gr.Column(scale=2):
234
+ inp_long = gr.Textbox(
235
+ label="📜 Long Text Input",
236
+ placeholder="Paste your story or article here...",
237
+ lines=10
238
+ )
239
+
240
+ with gr.Accordion("⚙️ Narration Settings", open=False):
241
+ long_ls = gr.Slider(0.5, 1.5, value=1.0, label="⏱ Reading Speed")
242
+ long_ns = gr.Slider(0.1, 1.0, value=0.5, label="🎭 Tone Variation")
243
+
244
+ btn_long = gr.Button("🎧 Read Aloud", variant="primary", size="lg")
245
+
246
+ with gr.Column(scale=1):
247
+ out_long = gr.Audio(label="📢 Full Narration", type="numpy")
248
+
249
+ btn_long.click(
250
+ infer_long,
251
+ inputs=[inp_long, long_ls, long_ns],
252
+ outputs=[out_long]
253
+ )
254
+
255
+ if __name__ == "__main__":
256
+ app.launch()