w11wo commited on
Commit
11120b4
1 Parent(s): 408d582

added demo

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Grad-TTS/LICENSE +19 -0
  2. Grad-TTS/README.md +74 -0
  3. Grad-TTS/THIRD_PARTY_NOTICE +75 -0
  4. Grad-TTS/checkpts/hifigan-config.json +38 -0
  5. Grad-TTS/data.py +186 -0
  6. Grad-TTS/finetune_multi_speaker.py +237 -0
  7. Grad-TTS/finetune_params.py +56 -0
  8. Grad-TTS/hifi-gan/LICENSE +21 -0
  9. Grad-TTS/hifi-gan/README.md +105 -0
  10. Grad-TTS/hifi-gan/env.py +17 -0
  11. Grad-TTS/hifi-gan/meldataset.py +170 -0
  12. Grad-TTS/hifi-gan/models.py +285 -0
  13. Grad-TTS/hifi-gan/xutils.py +60 -0
  14. Grad-TTS/inference.ipynb +199 -0
  15. Grad-TTS/inference.py +85 -0
  16. Grad-TTS/model/__init__.py +9 -0
  17. Grad-TTS/model/base.py +37 -0
  18. Grad-TTS/model/diffusion.py +294 -0
  19. Grad-TTS/model/monotonic_align/LICENCE +21 -0
  20. Grad-TTS/model/monotonic_align/__init__.py +23 -0
  21. Grad-TTS/model/monotonic_align/core.pyx +45 -0
  22. Grad-TTS/model/monotonic_align/setup.py +11 -0
  23. Grad-TTS/model/text_encoder.py +326 -0
  24. Grad-TTS/model/tts.py +181 -0
  25. Grad-TTS/model/utils.py +44 -0
  26. Grad-TTS/out/sample_0.wav +0 -0
  27. Grad-TTS/out/sample_1.wav +0 -0
  28. Grad-TTS/out/sample_2.wav +0 -0
  29. Grad-TTS/params.py +54 -0
  30. Grad-TTS/params_en.py +54 -0
  31. Grad-TTS/requirements.txt +12 -0
  32. Grad-TTS/resources/cmu_dictionary +0 -0
  33. Grad-TTS/resources/cmu_dictionary_id +0 -0
  34. Grad-TTS/resources/cmu_dictionary_id_en +0 -0
  35. Grad-TTS/resources/filelists/libri-tts/train.txt +0 -0
  36. Grad-TTS/resources/filelists/libri-tts/valid.txt +4 -0
  37. Grad-TTS/resources/filelists/ljspeech/test.txt +488 -0
  38. Grad-TTS/resources/filelists/ljspeech/train.txt +0 -0
  39. Grad-TTS/resources/filelists/ljspeech/valid.txt +95 -0
  40. Grad-TTS/resources/filelists/synthesis.txt +3 -0
  41. Grad-TTS/resources/ipa_dictionary_id +0 -0
  42. Grad-TTS/text/LICENSE +30 -0
  43. Grad-TTS/text/__init__.py +96 -0
  44. Grad-TTS/text/cleaners.py +73 -0
  45. Grad-TTS/text/cmudict.py +60 -0
  46. Grad-TTS/text/numbers.py +72 -0
  47. Grad-TTS/text/symbols.py +14 -0
  48. Grad-TTS/train.py +177 -0
  49. Grad-TTS/train_multi_speaker.py +182 -0
  50. Grad-TTS/utils.py +75 -0
Grad-TTS/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2021 Huawei Technologies Co., Ltd.
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 all
11
+ 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 THE
19
+ SOFTWARE.
Grad-TTS/README.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <img src="resources/reverse-diffusion.gif" alt="drawing" width="500"/>
3
+ </p>
4
+
5
+
6
+ # Grad-TTS
7
+
8
+ Official implementation of the Grad-TTS model based on Diffusion Probabilistic Modelling. For all details check out our paper accepted to ICML 2021 via [this](https://arxiv.org/abs/2105.06337) link.
9
+
10
+ **Authors**: Vadim Popov\*, Ivan Vovk\*, Vladimir Gogoryan, Tasnima Sadekova, Mikhail Kudinov.
11
+
12
+ <sup>\*Equal contribution.</sup>
13
+
14
+ ## Abstract
15
+
16
+ **Demo page** with voiced abstract: [link](https://grad-tts.github.io/).
17
+
18
+ Recently, denoising diffusion probabilistic models and generative score matching have shown high potential in modelling complex data distributions while stochastic calculus has provided a unified point of view on these techniques allowing for flexible inference schemes. In this paper we introduce Grad-TTS, a novel text-to-speech model with score-based decoder producing mel-spectrograms by gradually transforming noise predicted by encoder and aligned with text input by means of Monotonic Alignment Search. The framework of stochastic differential equations helps us to generalize conventional diffusion probabilistic models to the case of reconstructing data from noise with different parameters and allows to make this reconstruction flexible by explicitly controlling trade-off between sound quality and inference speed. Subjective human evaluation shows that Grad-TTS is competitive with state-of-the-art text-to-speech approaches in terms of Mean Opinion Score.
19
+
20
+ ## Installation
21
+
22
+ Firstly, install all Python package requirements:
23
+
24
+ ```bash
25
+ pip install -r requirements.txt
26
+ ```
27
+
28
+ Secondly, build `monotonic_align` code (Cython):
29
+
30
+ ```bash
31
+ cd model/monotonic_align; python setup.py build_ext --inplace; cd ../..
32
+ ```
33
+
34
+ **Note**: code is tested on Python==3.6.9.
35
+
36
+ ## Inference
37
+
38
+ You can download Grad-TTS and HiFi-GAN checkpoints trained on LJSpeech* and Libri-TTS datasets (22kHz) from [here](https://drive.google.com/drive/folders/1grsfccJbmEuSBGQExQKr3cVxNV0xEOZ7?usp=sharing).
39
+
40
+ ***Note**: we open-source 2 checkpoints of Grad-TTS trained on LJSpeech. They are the same models but trained with different positional encoding scale: **x1** (`"grad-tts-old.pt"`, ICML 2021 sumbission model) and **x1000** (`"grad-tts.pt"`). To use the former set `params.pe_scale=1` and to use the latter set `params.pe_scale=1000`. Libri-TTS checkpoint was trained with scale **x1000**.
41
+
42
+ Put necessary Grad-TTS and HiFi-GAN checkpoints into `checkpts` folder in root Grad-TTS directory (note: in `inference.py` you can change default HiFi-GAN path).
43
+
44
+ 1. Create text file with sentences you want to synthesize like `resources/filelists/synthesis.txt`.
45
+ 2. For single speaker set `params.n_spks=1` and for multispeaker (Libri-TTS) inference set `params.n_spks=247`.
46
+ 3. Run script `inference.py` by providing path to the text file, path to the Grad-TTS checkpoint, number of iterations to be used for reverse diffusion (default: 10) and speaker id if you want to perform multispeaker inference:
47
+ ```bash
48
+ python inference.py -f <your-text-file> -c <grad-tts-checkpoint> -t <number-of-timesteps> -s <speaker-id-if-multispeaker>
49
+ ```
50
+ 4. Check out folder called `out` for generated audios.
51
+
52
+ You can also perform *interactive inference* by running Jupyter Notebook `inference.ipynb` or by using our [Google Colab Demo](https://colab.research.google.com/drive/1YNrXtkJQKcYDmIYJeyX8s5eXxB4zgpZI?usp=sharing).
53
+
54
+ ## Training
55
+
56
+ 1. Make filelists of your audio data like ones included into `resources/filelists` folder. For single speaker training refer to `jspeech` filelists and to `libri-tts` filelists for multispeaker.
57
+ 2. Set experiment configuration in `params.py` file.
58
+ 3. Specify your GPU device and run training script:
59
+ ```bash
60
+ export CUDA_VISIBLE_DEVICES=YOUR_GPU_ID
61
+ python train.py # if single speaker
62
+ python train_multi_speaker.py # if multispeaker
63
+ ```
64
+ 4. To track your training process run tensorboard server on any available port:
65
+ ```bash
66
+ tensorboard --logdir=YOUR_LOG_DIR --port=8888
67
+ ```
68
+ During training all logging information and checkpoints are stored in `YOUR_LOG_DIR`, which you can specify in `params.py` before training.
69
+
70
+ ## References
71
+
72
+ * HiFi-GAN model is used as vocoder, official github repository: [link](https://github.com/jik876/hifi-gan).
73
+ * Monotonic Alignment Search algorithm is used for unsupervised duration modelling, official github repository: [link](https://github.com/jaywalnut310/glow-tts).
74
+ * Phonemization utilizes CMUdict, official github repository: [link](https://github.com/cmusphinx/cmudict).
Grad-TTS/THIRD_PARTY_NOTICE ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Please note we provide an open source software notice for the third party
2
+ open source software along with this software and/or this software component
3
+ contributed by Huawei (in the following just “this SOFTWARE”). The open source
4
+ software licenses are granted by the respective right holders.
5
+
6
+ WARRANTY DISCLAIMER
7
+ THE OPEN SOURCE SOFTWARE IN THIS SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL
8
+ BE USEFUL, BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
9
+ MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES
10
+ FOR MORE DETAILS.
11
+
12
+ COPYRIGHT NOTICE AND LICENSE TEXTS
13
+
14
+ SOFTWARE: HiFi-GAN
15
+ Copyright (c) 2020 Jungil Kong <henry.k@kakaoenterprise.com>
16
+ License: MIT
17
+ Permission is hereby granted, free of charge, to any person obtaining a copy
18
+ of this software and associated documentation files (the "Software"), to deal
19
+ in the Software without restriction, including without limitation the rights
20
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21
+ copies of the Software, and to permit persons to whom the Software is
22
+ furnished to do so, subject to the following conditions:
23
+
24
+ The above copyright notice and this permission notice shall be included in all
25
+ copies or substantial portions of the Software.
26
+
27
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33
+ SOFTWARE.
34
+
35
+ SOFTWARE: GLOW-TTS
36
+ Copyright (c) 2020 Jaehyeon Kim <jay.xyz@kakaoenterprise.com>
37
+ License: MIT
38
+ Text: See above
39
+
40
+ SOFTWARE: CMUDict
41
+ Copyright (C) 1993-2015 Carnegie Mellon University <air+cmudict@cs.cmu.edu>
42
+ License text
43
+ Copyright (C) 1993-2015 Carnegie Mellon University. All rights reserved.
44
+
45
+ Redistribution and use in source and binary forms, with or without
46
+ modification, are permitted provided that the following conditions
47
+ are met:
48
+
49
+ 1. Redistributions of source code must retain the above copyright
50
+ notice, this list of conditions and the following disclaimer.
51
+ The contents of this file are deemed to be source code.
52
+
53
+ 2. Redistributions in binary form must reproduce the above copyright
54
+ notice, this list of conditions and the following disclaimer in
55
+ the documentation and/or other materials provided with the
56
+ distribution.
57
+
58
+ This work was supported in part by funding from the Defense Advanced
59
+ Research Projects Agency, the Office of Naval Research and the National
60
+ Science Foundation of the United States of America, and by member
61
+ companies of the Carnegie Mellon Sphinx Speech Consortium. We acknowledge
62
+ the contributions of many volunteers to the expansion and improvement of
63
+ this dictionary.
64
+
65
+ THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
66
+ ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
67
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
68
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
69
+ NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
70
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
71
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
72
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
73
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
74
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
75
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Grad-TTS/checkpts/hifigan-config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "resblock": "1",
3
+ "num_gpus": 0,
4
+ "batch_size": 16,
5
+ "learning_rate": 0.0004,
6
+ "adam_b1": 0.8,
7
+ "adam_b2": 0.99,
8
+ "lr_decay": 0.999,
9
+ "seed": 1234,
10
+
11
+ "upsample_rates": [8,8,2,2],
12
+ "upsample_kernel_sizes": [16,16,4,4],
13
+ "upsample_initial_channel": 512,
14
+ "resblock_kernel_sizes": [3,7,11],
15
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
16
+ "resblock_initial_channel": 256,
17
+
18
+ "segment_size": 8192,
19
+ "num_mels": 80,
20
+ "num_freq": 1025,
21
+ "n_fft": 1024,
22
+ "hop_size": 256,
23
+ "win_size": 1024,
24
+
25
+ "sampling_rate": 22050,
26
+
27
+ "fmin": 0,
28
+ "fmax": 8000,
29
+ "fmax_loss": null,
30
+
31
+ "num_workers": 4,
32
+
33
+ "dist_config": {
34
+ "dist_backend": "nccl",
35
+ "dist_url": "tcp://localhost:54321",
36
+ "world_size": 1
37
+ }
38
+ }
Grad-TTS/data.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import random
10
+ import numpy as np
11
+
12
+ import torch
13
+ import torchaudio as ta
14
+
15
+ from text import text_to_sequence, cmudict
16
+ from text.symbols import symbols
17
+ from utils import parse_filelist, intersperse
18
+ from model.utils import fix_len_compatibility
19
+ from params import seed as random_seed
20
+
21
+ import sys
22
+ sys.path.insert(0, 'hifi-gan')
23
+ from meldataset import mel_spectrogram
24
+
25
+
26
+ class TextMelDataset(torch.utils.data.Dataset):
27
+ def __init__(self, filelist_path, cmudict_path, add_blank=True,
28
+ n_fft=1024, n_mels=80, sample_rate=22050,
29
+ hop_length=256, win_length=1024, f_min=0., f_max=8000):
30
+ self.filepaths_and_text = parse_filelist(filelist_path)
31
+ self.cmudict = cmudict.CMUDict(cmudict_path)
32
+ self.add_blank = add_blank
33
+ self.n_fft = n_fft
34
+ self.n_mels = n_mels
35
+ self.sample_rate = sample_rate
36
+ self.hop_length = hop_length
37
+ self.win_length = win_length
38
+ self.f_min = f_min
39
+ self.f_max = f_max
40
+ random.seed(random_seed)
41
+ random.shuffle(self.filepaths_and_text)
42
+
43
+ def get_pair(self, filepath_and_text):
44
+ filepath, text = filepath_and_text[0], filepath_and_text[1]
45
+ text = self.get_text(text, add_blank=self.add_blank)
46
+ mel = self.get_mel(filepath)
47
+ return (text, mel)
48
+
49
+ def get_mel(self, filepath):
50
+ audio, sr = ta.load(filepath)
51
+ assert sr == self.sample_rate
52
+ mel = mel_spectrogram(audio, self.n_fft, self.n_mels, self.sample_rate, self.hop_length,
53
+ self.win_length, self.f_min, self.f_max, center=False).squeeze()
54
+ return mel
55
+
56
+ def get_text(self, text, add_blank=True):
57
+ text_norm = text_to_sequence(text, dictionary=self.cmudict)
58
+ if self.add_blank:
59
+ text_norm = intersperse(text_norm, len(symbols)) # add a blank token, whose id number is len(symbols)
60
+ text_norm = torch.IntTensor(text_norm)
61
+ return text_norm
62
+
63
+ def __getitem__(self, index):
64
+ text, mel = self.get_pair(self.filepaths_and_text[index])
65
+ item = {'y': mel, 'x': text}
66
+ return item
67
+
68
+ def __len__(self):
69
+ return len(self.filepaths_and_text)
70
+
71
+ def sample_test_batch(self, size):
72
+ idx = np.random.choice(range(len(self)), size=size, replace=False)
73
+ test_batch = []
74
+ for index in idx:
75
+ test_batch.append(self.__getitem__(index))
76
+ return test_batch
77
+
78
+
79
+ class TextMelBatchCollate(object):
80
+ def __call__(self, batch):
81
+ B = len(batch)
82
+ y_max_length = max([item['y'].shape[-1] for item in batch])
83
+ y_max_length = fix_len_compatibility(y_max_length)
84
+ x_max_length = max([item['x'].shape[-1] for item in batch])
85
+ n_feats = batch[0]['y'].shape[-2]
86
+
87
+ y = torch.zeros((B, n_feats, y_max_length), dtype=torch.float32)
88
+ x = torch.zeros((B, x_max_length), dtype=torch.long)
89
+ y_lengths, x_lengths = [], []
90
+
91
+ for i, item in enumerate(batch):
92
+ y_, x_ = item['y'], item['x']
93
+ y_lengths.append(y_.shape[-1])
94
+ x_lengths.append(x_.shape[-1])
95
+ y[i, :, :y_.shape[-1]] = y_
96
+ x[i, :x_.shape[-1]] = x_
97
+
98
+ y_lengths = torch.LongTensor(y_lengths)
99
+ x_lengths = torch.LongTensor(x_lengths)
100
+ return {'x': x, 'x_lengths': x_lengths, 'y': y, 'y_lengths': y_lengths}
101
+
102
+
103
+ class TextMelSpeakerDataset(torch.utils.data.Dataset):
104
+ def __init__(self, filelist_path, cmudict_path, add_blank=True,
105
+ n_fft=1024, n_mels=80, sample_rate=22050,
106
+ hop_length=256, win_length=1024, f_min=0., f_max=8000):
107
+ super().__init__()
108
+ self.filelist = parse_filelist(filelist_path, split_char='|')
109
+ self.cmudict = cmudict.CMUDict(cmudict_path)
110
+ self.n_fft = n_fft
111
+ self.n_mels = n_mels
112
+ self.sample_rate = sample_rate
113
+ self.hop_length = hop_length
114
+ self.win_length = win_length
115
+ self.f_min = f_min
116
+ self.f_max = f_max
117
+ self.add_blank = add_blank
118
+ random.seed(random_seed)
119
+ random.shuffle(self.filelist)
120
+
121
+ def get_triplet(self, line):
122
+ filepath, text, speaker = line[0], line[1], line[2]
123
+ text = self.get_text(text, add_blank=self.add_blank)
124
+ mel = self.get_mel(filepath)
125
+ speaker = self.get_speaker(speaker)
126
+ return (text, mel, speaker)
127
+
128
+ def get_mel(self, filepath):
129
+ audio, sr = ta.load(filepath)
130
+ assert sr == self.sample_rate
131
+ mel = mel_spectrogram(audio, self.n_fft, self.n_mels, self.sample_rate, self.hop_length,
132
+ self.win_length, self.f_min, self.f_max, center=False).squeeze()
133
+ return mel
134
+
135
+ def get_text(self, text, add_blank=True):
136
+ text_norm = text_to_sequence(text, dictionary=self.cmudict)
137
+ if self.add_blank:
138
+ text_norm = intersperse(text_norm, len(symbols)) # add a blank token, whose id number is len(symbols)
139
+ text_norm = torch.LongTensor(text_norm)
140
+ return text_norm
141
+
142
+ def get_speaker(self, speaker):
143
+ speaker = torch.LongTensor([int(speaker)])
144
+ return speaker
145
+
146
+ def __getitem__(self, index):
147
+ text, mel, speaker = self.get_triplet(self.filelist[index])
148
+ item = {'y': mel, 'x': text, 'spk': speaker}
149
+ return item
150
+
151
+ def __len__(self):
152
+ return len(self.filelist)
153
+
154
+ def sample_test_batch(self, size):
155
+ idx = np.random.choice(range(len(self)), size=size, replace=False)
156
+ test_batch = []
157
+ for index in idx:
158
+ test_batch.append(self.__getitem__(index))
159
+ return test_batch
160
+
161
+
162
+ class TextMelSpeakerBatchCollate(object):
163
+ def __call__(self, batch):
164
+ B = len(batch)
165
+ y_max_length = max([item['y'].shape[-1] for item in batch])
166
+ y_max_length = fix_len_compatibility(y_max_length)
167
+ x_max_length = max([item['x'].shape[-1] for item in batch])
168
+ n_feats = batch[0]['y'].shape[-2]
169
+
170
+ y = torch.zeros((B, n_feats, y_max_length), dtype=torch.float32)
171
+ x = torch.zeros((B, x_max_length), dtype=torch.long)
172
+ y_lengths, x_lengths = [], []
173
+ spk = []
174
+
175
+ for i, item in enumerate(batch):
176
+ y_, x_, spk_ = item['y'], item['x'], item['spk']
177
+ y_lengths.append(y_.shape[-1])
178
+ x_lengths.append(x_.shape[-1])
179
+ y[i, :, :y_.shape[-1]] = y_
180
+ x[i, :x_.shape[-1]] = x_
181
+ spk.append(spk_)
182
+
183
+ y_lengths = torch.LongTensor(y_lengths)
184
+ x_lengths = torch.LongTensor(x_lengths)
185
+ spk = torch.cat(spk, dim=0)
186
+ return {'x': x, 'x_lengths': x_lengths, 'y': y, 'y_lengths': y_lengths, 'spk': spk}
Grad-TTS/finetune_multi_speaker.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import numpy as np
10
+ from tqdm import tqdm
11
+
12
+ import torch
13
+ from torch.utils.data import DataLoader
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+ import finetune_params as params
17
+ from model import GradTTS
18
+ from data import TextMelSpeakerDataset, TextMelSpeakerBatchCollate
19
+ from utils import plot_tensor, save_plot
20
+ from text.symbols import symbols
21
+
22
+
23
+ train_filelist_path = params.train_filelist_path
24
+ valid_filelist_path = params.valid_filelist_path
25
+ cmudict_path = params.cmudict_path
26
+ add_blank = params.add_blank
27
+ n_spks = params.n_spks
28
+ spk_emb_dim = params.spk_emb_dim
29
+
30
+ log_dir = params.log_dir
31
+ n_epochs = params.n_epochs
32
+ batch_size = params.batch_size
33
+ out_size = params.out_size
34
+ learning_rate = params.learning_rate
35
+ random_seed = params.seed
36
+
37
+ nsymbols = len(symbols) + 1 if add_blank else len(symbols)
38
+ n_enc_channels = params.n_enc_channels
39
+ filter_channels = params.filter_channels
40
+ filter_channels_dp = params.filter_channels_dp
41
+ n_enc_layers = params.n_enc_layers
42
+ enc_kernel = params.enc_kernel
43
+ enc_dropout = params.enc_dropout
44
+ n_heads = params.n_heads
45
+ window_size = params.window_size
46
+
47
+ n_feats = params.n_feats
48
+ n_fft = params.n_fft
49
+ sample_rate = params.sample_rate
50
+ hop_length = params.hop_length
51
+ win_length = params.win_length
52
+ f_min = params.f_min
53
+ f_max = params.f_max
54
+
55
+ dec_dim = params.dec_dim
56
+ beta_min = params.beta_min
57
+ beta_max = params.beta_max
58
+ pe_scale = params.pe_scale
59
+
60
+ num_workers = params.num_workers
61
+ checkpoint = params.checkpoint
62
+
63
+ if __name__ == "__main__":
64
+ torch.manual_seed(random_seed)
65
+ np.random.seed(random_seed)
66
+
67
+ print("Initializing logger...")
68
+ logger = SummaryWriter(log_dir=log_dir)
69
+
70
+ print("Initializing data loaders...")
71
+ train_dataset = TextMelSpeakerDataset(
72
+ train_filelist_path,
73
+ cmudict_path,
74
+ add_blank,
75
+ n_fft,
76
+ n_feats,
77
+ sample_rate,
78
+ hop_length,
79
+ win_length,
80
+ f_min,
81
+ f_max,
82
+ )
83
+ batch_collate = TextMelSpeakerBatchCollate()
84
+ loader = DataLoader(
85
+ dataset=train_dataset,
86
+ batch_size=batch_size,
87
+ collate_fn=batch_collate,
88
+ drop_last=True,
89
+ num_workers=num_workers,
90
+ shuffle=True,
91
+ )
92
+ test_dataset = TextMelSpeakerDataset(
93
+ valid_filelist_path,
94
+ cmudict_path,
95
+ add_blank,
96
+ n_fft,
97
+ n_feats,
98
+ sample_rate,
99
+ hop_length,
100
+ win_length,
101
+ f_min,
102
+ f_max,
103
+ )
104
+
105
+ print("Initializing model...")
106
+ model = GradTTS(
107
+ nsymbols,
108
+ n_spks,
109
+ spk_emb_dim,
110
+ n_enc_channels,
111
+ filter_channels,
112
+ filter_channels_dp,
113
+ n_heads,
114
+ n_enc_layers,
115
+ enc_kernel,
116
+ enc_dropout,
117
+ window_size,
118
+ n_feats,
119
+ dec_dim,
120
+ beta_min,
121
+ beta_max,
122
+ pe_scale,
123
+ ).cuda()
124
+ model.load_state_dict(torch.load(checkpoint, map_location=torch.device("cuda")))
125
+ print("Number of encoder parameters = %.2fm" % (model.encoder.nparams / 1e6))
126
+ print("Number of decoder parameters = %.2fm" % (model.decoder.nparams / 1e6))
127
+
128
+ print("Initializing optimizer...")
129
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=learning_rate)
130
+
131
+ print("Logging test batch...")
132
+ test_batch = test_dataset.sample_test_batch(size=params.test_size)
133
+ for item in test_batch:
134
+ mel, spk = item["y"], item["spk"]
135
+ i = int(spk.cpu())
136
+ logger.add_image(
137
+ f"image_{i}/ground_truth",
138
+ plot_tensor(mel.squeeze()),
139
+ global_step=0,
140
+ dataformats="HWC",
141
+ )
142
+ save_plot(mel.squeeze(), f"{log_dir}/original_{i}.png")
143
+
144
+ print("Start training...")
145
+ iteration = 0
146
+ for epoch in range(1, n_epochs + 1):
147
+ model.eval()
148
+ print("Synthesis...")
149
+ with torch.no_grad():
150
+ for item in test_batch:
151
+ x = item["x"].to(torch.long).unsqueeze(0).cuda()
152
+ x_lengths = torch.LongTensor([x.shape[-1]]).cuda()
153
+ spk = item["spk"].to(torch.long).cuda()
154
+ i = int(spk.cpu())
155
+
156
+ y_enc, y_dec, attn = model(x, x_lengths, n_timesteps=50, spk=spk)
157
+ logger.add_image(
158
+ f"image_{i}/generated_enc",
159
+ plot_tensor(y_enc.squeeze().cpu()),
160
+ global_step=iteration,
161
+ dataformats="HWC",
162
+ )
163
+ logger.add_image(
164
+ f"image_{i}/generated_dec",
165
+ plot_tensor(y_dec.squeeze().cpu()),
166
+ global_step=iteration,
167
+ dataformats="HWC",
168
+ )
169
+ logger.add_image(
170
+ f"image_{i}/alignment",
171
+ plot_tensor(attn.squeeze().cpu()),
172
+ global_step=iteration,
173
+ dataformats="HWC",
174
+ )
175
+ save_plot(y_enc.squeeze().cpu(), f"{log_dir}/generated_enc_{i}.png")
176
+ save_plot(y_dec.squeeze().cpu(), f"{log_dir}/generated_dec_{i}.png")
177
+ save_plot(attn.squeeze().cpu(), f"{log_dir}/alignment_{i}.png")
178
+
179
+ model.train()
180
+ dur_losses = []
181
+ prior_losses = []
182
+ diff_losses = []
183
+ with tqdm(loader, total=len(train_dataset) // batch_size) as progress_bar:
184
+ for batch in progress_bar:
185
+ model.zero_grad()
186
+ x, x_lengths = batch["x"].cuda(), batch["x_lengths"].cuda()
187
+ y, y_lengths = batch["y"].cuda(), batch["y_lengths"].cuda()
188
+ spk = batch["spk"].cuda()
189
+ dur_loss, prior_loss, diff_loss = model.compute_loss(
190
+ x, x_lengths, y, y_lengths, spk=spk, out_size=out_size
191
+ )
192
+ loss = sum([dur_loss, prior_loss, diff_loss])
193
+ loss.backward()
194
+
195
+ enc_grad_norm = torch.nn.utils.clip_grad_norm_(
196
+ model.encoder.parameters(), max_norm=1
197
+ )
198
+ dec_grad_norm = torch.nn.utils.clip_grad_norm_(
199
+ model.decoder.parameters(), max_norm=1
200
+ )
201
+ optimizer.step()
202
+
203
+ logger.add_scalar(
204
+ "training/duration_loss", dur_loss, global_step=iteration
205
+ )
206
+ logger.add_scalar(
207
+ "training/prior_loss", prior_loss, global_step=iteration
208
+ )
209
+ logger.add_scalar(
210
+ "training/diffusion_loss", diff_loss, global_step=iteration
211
+ )
212
+ logger.add_scalar(
213
+ "training/encoder_grad_norm", enc_grad_norm, global_step=iteration
214
+ )
215
+ logger.add_scalar(
216
+ "training/decoder_grad_norm", dec_grad_norm, global_step=iteration
217
+ )
218
+
219
+ msg = f"Epoch: {epoch}, iteration: {iteration} | dur_loss: {dur_loss.item()}, prior_loss: {prior_loss.item()}, diff_loss: {diff_loss.item()}"
220
+ progress_bar.set_description(msg)
221
+
222
+ dur_losses.append(dur_loss.item())
223
+ prior_losses.append(prior_loss.item())
224
+ diff_losses.append(diff_loss.item())
225
+ iteration += 1
226
+
227
+ msg = "Epoch %d: duration loss = %.3f " % (epoch, np.mean(dur_losses))
228
+ msg += "| prior loss = %.3f " % np.mean(prior_losses)
229
+ msg += "| diffusion loss = %.3f\n" % np.mean(diff_losses)
230
+ with open(f"{log_dir}/train.log", "a") as f:
231
+ f.write(msg)
232
+
233
+ if epoch % params.save_every > 0:
234
+ continue
235
+
236
+ ckpt = model.state_dict()
237
+ torch.save(ckpt, f=f"{log_dir}/grad_{epoch}.pt")
Grad-TTS/finetune_params.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ from model.utils import fix_len_compatibility
10
+
11
+
12
+ # data parameters
13
+ train_filelist_path = "../../id/train.txt"
14
+ valid_filelist_path = "../../id/valid.txt"
15
+ # test_filelist_path = 'resources/filelists/ljspeech/test.txt'
16
+ cmudict_path = "resources/cmu_dictionary_id"
17
+ add_blank = True
18
+ n_feats = 80
19
+ n_spks = 247 # for Libri-TTS filelist and 1 for LJSpeech
20
+ spk_emb_dim = 64
21
+ n_feats = 80
22
+ n_fft = 1024
23
+ sample_rate = 22050
24
+ hop_length = 256
25
+ win_length = 1024
26
+ f_min = 0
27
+ f_max = 8000
28
+
29
+ # encoder parameters
30
+ n_enc_channels = 192
31
+ filter_channels = 768
32
+ filter_channels_dp = 256
33
+ n_enc_layers = 6
34
+ enc_kernel = 3
35
+ enc_dropout = 0.1
36
+ n_heads = 2
37
+ window_size = 4
38
+
39
+ # decoder parameters
40
+ dec_dim = 64
41
+ beta_min = 0.05
42
+ beta_max = 20.0
43
+ pe_scale = 1000 # 1 for `grad-tts-old.pt` checkpoint
44
+
45
+ # training parameters
46
+ log_dir = "logs/grad-tts-bookbot-ft-weildan"
47
+ test_size = 4
48
+ n_epochs = 24000
49
+ batch_size = 8
50
+ learning_rate = 1e-4
51
+ seed = 37
52
+ save_every = 1000
53
+ out_size = fix_len_compatibility(2 * 22050 // 256)
54
+ num_workers = 6
55
+
56
+ checkpoint = "checkpts/grad-tts-libri-tts.pt"
Grad-TTS/hifi-gan/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Jungil Kong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Grad-TTS/hifi-gan/README.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis
2
+
3
+ ### Jungil Kong, Jaehyeon Kim, Jaekyoung Bae
4
+
5
+ In our [paper](https://arxiv.org/abs/2010.05646),
6
+ we proposed HiFi-GAN: a GAN-based model capable of generating high fidelity speech efficiently.<br/>
7
+ We provide our implementation and pretrained models as open source in this repository.
8
+
9
+ **Abstract :**
10
+ Several recent work on speech synthesis have employed generative adversarial networks (GANs) to produce raw waveforms.
11
+ Although such methods improve the sampling efficiency and memory usage,
12
+ their sample quality has not yet reached that of autoregressive and flow-based generative models.
13
+ In this work, we propose HiFi-GAN, which achieves both efficient and high-fidelity speech synthesis.
14
+ As speech audio consists of sinusoidal signals with various periods,
15
+ we demonstrate that modeling periodic patterns of an audio is crucial for enhancing sample quality.
16
+ A subjective human evaluation (mean opinion score, MOS) of a single speaker dataset indicates that our proposed method
17
+ demonstrates similarity to human quality while generating 22.05 kHz high-fidelity audio 167.9 times faster than
18
+ real-time on a single V100 GPU. We further show the generality of HiFi-GAN to the mel-spectrogram inversion of unseen
19
+ speakers and end-to-end speech synthesis. Finally, a small footprint version of HiFi-GAN generates samples 13.4 times
20
+ faster than real-time on CPU with comparable quality to an autoregressive counterpart.
21
+
22
+ Visit our [demo website](https://jik876.github.io/hifi-gan-demo/) for audio samples.
23
+
24
+
25
+ ## Pre-requisites
26
+ 1. Python >= 3.6
27
+ 2. Clone this repository.
28
+ 3. Install python requirements. Please refer [requirements.txt](requirements.txt)
29
+ 4. Download and extract the [LJ Speech dataset](https://keithito.com/LJ-Speech-Dataset/).
30
+ And move all wav files to `LJSpeech-1.1/wavs`
31
+
32
+
33
+ ## Training
34
+ ```
35
+ python train.py --config config_v1.json
36
+ ```
37
+ To train V2 or V3 Generator, replace `config_v1.json` with `config_v2.json` or `config_v3.json`.<br>
38
+ Checkpoints and copy of the configuration file are saved in `cp_hifigan` directory by default.<br>
39
+ You can change the path by adding `--checkpoint_path` option.
40
+
41
+ Validation loss during training with V1 generator.<br>
42
+ ![validation loss](./validation_loss.png)
43
+
44
+ ## Pretrained Model
45
+ You can also use pretrained models we provide.<br/>
46
+ [Download pretrained models](https://drive.google.com/drive/folders/1-eEYTB5Av9jNql0WGBlRoi-WH2J7bp5Y?usp=sharing)<br/>
47
+ Details of each folder are as in follows:
48
+
49
+ |Folder Name|Generator|Dataset|Fine-Tuned|
50
+ |------|---|---|---|
51
+ |LJ_V1|V1|LJSpeech|No|
52
+ |LJ_V2|V2|LJSpeech|No|
53
+ |LJ_V3|V3|LJSpeech|No|
54
+ |LJ_FT_T2_V1|V1|LJSpeech|Yes ([Tacotron2](https://github.com/NVIDIA/tacotron2))|
55
+ |LJ_FT_T2_V2|V2|LJSpeech|Yes ([Tacotron2](https://github.com/NVIDIA/tacotron2))|
56
+ |LJ_FT_T2_V3|V3|LJSpeech|Yes ([Tacotron2](https://github.com/NVIDIA/tacotron2))|
57
+ |VCTK_V1|V1|VCTK|No|
58
+ |VCTK_V2|V2|VCTK|No|
59
+ |VCTK_V3|V3|VCTK|No|
60
+ |UNIVERSAL_V1|V1|Universal|No|
61
+
62
+ We provide the universal model with discriminator weights that can be used as a base for transfer learning to other datasets.
63
+
64
+ ## Fine-Tuning
65
+ 1. Generate mel-spectrograms in numpy format using [Tacotron2](https://github.com/NVIDIA/tacotron2) with teacher-forcing.<br/>
66
+ The file name of the generated mel-spectrogram should match the audio file and the extension should be `.npy`.<br/>
67
+ Example:
68
+ ```
69
+ Audio File : LJ001-0001.wav
70
+ Mel-Spectrogram File : LJ001-0001.npy
71
+ ```
72
+ 2. Create `ft_dataset` folder and copy the generated mel-spectrogram files into it.<br/>
73
+ 3. Run the following command.
74
+ ```
75
+ python train.py --fine_tuning True --config config_v1.json
76
+ ```
77
+ For other command line options, please refer to the training section.
78
+
79
+
80
+ ## Inference from wav file
81
+ 1. Make `test_files` directory and copy wav files into the directory.
82
+ 2. Run the following command.
83
+ ```
84
+ python inference.py --checkpoint_file [generator checkpoint file path]
85
+ ```
86
+ Generated wav files are saved in `generated_files` by default.<br>
87
+ You can change the path by adding `--output_dir` option.
88
+
89
+
90
+ ## Inference for end-to-end speech synthesis
91
+ 1. Make `test_mel_files` directory and copy generated mel-spectrogram files into the directory.<br>
92
+ You can generate mel-spectrograms using [Tacotron2](https://github.com/NVIDIA/tacotron2),
93
+ [Glow-TTS](https://github.com/jaywalnut310/glow-tts) and so forth.
94
+ 2. Run the following command.
95
+ ```
96
+ python inference_e2e.py --checkpoint_file [generator checkpoint file path]
97
+ ```
98
+ Generated wav files are saved in `generated_files_from_mel` by default.<br>
99
+ You can change the path by adding `--output_dir` option.
100
+
101
+
102
+ ## Acknowledgements
103
+ We referred to [WaveGlow](https://github.com/NVIDIA/waveglow), [MelGAN](https://github.com/descriptinc/melgan-neurips)
104
+ and [Tacotron2](https://github.com/NVIDIA/tacotron2) to implement this.
105
+
Grad-TTS/hifi-gan/env.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/jik876/hifi-gan """
2
+
3
+ import os
4
+ import shutil
5
+
6
+
7
+ class AttrDict(dict):
8
+ def __init__(self, *args, **kwargs):
9
+ super(AttrDict, self).__init__(*args, **kwargs)
10
+ self.__dict__ = self
11
+
12
+
13
+ def build_env(config, config_name, path):
14
+ t_path = os.path.join(path, config_name)
15
+ if config != t_path:
16
+ os.makedirs(path, exist_ok=True)
17
+ shutil.copyfile(config, os.path.join(path, config_name))
Grad-TTS/hifi-gan/meldataset.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/jik876/hifi-gan """
2
+
3
+ import math
4
+ import os
5
+ import random
6
+ import torch
7
+ import torch.utils.data
8
+ import numpy as np
9
+ from librosa.util import normalize
10
+ from scipy.io.wavfile import read
11
+ from librosa.filters import mel as librosa_mel_fn
12
+
13
+ MAX_WAV_VALUE = 32768.0
14
+
15
+
16
+ def load_wav(full_path):
17
+ sampling_rate, data = read(full_path)
18
+ return data, sampling_rate
19
+
20
+
21
+ def dynamic_range_compression(x, C=1, clip_val=1e-5):
22
+ return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
23
+
24
+
25
+ def dynamic_range_decompression(x, C=1):
26
+ return np.exp(x) / C
27
+
28
+
29
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
30
+ return torch.log(torch.clamp(x, min=clip_val) * C)
31
+
32
+
33
+ def dynamic_range_decompression_torch(x, C=1):
34
+ return torch.exp(x) / C
35
+
36
+
37
+ def spectral_normalize_torch(magnitudes):
38
+ output = dynamic_range_compression_torch(magnitudes)
39
+ return output
40
+
41
+
42
+ def spectral_de_normalize_torch(magnitudes):
43
+ output = dynamic_range_decompression_torch(magnitudes)
44
+ return output
45
+
46
+
47
+ mel_basis = {}
48
+ hann_window = {}
49
+
50
+
51
+ def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
52
+ if torch.min(y) < -1.:
53
+ print('min value is ', torch.min(y))
54
+ if torch.max(y) > 1.:
55
+ print('max value is ', torch.max(y))
56
+
57
+ global mel_basis, hann_window
58
+ if fmax not in mel_basis:
59
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
60
+ mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device)
61
+ hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
62
+
63
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
64
+ y = y.squeeze(1)
65
+
66
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[str(y.device)],
67
+ center=center, pad_mode='reflect', normalized=False, onesided=True)
68
+
69
+ spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9))
70
+
71
+ spec = torch.matmul(mel_basis[str(fmax)+'_'+str(y.device)], spec)
72
+ spec = spectral_normalize_torch(spec)
73
+
74
+ return spec
75
+
76
+
77
+ def get_dataset_filelist(a):
78
+ with open(a.input_training_file, 'r', encoding='utf-8') as fi:
79
+ training_files = [os.path.join(a.input_wavs_dir, x.split('|')[0] + '.wav')
80
+ for x in fi.read().split('\n') if len(x) > 0]
81
+
82
+ with open(a.input_validation_file, 'r', encoding='utf-8') as fi:
83
+ validation_files = [os.path.join(a.input_wavs_dir, x.split('|')[0] + '.wav')
84
+ for x in fi.read().split('\n') if len(x) > 0]
85
+ return training_files, validation_files
86
+
87
+
88
+ class MelDataset(torch.utils.data.Dataset):
89
+ def __init__(self, training_files, segment_size, n_fft, num_mels,
90
+ hop_size, win_size, sampling_rate, fmin, fmax, split=True, shuffle=True, n_cache_reuse=1,
91
+ device=None, fmax_loss=None, fine_tuning=False, base_mels_path=None):
92
+ self.audio_files = training_files
93
+ random.seed(1234)
94
+ if shuffle:
95
+ random.shuffle(self.audio_files)
96
+ self.segment_size = segment_size
97
+ self.sampling_rate = sampling_rate
98
+ self.split = split
99
+ self.n_fft = n_fft
100
+ self.num_mels = num_mels
101
+ self.hop_size = hop_size
102
+ self.win_size = win_size
103
+ self.fmin = fmin
104
+ self.fmax = fmax
105
+ self.fmax_loss = fmax_loss
106
+ self.cached_wav = None
107
+ self.n_cache_reuse = n_cache_reuse
108
+ self._cache_ref_count = 0
109
+ self.device = device
110
+ self.fine_tuning = fine_tuning
111
+ self.base_mels_path = base_mels_path
112
+
113
+ def __getitem__(self, index):
114
+ filename = self.audio_files[index]
115
+ if self._cache_ref_count == 0:
116
+ audio, sampling_rate = load_wav(filename)
117
+ audio = audio / MAX_WAV_VALUE
118
+ if not self.fine_tuning:
119
+ audio = normalize(audio) * 0.95
120
+ self.cached_wav = audio
121
+ if sampling_rate != self.sampling_rate:
122
+ raise ValueError("{} SR doesn't match target {} SR".format(
123
+ sampling_rate, self.sampling_rate))
124
+ self._cache_ref_count = self.n_cache_reuse
125
+ else:
126
+ audio = self.cached_wav
127
+ self._cache_ref_count -= 1
128
+
129
+ audio = torch.FloatTensor(audio)
130
+ audio = audio.unsqueeze(0)
131
+
132
+ if not self.fine_tuning:
133
+ if self.split:
134
+ if audio.size(1) >= self.segment_size:
135
+ max_audio_start = audio.size(1) - self.segment_size
136
+ audio_start = random.randint(0, max_audio_start)
137
+ audio = audio[:, audio_start:audio_start+self.segment_size]
138
+ else:
139
+ audio = torch.nn.functional.pad(audio, (0, self.segment_size - audio.size(1)), 'constant')
140
+
141
+ mel = mel_spectrogram(audio, self.n_fft, self.num_mels,
142
+ self.sampling_rate, self.hop_size, self.win_size, self.fmin, self.fmax,
143
+ center=False)
144
+ else:
145
+ mel = np.load(
146
+ os.path.join(self.base_mels_path, os.path.splitext(os.path.split(filename)[-1])[0] + '.npy'))
147
+ mel = torch.from_numpy(mel)
148
+
149
+ if len(mel.shape) < 3:
150
+ mel = mel.unsqueeze(0)
151
+
152
+ if self.split:
153
+ frames_per_seg = math.ceil(self.segment_size / self.hop_size)
154
+
155
+ if audio.size(1) >= self.segment_size:
156
+ mel_start = random.randint(0, mel.size(2) - frames_per_seg - 1)
157
+ mel = mel[:, :, mel_start:mel_start + frames_per_seg]
158
+ audio = audio[:, mel_start * self.hop_size:(mel_start + frames_per_seg) * self.hop_size]
159
+ else:
160
+ mel = torch.nn.functional.pad(mel, (0, frames_per_seg - mel.size(2)), 'constant')
161
+ audio = torch.nn.functional.pad(audio, (0, self.segment_size - audio.size(1)), 'constant')
162
+
163
+ mel_loss = mel_spectrogram(audio, self.n_fft, self.num_mels,
164
+ self.sampling_rate, self.hop_size, self.win_size, self.fmin, self.fmax_loss,
165
+ center=False)
166
+
167
+ return (mel.squeeze(), audio.squeeze(0), filename, mel_loss.squeeze())
168
+
169
+ def __len__(self):
170
+ return len(self.audio_files)
Grad-TTS/hifi-gan/models.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/jik876/hifi-gan """
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ import torch.nn as nn
6
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
7
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
8
+ from xutils import init_weights, get_padding
9
+
10
+ LRELU_SLOPE = 0.1
11
+
12
+
13
+ class ResBlock1(torch.nn.Module):
14
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)):
15
+ super(ResBlock1, self).__init__()
16
+ self.h = h
17
+ self.convs1 = nn.ModuleList([
18
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
19
+ padding=get_padding(kernel_size, dilation[0]))),
20
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
21
+ padding=get_padding(kernel_size, dilation[1]))),
22
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
23
+ padding=get_padding(kernel_size, dilation[2])))
24
+ ])
25
+ self.convs1.apply(init_weights)
26
+
27
+ self.convs2 = nn.ModuleList([
28
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
29
+ padding=get_padding(kernel_size, 1))),
30
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
31
+ padding=get_padding(kernel_size, 1))),
32
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
33
+ padding=get_padding(kernel_size, 1)))
34
+ ])
35
+ self.convs2.apply(init_weights)
36
+
37
+ def forward(self, x):
38
+ for c1, c2 in zip(self.convs1, self.convs2):
39
+ xt = F.leaky_relu(x, LRELU_SLOPE)
40
+ xt = c1(xt)
41
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
42
+ xt = c2(xt)
43
+ x = xt + x
44
+ return x
45
+
46
+ def remove_weight_norm(self):
47
+ for l in self.convs1:
48
+ remove_weight_norm(l)
49
+ for l in self.convs2:
50
+ remove_weight_norm(l)
51
+
52
+
53
+ class ResBlock2(torch.nn.Module):
54
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)):
55
+ super(ResBlock2, self).__init__()
56
+ self.h = h
57
+ self.convs = nn.ModuleList([
58
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
59
+ padding=get_padding(kernel_size, dilation[0]))),
60
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
61
+ padding=get_padding(kernel_size, dilation[1])))
62
+ ])
63
+ self.convs.apply(init_weights)
64
+
65
+ def forward(self, x):
66
+ for c in self.convs:
67
+ xt = F.leaky_relu(x, LRELU_SLOPE)
68
+ xt = c(xt)
69
+ x = xt + x
70
+ return x
71
+
72
+ def remove_weight_norm(self):
73
+ for l in self.convs:
74
+ remove_weight_norm(l)
75
+
76
+
77
+ class Generator(torch.nn.Module):
78
+ def __init__(self, h):
79
+ super(Generator, self).__init__()
80
+ self.h = h
81
+ self.num_kernels = len(h.resblock_kernel_sizes)
82
+ self.num_upsamples = len(h.upsample_rates)
83
+ self.conv_pre = weight_norm(Conv1d(80, h.upsample_initial_channel, 7, 1, padding=3))
84
+ resblock = ResBlock1 if h.resblock == '1' else ResBlock2
85
+
86
+ self.ups = nn.ModuleList()
87
+ for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
88
+ self.ups.append(weight_norm(
89
+ ConvTranspose1d(h.upsample_initial_channel//(2**i), h.upsample_initial_channel//(2**(i+1)),
90
+ k, u, padding=(k-u)//2)))
91
+
92
+ self.resblocks = nn.ModuleList()
93
+ for i in range(len(self.ups)):
94
+ ch = h.upsample_initial_channel//(2**(i+1))
95
+ for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
96
+ self.resblocks.append(resblock(h, ch, k, d))
97
+
98
+ self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
99
+ self.ups.apply(init_weights)
100
+ self.conv_post.apply(init_weights)
101
+
102
+ def forward(self, x):
103
+ x = self.conv_pre(x)
104
+ for i in range(self.num_upsamples):
105
+ x = F.leaky_relu(x, LRELU_SLOPE)
106
+ x = self.ups[i](x)
107
+ xs = None
108
+ for j in range(self.num_kernels):
109
+ if xs is None:
110
+ xs = self.resblocks[i*self.num_kernels+j](x)
111
+ else:
112
+ xs += self.resblocks[i*self.num_kernels+j](x)
113
+ x = xs / self.num_kernels
114
+ x = F.leaky_relu(x)
115
+ x = self.conv_post(x)
116
+ x = torch.tanh(x)
117
+
118
+ return x
119
+
120
+ def remove_weight_norm(self):
121
+ print('Removing weight norm...')
122
+ for l in self.ups:
123
+ remove_weight_norm(l)
124
+ for l in self.resblocks:
125
+ l.remove_weight_norm()
126
+ remove_weight_norm(self.conv_pre)
127
+ remove_weight_norm(self.conv_post)
128
+
129
+
130
+ class DiscriminatorP(torch.nn.Module):
131
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
132
+ super(DiscriminatorP, self).__init__()
133
+ self.period = period
134
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
135
+ self.convs = nn.ModuleList([
136
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
137
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
138
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
139
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
140
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(2, 0))),
141
+ ])
142
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
143
+
144
+ def forward(self, x):
145
+ fmap = []
146
+
147
+ # 1d to 2d
148
+ b, c, t = x.shape
149
+ if t % self.period != 0: # pad first
150
+ n_pad = self.period - (t % self.period)
151
+ x = F.pad(x, (0, n_pad), "reflect")
152
+ t = t + n_pad
153
+ x = x.view(b, c, t // self.period, self.period)
154
+
155
+ for l in self.convs:
156
+ x = l(x)
157
+ x = F.leaky_relu(x, LRELU_SLOPE)
158
+ fmap.append(x)
159
+ x = self.conv_post(x)
160
+ fmap.append(x)
161
+ x = torch.flatten(x, 1, -1)
162
+
163
+ return x, fmap
164
+
165
+
166
+ class MultiPeriodDiscriminator(torch.nn.Module):
167
+ def __init__(self):
168
+ super(MultiPeriodDiscriminator, self).__init__()
169
+ self.discriminators = nn.ModuleList([
170
+ DiscriminatorP(2),
171
+ DiscriminatorP(3),
172
+ DiscriminatorP(5),
173
+ DiscriminatorP(7),
174
+ DiscriminatorP(11),
175
+ ])
176
+
177
+ def forward(self, y, y_hat):
178
+ y_d_rs = []
179
+ y_d_gs = []
180
+ fmap_rs = []
181
+ fmap_gs = []
182
+ for i, d in enumerate(self.discriminators):
183
+ y_d_r, fmap_r = d(y)
184
+ y_d_g, fmap_g = d(y_hat)
185
+ y_d_rs.append(y_d_r)
186
+ fmap_rs.append(fmap_r)
187
+ y_d_gs.append(y_d_g)
188
+ fmap_gs.append(fmap_g)
189
+
190
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
191
+
192
+
193
+ class DiscriminatorS(torch.nn.Module):
194
+ def __init__(self, use_spectral_norm=False):
195
+ super(DiscriminatorS, self).__init__()
196
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
197
+ self.convs = nn.ModuleList([
198
+ norm_f(Conv1d(1, 128, 15, 1, padding=7)),
199
+ norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)),
200
+ norm_f(Conv1d(128, 256, 41, 2, groups=16, padding=20)),
201
+ norm_f(Conv1d(256, 512, 41, 4, groups=16, padding=20)),
202
+ norm_f(Conv1d(512, 1024, 41, 4, groups=16, padding=20)),
203
+ norm_f(Conv1d(1024, 1024, 41, 1, groups=16, padding=20)),
204
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
205
+ ])
206
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
207
+
208
+ def forward(self, x):
209
+ fmap = []
210
+ for l in self.convs:
211
+ x = l(x)
212
+ x = F.leaky_relu(x, LRELU_SLOPE)
213
+ fmap.append(x)
214
+ x = self.conv_post(x)
215
+ fmap.append(x)
216
+ x = torch.flatten(x, 1, -1)
217
+
218
+ return x, fmap
219
+
220
+
221
+ class MultiScaleDiscriminator(torch.nn.Module):
222
+ def __init__(self):
223
+ super(MultiScaleDiscriminator, self).__init__()
224
+ self.discriminators = nn.ModuleList([
225
+ DiscriminatorS(use_spectral_norm=True),
226
+ DiscriminatorS(),
227
+ DiscriminatorS(),
228
+ ])
229
+ self.meanpools = nn.ModuleList([
230
+ AvgPool1d(4, 2, padding=2),
231
+ AvgPool1d(4, 2, padding=2)
232
+ ])
233
+
234
+ def forward(self, y, y_hat):
235
+ y_d_rs = []
236
+ y_d_gs = []
237
+ fmap_rs = []
238
+ fmap_gs = []
239
+ for i, d in enumerate(self.discriminators):
240
+ if i != 0:
241
+ y = self.meanpools[i-1](y)
242
+ y_hat = self.meanpools[i-1](y_hat)
243
+ y_d_r, fmap_r = d(y)
244
+ y_d_g, fmap_g = d(y_hat)
245
+ y_d_rs.append(y_d_r)
246
+ fmap_rs.append(fmap_r)
247
+ y_d_gs.append(y_d_g)
248
+ fmap_gs.append(fmap_g)
249
+
250
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
251
+
252
+
253
+ def feature_loss(fmap_r, fmap_g):
254
+ loss = 0
255
+ for dr, dg in zip(fmap_r, fmap_g):
256
+ for rl, gl in zip(dr, dg):
257
+ loss += torch.mean(torch.abs(rl - gl))
258
+
259
+ return loss*2
260
+
261
+
262
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
263
+ loss = 0
264
+ r_losses = []
265
+ g_losses = []
266
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
267
+ r_loss = torch.mean((1-dr)**2)
268
+ g_loss = torch.mean(dg**2)
269
+ loss += (r_loss + g_loss)
270
+ r_losses.append(r_loss.item())
271
+ g_losses.append(g_loss.item())
272
+
273
+ return loss, r_losses, g_losses
274
+
275
+
276
+ def generator_loss(disc_outputs):
277
+ loss = 0
278
+ gen_losses = []
279
+ for dg in disc_outputs:
280
+ l = torch.mean((1-dg)**2)
281
+ gen_losses.append(l)
282
+ loss += l
283
+
284
+ return loss, gen_losses
285
+
Grad-TTS/hifi-gan/xutils.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/jik876/hifi-gan """
2
+
3
+ import glob
4
+ import os
5
+ import matplotlib
6
+ import torch
7
+ from torch.nn.utils import weight_norm
8
+ matplotlib.use("Agg")
9
+ import matplotlib.pylab as plt
10
+
11
+
12
+ def plot_spectrogram(spectrogram):
13
+ fig, ax = plt.subplots(figsize=(10, 2))
14
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower",
15
+ interpolation='none')
16
+ plt.colorbar(im, ax=ax)
17
+
18
+ fig.canvas.draw()
19
+ plt.close()
20
+
21
+ return fig
22
+
23
+
24
+ def init_weights(m, mean=0.0, std=0.01):
25
+ classname = m.__class__.__name__
26
+ if classname.find("Conv") != -1:
27
+ m.weight.data.normal_(mean, std)
28
+
29
+
30
+ def apply_weight_norm(m):
31
+ classname = m.__class__.__name__
32
+ if classname.find("Conv") != -1:
33
+ weight_norm(m)
34
+
35
+
36
+ def get_padding(kernel_size, dilation=1):
37
+ return int((kernel_size*dilation - dilation)/2)
38
+
39
+
40
+ def load_checkpoint(filepath, device):
41
+ assert os.path.isfile(filepath)
42
+ print("Loading '{}'".format(filepath))
43
+ checkpoint_dict = torch.load(filepath, map_location=device)
44
+ print("Complete.")
45
+ return checkpoint_dict
46
+
47
+
48
+ def save_checkpoint(filepath, obj):
49
+ print("Saving checkpoint to {}".format(filepath))
50
+ torch.save(obj, filepath)
51
+ print("Complete.")
52
+
53
+
54
+ def scan_checkpoint(cp_dir, prefix):
55
+ pattern = os.path.join(cp_dir, prefix + '????????')
56
+ cp_list = glob.glob(pattern)
57
+ if len(cp_list) == 0:
58
+ return None
59
+ return sorted(cp_list)[-1]
60
+
Grad-TTS/inference.ipynb ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "source": [
6
+ "# Grad-TTS: A Diffusion Probabilistic Model for Text-to-Speech\r\n",
7
+ "\r\n",
8
+ "Official implementation of the Grad-TTS model based on Diffusion Probabilistic Models. For all details check out our paper accepted to ICML 2021 via [this](https://arxiv.org/abs/2105.06337) link.\r\n",
9
+ "\r\n",
10
+ "You can listen to the samples on our demo page via [this](https://grad-tts.github.io/) link.\r\n",
11
+ "\r\n",
12
+ "You can access Google Colab demo notebook via [this](https://colab.research.google.com/drive/1YNrXtkJQKcYDmIYJeyX8s5eXxB4zgpZI?usp=sharing) link.\r\n",
13
+ "\r\n",
14
+ "**Authors**: Vadim Popov\\*, Ivan Vovk\\*, Vladimir Gogoryan, Tasnima Sadekova, Mikhail Kudinov.\r\n",
15
+ "\r\n",
16
+ "<sup>\\*Equal contribution.</sup>\r\n",
17
+ "\r\n",
18
+ "**Note**: for fast synthesis prefer running inference on GPU device."
19
+ ],
20
+ "metadata": {}
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "execution_count": null,
25
+ "source": [
26
+ "%env CUDA_VISIBLE_DEVICES=0"
27
+ ],
28
+ "outputs": [],
29
+ "metadata": {}
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": null,
34
+ "source": [
35
+ "import argparse\r\n",
36
+ "import json\r\n",
37
+ "import datetime as dt\r\n",
38
+ "import numpy as np\r\n",
39
+ "import matplotlib.pyplot as plt\r\n",
40
+ "import IPython.display as ipd\r\n",
41
+ "from tqdm import tqdm\r\n",
42
+ "from scipy.io.wavfile import write\r\n",
43
+ "\r\n",
44
+ "import torch\r\n",
45
+ "\r\n",
46
+ "# For Grad-TTS\r\n",
47
+ "import params\r\n",
48
+ "from model import GradTTS\r\n",
49
+ "from text import text_to_sequence, cmudict\r\n",
50
+ "from text.symbols import symbols\r\n",
51
+ "from utils import intersperse\r\n",
52
+ "\r\n",
53
+ "# For HiFi-GAN\r\n",
54
+ "import sys\r\n",
55
+ "sys.path.append('./hifi-gan/')\r\n",
56
+ "from env import AttrDict\r\n",
57
+ "from models import Generator as HiFiGAN"
58
+ ],
59
+ "outputs": [],
60
+ "metadata": {}
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": null,
65
+ "source": [
66
+ "N_SPKS = 247 # 247 for Libri-TTS model and 1 for single speaker (LJSpeech)"
67
+ ],
68
+ "outputs": [],
69
+ "metadata": {}
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "source": [
75
+ "generator = GradTTS(len(symbols)+1, N_SPKS, params.spk_emb_dim,\r\n",
76
+ " params.n_enc_channels, params.filter_channels,\r\n",
77
+ " params.filter_channels_dp, params.n_heads, params.n_enc_layers,\r\n",
78
+ " params.enc_kernel, params.enc_dropout, params.window_size,\r\n",
79
+ " params.n_feats, params.dec_dim, params.beta_min, params.beta_max,\r\n",
80
+ " pe_scale=1000) # pe_scale=1 for `grad-tts-old.pt`\r\n",
81
+ "generator.load_state_dict(torch.load('./checkpts/grad-tts-libri-tts.pt', map_location=lambda loc, storage: loc))\r\n",
82
+ "_ = generator.cuda().eval()\r\n",
83
+ "print(f'Number of parameters: {generator.nparams}')\r\n",
84
+ "\r\n",
85
+ "cmu = cmudict.CMUDict('./resources/cmu_dictionary')"
86
+ ],
87
+ "outputs": [],
88
+ "metadata": {}
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "execution_count": null,
93
+ "source": [
94
+ "with open('./checkpts/hifigan-config.json') as f:\r\n",
95
+ " h = AttrDict(json.load(f))\r\n",
96
+ "hifigan = HiFiGAN(h)\r\n",
97
+ "hifigan.load_state_dict(torch.load('./checkpts/hifigan.pt', map_location=lambda loc, storage: loc)['generator'])\r\n",
98
+ "_ = hifigan.cuda().eval()\r\n",
99
+ "hifigan.remove_weight_norm()\r\n",
100
+ "%matplotlib inline"
101
+ ],
102
+ "outputs": [],
103
+ "metadata": {}
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": null,
108
+ "source": [
109
+ "text = \"Here are the match lineups for the Colombia Haiti match.\""
110
+ ],
111
+ "outputs": [],
112
+ "metadata": {}
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": null,
117
+ "source": [
118
+ "x = torch.LongTensor(intersperse(text_to_sequence(text, dictionary=cmu), len(symbols))).cuda()[None]\r\n",
119
+ "x_lengths = torch.LongTensor([x.shape[-1]]).cuda()\r\n",
120
+ "x.shape, x_lengths"
121
+ ],
122
+ "outputs": [],
123
+ "metadata": {}
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "execution_count": null,
128
+ "source": [
129
+ "t = dt.datetime.now()\r\n",
130
+ "y_enc, y_dec, attn = generator.forward(x, x_lengths, n_timesteps=50, temperature=1.3,\r\n",
131
+ " stoc=False, spk=None if N_SPKS==1 else torch.LongTensor([15]).cuda(),\r\n",
132
+ " length_scale=0.91)\r\n",
133
+ "t = (dt.datetime.now() - t).total_seconds()\r\n",
134
+ "print(f'Grad-TTS RTF: {t * 22050 / (y_dec.shape[-1] * 256)}')\r\n",
135
+ "\r\n",
136
+ "plt.figure(figsize=(15, 4))\r\n",
137
+ "plt.subplot(1, 3, 1)\r\n",
138
+ "plt.title('Encoder outputs')\r\n",
139
+ "plt.imshow(y_enc.cpu().squeeze(), aspect='auto', origin='lower')\r\n",
140
+ "plt.colorbar()\r\n",
141
+ "plt.subplot(1, 3, 2)\r\n",
142
+ "plt.title('Decoder outputs')\r\n",
143
+ "plt.imshow(y_dec.cpu().squeeze(), aspect='auto', origin='lower')\r\n",
144
+ "plt.colorbar()\r\n",
145
+ "plt.subplot(1, 3, 3)\r\n",
146
+ "plt.title('Alignment')\r\n",
147
+ "plt.imshow(attn.cpu().squeeze(), aspect='auto', origin='lower');"
148
+ ],
149
+ "outputs": [],
150
+ "metadata": {}
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "execution_count": null,
155
+ "source": [
156
+ "with torch.no_grad():\r\n",
157
+ " audio = hifigan.forward(y_dec).cpu().squeeze().clamp(-1, 1)\r\n",
158
+ "ipd.display(ipd.Audio(audio, rate=22050))"
159
+ ],
160
+ "outputs": [],
161
+ "metadata": {}
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": null,
166
+ "source": [],
167
+ "outputs": [],
168
+ "metadata": {}
169
+ }
170
+ ],
171
+ "metadata": {
172
+ "kernelspec": {
173
+ "name": "python3",
174
+ "display_name": "Python 3.8.3 64-bit"
175
+ },
176
+ "language_info": {
177
+ "codemirror_mode": {
178
+ "name": "ipython",
179
+ "version": 3
180
+ },
181
+ "file_extension": ".py",
182
+ "mimetype": "text/x-python",
183
+ "name": "python",
184
+ "nbconvert_exporter": "python",
185
+ "pygments_lexer": "ipython3",
186
+ "version": "3.8.3"
187
+ },
188
+ "metadata": {
189
+ "interpreter": {
190
+ "hash": "1c27759576147a09f82f75fe7e6da160ee29ac300de0ba196702adc9d307c9a1"
191
+ }
192
+ },
193
+ "interpreter": {
194
+ "hash": "1c27759576147a09f82f75fe7e6da160ee29ac300de0ba196702adc9d307c9a1"
195
+ }
196
+ },
197
+ "nbformat": 4,
198
+ "nbformat_minor": 4
199
+ }
Grad-TTS/inference.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import argparse
10
+ import json
11
+ import datetime as dt
12
+ import numpy as np
13
+ from scipy.io.wavfile import write
14
+
15
+ import torch
16
+
17
+ import params
18
+ from model import GradTTS
19
+ from text import text_to_sequence, cmudict
20
+ from text.symbols import symbols
21
+ from utils import intersperse
22
+
23
+ import sys
24
+ sys.path.append('./hifi-gan/')
25
+ from env import AttrDict
26
+ from models import Generator as HiFiGAN
27
+
28
+
29
+ HIFIGAN_CONFIG = './checkpts/hifigan-config.json'
30
+ HIFIGAN_CHECKPT = './checkpts/hifigan.pt'
31
+
32
+
33
+ if __name__ == '__main__':
34
+ parser = argparse.ArgumentParser()
35
+ parser.add_argument('-f', '--file', type=str, required=True, help='path to a file with texts to synthesize')
36
+ parser.add_argument('-c', '--checkpoint', type=str, required=True, help='path to a checkpoint of Grad-TTS')
37
+ parser.add_argument('-t', '--timesteps', type=int, required=False, default=10, help='number of timesteps of reverse diffusion')
38
+ parser.add_argument('-s', '--speaker_id', type=int, required=False, default=None, help='speaker id for multispeaker model')
39
+ args = parser.parse_args()
40
+
41
+ if not isinstance(args.speaker_id, type(None)):
42
+ assert params.n_spks > 1, "Ensure you set right number of speakers in `params.py`."
43
+ spk = torch.LongTensor([args.speaker_id]).cuda()
44
+ else:
45
+ spk = None
46
+
47
+ print('Initializing Grad-TTS...')
48
+ generator = GradTTS(len(symbols)+1, params.n_spks, params.spk_emb_dim,
49
+ params.n_enc_channels, params.filter_channels,
50
+ params.filter_channels_dp, params.n_heads, params.n_enc_layers,
51
+ params.enc_kernel, params.enc_dropout, params.window_size,
52
+ params.n_feats, params.dec_dim, params.beta_min, params.beta_max, params.pe_scale)
53
+ generator.load_state_dict(torch.load(args.checkpoint, map_location=lambda loc, storage: loc))
54
+ _ = generator.cuda().eval()
55
+ print(f'Number of parameters: {generator.nparams}')
56
+
57
+ print('Initializing HiFi-GAN...')
58
+ with open(HIFIGAN_CONFIG) as f:
59
+ h = AttrDict(json.load(f))
60
+ vocoder = HiFiGAN(h)
61
+ vocoder.load_state_dict(torch.load(HIFIGAN_CHECKPT, map_location=lambda loc, storage: loc)['generator'])
62
+ _ = vocoder.cuda().eval()
63
+ vocoder.remove_weight_norm()
64
+
65
+ with open(args.file, 'r', encoding='utf-8') as f:
66
+ texts = [line.strip() for line in f.readlines()]
67
+ cmu = cmudict.CMUDict('./resources/cmu_dictionary')
68
+
69
+ with torch.no_grad():
70
+ for i, text in enumerate(texts):
71
+ print(f'Synthesizing {i} text...', end=' ')
72
+ x = torch.LongTensor(intersperse(text_to_sequence(text, dictionary=cmu), len(symbols))).cuda()[None]
73
+ x_lengths = torch.LongTensor([x.shape[-1]]).cuda()
74
+
75
+ t = dt.datetime.now()
76
+ y_enc, y_dec, attn = generator.forward(x, x_lengths, n_timesteps=args.timesteps, temperature=1.5,
77
+ stoc=False, spk=spk, length_scale=0.91)
78
+ t = (dt.datetime.now() - t).total_seconds()
79
+ print(f'Grad-TTS RTF: {t * 22050 / (y_dec.shape[-1] * 256)}')
80
+
81
+ audio = (vocoder.forward(y_dec).cpu().squeeze().clamp(-1, 1).numpy() * 32768).astype(np.int16)
82
+
83
+ write(f'./out/sample_{i}.wav', 22050, audio)
84
+
85
+ print('Done. Check out `out` folder for samples.')
Grad-TTS/model/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ from .tts import GradTTS
Grad-TTS/model/base.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import numpy as np
10
+ import torch
11
+
12
+
13
+ class BaseModule(torch.nn.Module):
14
+ def __init__(self):
15
+ super(BaseModule, self).__init__()
16
+
17
+ @property
18
+ def nparams(self):
19
+ """
20
+ Returns number of trainable parameters of the module.
21
+ """
22
+ num_params = 0
23
+ for name, param in self.named_parameters():
24
+ if param.requires_grad:
25
+ num_params += np.prod(param.detach().cpu().numpy().shape)
26
+ return num_params
27
+
28
+
29
+ def relocate_input(self, x: list):
30
+ """
31
+ Relocates provided tensors to the same device set for the module.
32
+ """
33
+ device = next(self.parameters()).device
34
+ for i in range(len(x)):
35
+ if isinstance(x[i], torch.Tensor) and x[i].device != device:
36
+ x[i] = x[i].to(device)
37
+ return x
Grad-TTS/model/diffusion.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import math
10
+ import torch
11
+ from einops import rearrange
12
+
13
+ from model.base import BaseModule
14
+
15
+
16
+ class Mish(BaseModule):
17
+ def forward(self, x):
18
+ return x * torch.tanh(torch.nn.functional.softplus(x))
19
+
20
+
21
+ class Upsample(BaseModule):
22
+ def __init__(self, dim):
23
+ super(Upsample, self).__init__()
24
+ self.conv = torch.nn.ConvTranspose2d(dim, dim, 4, 2, 1)
25
+
26
+ def forward(self, x):
27
+ return self.conv(x)
28
+
29
+
30
+ class Downsample(BaseModule):
31
+ def __init__(self, dim):
32
+ super(Downsample, self).__init__()
33
+ self.conv = torch.nn.Conv2d(dim, dim, 3, 2, 1)
34
+
35
+ def forward(self, x):
36
+ return self.conv(x)
37
+
38
+
39
+ class Rezero(BaseModule):
40
+ def __init__(self, fn):
41
+ super(Rezero, self).__init__()
42
+ self.fn = fn
43
+ self.g = torch.nn.Parameter(torch.zeros(1))
44
+
45
+ def forward(self, x):
46
+ return self.fn(x) * self.g
47
+
48
+
49
+ class Block(BaseModule):
50
+ def __init__(self, dim, dim_out, groups=8):
51
+ super(Block, self).__init__()
52
+ self.block = torch.nn.Sequential(torch.nn.Conv2d(dim, dim_out, 3,
53
+ padding=1), torch.nn.GroupNorm(
54
+ groups, dim_out), Mish())
55
+
56
+ def forward(self, x, mask):
57
+ output = self.block(x * mask)
58
+ return output * mask
59
+
60
+
61
+ class ResnetBlock(BaseModule):
62
+ def __init__(self, dim, dim_out, time_emb_dim, groups=8):
63
+ super(ResnetBlock, self).__init__()
64
+ self.mlp = torch.nn.Sequential(Mish(), torch.nn.Linear(time_emb_dim,
65
+ dim_out))
66
+
67
+ self.block1 = Block(dim, dim_out, groups=groups)
68
+ self.block2 = Block(dim_out, dim_out, groups=groups)
69
+ if dim != dim_out:
70
+ self.res_conv = torch.nn.Conv2d(dim, dim_out, 1)
71
+ else:
72
+ self.res_conv = torch.nn.Identity()
73
+
74
+ def forward(self, x, mask, time_emb):
75
+ h = self.block1(x, mask)
76
+ h += self.mlp(time_emb).unsqueeze(-1).unsqueeze(-1)
77
+ h = self.block2(h, mask)
78
+ output = h + self.res_conv(x * mask)
79
+ return output
80
+
81
+
82
+ class LinearAttention(BaseModule):
83
+ def __init__(self, dim, heads=4, dim_head=32):
84
+ super(LinearAttention, self).__init__()
85
+ self.heads = heads
86
+ hidden_dim = dim_head * heads
87
+ self.to_qkv = torch.nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
88
+ self.to_out = torch.nn.Conv2d(hidden_dim, dim, 1)
89
+
90
+ def forward(self, x):
91
+ b, c, h, w = x.shape
92
+ qkv = self.to_qkv(x)
93
+ q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)',
94
+ heads = self.heads, qkv=3)
95
+ k = k.softmax(dim=-1)
96
+ context = torch.einsum('bhdn,bhen->bhde', k, v)
97
+ out = torch.einsum('bhde,bhdn->bhen', context, q)
98
+ out = rearrange(out, 'b heads c (h w) -> b (heads c) h w',
99
+ heads=self.heads, h=h, w=w)
100
+ return self.to_out(out)
101
+
102
+
103
+ class Residual(BaseModule):
104
+ def __init__(self, fn):
105
+ super(Residual, self).__init__()
106
+ self.fn = fn
107
+
108
+ def forward(self, x, *args, **kwargs):
109
+ output = self.fn(x, *args, **kwargs) + x
110
+ return output
111
+
112
+
113
+ class SinusoidalPosEmb(BaseModule):
114
+ def __init__(self, dim):
115
+ super(SinusoidalPosEmb, self).__init__()
116
+ self.dim = dim
117
+
118
+ def forward(self, x, scale=1000):
119
+ device = x.device
120
+ half_dim = self.dim // 2
121
+ emb = math.log(10000) / (half_dim - 1)
122
+ emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
123
+ emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
124
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
125
+ return emb
126
+
127
+
128
+ class GradLogPEstimator2d(BaseModule):
129
+ def __init__(self, dim, dim_mults=(1, 2, 4), groups=8,
130
+ n_spks=None, spk_emb_dim=64, n_feats=80, pe_scale=1000):
131
+ super(GradLogPEstimator2d, self).__init__()
132
+ self.dim = dim
133
+ self.dim_mults = dim_mults
134
+ self.groups = groups
135
+ self.n_spks = n_spks if not isinstance(n_spks, type(None)) else 1
136
+ self.spk_emb_dim = spk_emb_dim
137
+ self.pe_scale = pe_scale
138
+
139
+ if n_spks > 1:
140
+ self.spk_mlp = torch.nn.Sequential(torch.nn.Linear(spk_emb_dim, spk_emb_dim * 4), Mish(),
141
+ torch.nn.Linear(spk_emb_dim * 4, n_feats))
142
+ self.time_pos_emb = SinusoidalPosEmb(dim)
143
+ self.mlp = torch.nn.Sequential(torch.nn.Linear(dim, dim * 4), Mish(),
144
+ torch.nn.Linear(dim * 4, dim))
145
+
146
+ dims = [2 + (1 if n_spks > 1 else 0), *map(lambda m: dim * m, dim_mults)]
147
+ in_out = list(zip(dims[:-1], dims[1:]))
148
+ self.downs = torch.nn.ModuleList([])
149
+ self.ups = torch.nn.ModuleList([])
150
+ num_resolutions = len(in_out)
151
+
152
+ for ind, (dim_in, dim_out) in enumerate(in_out):
153
+ is_last = ind >= (num_resolutions - 1)
154
+ self.downs.append(torch.nn.ModuleList([
155
+ ResnetBlock(dim_in, dim_out, time_emb_dim=dim),
156
+ ResnetBlock(dim_out, dim_out, time_emb_dim=dim),
157
+ Residual(Rezero(LinearAttention(dim_out))),
158
+ Downsample(dim_out) if not is_last else torch.nn.Identity()]))
159
+
160
+ mid_dim = dims[-1]
161
+ self.mid_block1 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=dim)
162
+ self.mid_attn = Residual(Rezero(LinearAttention(mid_dim)))
163
+ self.mid_block2 = ResnetBlock(mid_dim, mid_dim, time_emb_dim=dim)
164
+
165
+ for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])):
166
+ self.ups.append(torch.nn.ModuleList([
167
+ ResnetBlock(dim_out * 2, dim_in, time_emb_dim=dim),
168
+ ResnetBlock(dim_in, dim_in, time_emb_dim=dim),
169
+ Residual(Rezero(LinearAttention(dim_in))),
170
+ Upsample(dim_in)]))
171
+ self.final_block = Block(dim, dim)
172
+ self.final_conv = torch.nn.Conv2d(dim, 1, 1)
173
+
174
+ def forward(self, x, mask, mu, t, spk=None):
175
+ if not isinstance(spk, type(None)):
176
+ s = self.spk_mlp(spk)
177
+
178
+ t = self.time_pos_emb(t, scale=self.pe_scale)
179
+ t = self.mlp(t)
180
+
181
+ if self.n_spks < 2:
182
+ x = torch.stack([mu, x], 1)
183
+ else:
184
+ s = s.unsqueeze(-1).repeat(1, 1, x.shape[-1])
185
+ x = torch.stack([mu, x, s], 1)
186
+ mask = mask.unsqueeze(1)
187
+
188
+ hiddens = []
189
+ masks = [mask]
190
+ for resnet1, resnet2, attn, downsample in self.downs:
191
+ mask_down = masks[-1]
192
+ x = resnet1(x, mask_down, t)
193
+ x = resnet2(x, mask_down, t)
194
+ x = attn(x)
195
+ hiddens.append(x)
196
+ x = downsample(x * mask_down)
197
+ masks.append(mask_down[:, :, :, ::2])
198
+
199
+ masks = masks[:-1]
200
+ mask_mid = masks[-1]
201
+ x = self.mid_block1(x, mask_mid, t)
202
+ x = self.mid_attn(x)
203
+ x = self.mid_block2(x, mask_mid, t)
204
+
205
+ for resnet1, resnet2, attn, upsample in self.ups:
206
+ mask_up = masks.pop()
207
+ x = torch.cat((x, hiddens.pop()), dim=1)
208
+ x = resnet1(x, mask_up, t)
209
+ x = resnet2(x, mask_up, t)
210
+ x = attn(x)
211
+ x = upsample(x * mask_up)
212
+
213
+ x = self.final_block(x, mask)
214
+ output = self.final_conv(x * mask)
215
+
216
+ return (output * mask).squeeze(1)
217
+
218
+
219
+ def get_noise(t, beta_init, beta_term, cumulative=False):
220
+ if cumulative:
221
+ noise = beta_init*t + 0.5*(beta_term - beta_init)*(t**2)
222
+ else:
223
+ noise = beta_init + (beta_term - beta_init)*t
224
+ return noise
225
+
226
+
227
+ class Diffusion(BaseModule):
228
+ def __init__(self, n_feats, dim,
229
+ n_spks=1, spk_emb_dim=64,
230
+ beta_min=0.05, beta_max=20, pe_scale=1000):
231
+ super(Diffusion, self).__init__()
232
+ self.n_feats = n_feats
233
+ self.dim = dim
234
+ self.n_spks = n_spks
235
+ self.spk_emb_dim = spk_emb_dim
236
+ self.beta_min = beta_min
237
+ self.beta_max = beta_max
238
+ self.pe_scale = pe_scale
239
+
240
+ self.estimator = GradLogPEstimator2d(dim, n_spks=n_spks,
241
+ spk_emb_dim=spk_emb_dim,
242
+ pe_scale=pe_scale)
243
+
244
+ def forward_diffusion(self, x0, mask, mu, t):
245
+ time = t.unsqueeze(-1).unsqueeze(-1)
246
+ cum_noise = get_noise(time, self.beta_min, self.beta_max, cumulative=True)
247
+ mean = x0*torch.exp(-0.5*cum_noise) + mu*(1.0 - torch.exp(-0.5*cum_noise))
248
+ variance = 1.0 - torch.exp(-cum_noise)
249
+ z = torch.randn(x0.shape, dtype=x0.dtype, device=x0.device,
250
+ requires_grad=False)
251
+ xt = mean + z * torch.sqrt(variance)
252
+ return xt * mask, z * mask
253
+
254
+ @torch.no_grad()
255
+ def reverse_diffusion(self, z, mask, mu, n_timesteps, stoc=False, spk=None):
256
+ h = 1.0 / n_timesteps
257
+ xt = z * mask
258
+ for i in range(n_timesteps):
259
+ t = (1.0 - (i + 0.5)*h) * torch.ones(z.shape[0], dtype=z.dtype,
260
+ device=z.device)
261
+ time = t.unsqueeze(-1).unsqueeze(-1)
262
+ noise_t = get_noise(time, self.beta_min, self.beta_max,
263
+ cumulative=False)
264
+ if stoc: # adds stochastic term
265
+ dxt_det = 0.5 * (mu - xt) - self.estimator(xt, mask, mu, t, spk)
266
+ dxt_det = dxt_det * noise_t * h
267
+ dxt_stoc = torch.randn(z.shape, dtype=z.dtype, device=z.device,
268
+ requires_grad=False)
269
+ dxt_stoc = dxt_stoc * torch.sqrt(noise_t * h)
270
+ dxt = dxt_det + dxt_stoc
271
+ else:
272
+ dxt = 0.5 * (mu - xt - self.estimator(xt, mask, mu, t, spk))
273
+ dxt = dxt * noise_t * h
274
+ xt = (xt - dxt) * mask
275
+ return xt
276
+
277
+ @torch.no_grad()
278
+ def forward(self, z, mask, mu, n_timesteps, stoc=False, spk=None):
279
+ return self.reverse_diffusion(z, mask, mu, n_timesteps, stoc, spk)
280
+
281
+ def loss_t(self, x0, mask, mu, t, spk=None):
282
+ xt, z = self.forward_diffusion(x0, mask, mu, t)
283
+ time = t.unsqueeze(-1).unsqueeze(-1)
284
+ cum_noise = get_noise(time, self.beta_min, self.beta_max, cumulative=True)
285
+ noise_estimation = self.estimator(xt, mask, mu, t, spk)
286
+ noise_estimation *= torch.sqrt(1.0 - torch.exp(-cum_noise))
287
+ loss = torch.sum((noise_estimation + z)**2) / (torch.sum(mask)*self.n_feats)
288
+ return loss, xt
289
+
290
+ def compute_loss(self, x0, mask, mu, spk=None, offset=1e-5):
291
+ t = torch.rand(x0.shape[0], dtype=x0.dtype, device=x0.device,
292
+ requires_grad=False)
293
+ t = torch.clamp(t, offset, 1.0 - offset)
294
+ return self.loss_t(x0, mask, mu, t, spk)
Grad-TTS/model/monotonic_align/LICENCE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Jaehyeon Kim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Grad-TTS/model/monotonic_align/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/jaywalnut310/glow-tts """
2
+
3
+ import numpy as np
4
+ import torch
5
+ from .model.monotonic_align.core import maximum_path_c
6
+
7
+
8
+ def maximum_path(value, mask):
9
+ """ Cython optimised version.
10
+ value: [b, t_x, t_y]
11
+ mask: [b, t_x, t_y]
12
+ """
13
+ value = value * mask
14
+ device = value.device
15
+ dtype = value.dtype
16
+ value = value.data.cpu().numpy().astype(np.float32)
17
+ path = np.zeros_like(value).astype(np.int32)
18
+ mask = mask.data.cpu().numpy()
19
+
20
+ t_x_max = mask.sum(1)[:, 0].astype(np.int32)
21
+ t_y_max = mask.sum(2)[:, 0].astype(np.int32)
22
+ maximum_path_c(path, value, t_x_max, t_y_max)
23
+ return torch.from_numpy(path).to(device=device, dtype=dtype)
Grad-TTS/model/monotonic_align/core.pyx ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ cimport numpy as np
3
+ cimport cython
4
+ from cython.parallel import prange
5
+
6
+
7
+ @cython.boundscheck(False)
8
+ @cython.wraparound(False)
9
+ cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_x, int t_y, float max_neg_val) nogil:
10
+ cdef int x
11
+ cdef int y
12
+ cdef float v_prev
13
+ cdef float v_cur
14
+ cdef float tmp
15
+ cdef int index = t_x - 1
16
+
17
+ for y in range(t_y):
18
+ for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
19
+ if x == y:
20
+ v_cur = max_neg_val
21
+ else:
22
+ v_cur = value[x, y-1]
23
+ if x == 0:
24
+ if y == 0:
25
+ v_prev = 0.
26
+ else:
27
+ v_prev = max_neg_val
28
+ else:
29
+ v_prev = value[x-1, y-1]
30
+ value[x, y] = max(v_cur, v_prev) + value[x, y]
31
+
32
+ for y in range(t_y - 1, -1, -1):
33
+ path[index, y] = 1
34
+ if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]):
35
+ index = index - 1
36
+
37
+
38
+ @cython.boundscheck(False)
39
+ @cython.wraparound(False)
40
+ cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil:
41
+ cdef int b = values.shape[0]
42
+
43
+ cdef int i
44
+ for i in prange(b, nogil=True):
45
+ maximum_path_each(paths[i], values[i], t_xs[i], t_ys[i], max_neg_val)
Grad-TTS/model/monotonic_align/setup.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/jaywalnut310/glow-tts """
2
+
3
+ from distutils.core import setup
4
+ from Cython.Build import cythonize
5
+ import numpy
6
+
7
+ setup(
8
+ name = 'monotonic_align',
9
+ ext_modules = cythonize("core.pyx"),
10
+ include_dirs=[numpy.get_include()]
11
+ )
Grad-TTS/model/text_encoder.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/jaywalnut310/glow-tts """
2
+
3
+ import math
4
+
5
+ import torch
6
+
7
+ from model.base import BaseModule
8
+ from model.utils import sequence_mask, convert_pad_shape
9
+
10
+
11
+ class LayerNorm(BaseModule):
12
+ def __init__(self, channels, eps=1e-4):
13
+ super(LayerNorm, self).__init__()
14
+ self.channels = channels
15
+ self.eps = eps
16
+
17
+ self.gamma = torch.nn.Parameter(torch.ones(channels))
18
+ self.beta = torch.nn.Parameter(torch.zeros(channels))
19
+
20
+ def forward(self, x):
21
+ n_dims = len(x.shape)
22
+ mean = torch.mean(x, 1, keepdim=True)
23
+ variance = torch.mean((x - mean)**2, 1, keepdim=True)
24
+
25
+ x = (x - mean) * torch.rsqrt(variance + self.eps)
26
+
27
+ shape = [1, -1] + [1] * (n_dims - 2)
28
+ x = x * self.gamma.view(*shape) + self.beta.view(*shape)
29
+ return x
30
+
31
+
32
+ class ConvReluNorm(BaseModule):
33
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size,
34
+ n_layers, p_dropout):
35
+ super(ConvReluNorm, self).__init__()
36
+ self.in_channels = in_channels
37
+ self.hidden_channels = hidden_channels
38
+ self.out_channels = out_channels
39
+ self.kernel_size = kernel_size
40
+ self.n_layers = n_layers
41
+ self.p_dropout = p_dropout
42
+
43
+ self.conv_layers = torch.nn.ModuleList()
44
+ self.norm_layers = torch.nn.ModuleList()
45
+ self.conv_layers.append(torch.nn.Conv1d(in_channels, hidden_channels,
46
+ kernel_size, padding=kernel_size//2))
47
+ self.norm_layers.append(LayerNorm(hidden_channels))
48
+ self.relu_drop = torch.nn.Sequential(torch.nn.ReLU(), torch.nn.Dropout(p_dropout))
49
+ for _ in range(n_layers - 1):
50
+ self.conv_layers.append(torch.nn.Conv1d(hidden_channels, hidden_channels,
51
+ kernel_size, padding=kernel_size//2))
52
+ self.norm_layers.append(LayerNorm(hidden_channels))
53
+ self.proj = torch.nn.Conv1d(hidden_channels, out_channels, 1)
54
+ self.proj.weight.data.zero_()
55
+ self.proj.bias.data.zero_()
56
+
57
+ def forward(self, x, x_mask):
58
+ x_org = x
59
+ for i in range(self.n_layers):
60
+ x = self.conv_layers[i](x * x_mask)
61
+ x = self.norm_layers[i](x)
62
+ x = self.relu_drop(x)
63
+ x = x_org + self.proj(x)
64
+ return x * x_mask
65
+
66
+
67
+ class DurationPredictor(BaseModule):
68
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout):
69
+ super(DurationPredictor, self).__init__()
70
+ self.in_channels = in_channels
71
+ self.filter_channels = filter_channels
72
+ self.p_dropout = p_dropout
73
+
74
+ self.drop = torch.nn.Dropout(p_dropout)
75
+ self.conv_1 = torch.nn.Conv1d(in_channels, filter_channels,
76
+ kernel_size, padding=kernel_size//2)
77
+ self.norm_1 = LayerNorm(filter_channels)
78
+ self.conv_2 = torch.nn.Conv1d(filter_channels, filter_channels,
79
+ kernel_size, padding=kernel_size//2)
80
+ self.norm_2 = LayerNorm(filter_channels)
81
+ self.proj = torch.nn.Conv1d(filter_channels, 1, 1)
82
+
83
+ def forward(self, x, x_mask):
84
+ x = self.conv_1(x * x_mask)
85
+ x = torch.relu(x)
86
+ x = self.norm_1(x)
87
+ x = self.drop(x)
88
+ x = self.conv_2(x * x_mask)
89
+ x = torch.relu(x)
90
+ x = self.norm_2(x)
91
+ x = self.drop(x)
92
+ x = self.proj(x * x_mask)
93
+ return x * x_mask
94
+
95
+
96
+ class MultiHeadAttention(BaseModule):
97
+ def __init__(self, channels, out_channels, n_heads, window_size=None,
98
+ heads_share=True, p_dropout=0.0, proximal_bias=False,
99
+ proximal_init=False):
100
+ super(MultiHeadAttention, self).__init__()
101
+ assert channels % n_heads == 0
102
+
103
+ self.channels = channels
104
+ self.out_channels = out_channels
105
+ self.n_heads = n_heads
106
+ self.window_size = window_size
107
+ self.heads_share = heads_share
108
+ self.proximal_bias = proximal_bias
109
+ self.p_dropout = p_dropout
110
+ self.attn = None
111
+
112
+ self.k_channels = channels // n_heads
113
+ self.conv_q = torch.nn.Conv1d(channels, channels, 1)
114
+ self.conv_k = torch.nn.Conv1d(channels, channels, 1)
115
+ self.conv_v = torch.nn.Conv1d(channels, channels, 1)
116
+ if window_size is not None:
117
+ n_heads_rel = 1 if heads_share else n_heads
118
+ rel_stddev = self.k_channels**-0.5
119
+ self.emb_rel_k = torch.nn.Parameter(torch.randn(n_heads_rel,
120
+ window_size * 2 + 1, self.k_channels) * rel_stddev)
121
+ self.emb_rel_v = torch.nn.Parameter(torch.randn(n_heads_rel,
122
+ window_size * 2 + 1, self.k_channels) * rel_stddev)
123
+ self.conv_o = torch.nn.Conv1d(channels, out_channels, 1)
124
+ self.drop = torch.nn.Dropout(p_dropout)
125
+
126
+ torch.nn.init.xavier_uniform_(self.conv_q.weight)
127
+ torch.nn.init.xavier_uniform_(self.conv_k.weight)
128
+ if proximal_init:
129
+ self.conv_k.weight.data.copy_(self.conv_q.weight.data)
130
+ self.conv_k.bias.data.copy_(self.conv_q.bias.data)
131
+ torch.nn.init.xavier_uniform_(self.conv_v.weight)
132
+
133
+ def forward(self, x, c, attn_mask=None):
134
+ q = self.conv_q(x)
135
+ k = self.conv_k(c)
136
+ v = self.conv_v(c)
137
+
138
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
139
+
140
+ x = self.conv_o(x)
141
+ return x
142
+
143
+ def attention(self, query, key, value, mask=None):
144
+ b, d, t_s, t_t = (*key.size(), query.size(2))
145
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
146
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
147
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
148
+
149
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.k_channels)
150
+ if self.window_size is not None:
151
+ assert t_s == t_t, "Relative attention is only available for self-attention."
152
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
153
+ rel_logits = self._matmul_with_relative_keys(query, key_relative_embeddings)
154
+ rel_logits = self._relative_position_to_absolute_position(rel_logits)
155
+ scores_local = rel_logits / math.sqrt(self.k_channels)
156
+ scores = scores + scores_local
157
+ if self.proximal_bias:
158
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
159
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device,
160
+ dtype=scores.dtype)
161
+ if mask is not None:
162
+ scores = scores.masked_fill(mask == 0, -1e4)
163
+ p_attn = torch.nn.functional.softmax(scores, dim=-1)
164
+ p_attn = self.drop(p_attn)
165
+ output = torch.matmul(p_attn, value)
166
+ if self.window_size is not None:
167
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
168
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
169
+ output = output + self._matmul_with_relative_values(relative_weights,
170
+ value_relative_embeddings)
171
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t)
172
+ return output, p_attn
173
+
174
+ def _matmul_with_relative_values(self, x, y):
175
+ ret = torch.matmul(x, y.unsqueeze(0))
176
+ return ret
177
+
178
+ def _matmul_with_relative_keys(self, x, y):
179
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
180
+ return ret
181
+
182
+ def _get_relative_embeddings(self, relative_embeddings, length):
183
+ pad_length = max(length - (self.window_size + 1), 0)
184
+ slice_start_position = max((self.window_size + 1) - length, 0)
185
+ slice_end_position = slice_start_position + 2 * length - 1
186
+ if pad_length > 0:
187
+ padded_relative_embeddings = torch.nn.functional.pad(
188
+ relative_embeddings, convert_pad_shape([[0, 0],
189
+ [pad_length, pad_length], [0, 0]]))
190
+ else:
191
+ padded_relative_embeddings = relative_embeddings
192
+ used_relative_embeddings = padded_relative_embeddings[:,
193
+ slice_start_position:slice_end_position]
194
+ return used_relative_embeddings
195
+
196
+ def _relative_position_to_absolute_position(self, x):
197
+ batch, heads, length, _ = x.size()
198
+ x = torch.nn.functional.pad(x, convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
199
+ x_flat = x.view([batch, heads, length * 2 * length])
200
+ x_flat = torch.nn.functional.pad(x_flat, convert_pad_shape([[0,0],[0,0],[0,length-1]]))
201
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
202
+ return x_final
203
+
204
+ def _absolute_position_to_relative_position(self, x):
205
+ batch, heads, length, _ = x.size()
206
+ x = torch.nn.functional.pad(x, convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
207
+ x_flat = x.view([batch, heads, length**2 + length*(length - 1)])
208
+ x_flat = torch.nn.functional.pad(x_flat, convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
209
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
210
+ return x_final
211
+
212
+ def _attention_bias_proximal(self, length):
213
+ r = torch.arange(length, dtype=torch.float32)
214
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
215
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
216
+
217
+
218
+ class FFN(BaseModule):
219
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size,
220
+ p_dropout=0.0):
221
+ super(FFN, self).__init__()
222
+ self.in_channels = in_channels
223
+ self.out_channels = out_channels
224
+ self.filter_channels = filter_channels
225
+ self.kernel_size = kernel_size
226
+ self.p_dropout = p_dropout
227
+
228
+ self.conv_1 = torch.nn.Conv1d(in_channels, filter_channels, kernel_size,
229
+ padding=kernel_size//2)
230
+ self.conv_2 = torch.nn.Conv1d(filter_channels, out_channels, kernel_size,
231
+ padding=kernel_size//2)
232
+ self.drop = torch.nn.Dropout(p_dropout)
233
+
234
+ def forward(self, x, x_mask):
235
+ x = self.conv_1(x * x_mask)
236
+ x = torch.relu(x)
237
+ x = self.drop(x)
238
+ x = self.conv_2(x * x_mask)
239
+ return x * x_mask
240
+
241
+
242
+ class Encoder(BaseModule):
243
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers,
244
+ kernel_size=1, p_dropout=0.0, window_size=None, **kwargs):
245
+ super(Encoder, self).__init__()
246
+ self.hidden_channels = hidden_channels
247
+ self.filter_channels = filter_channels
248
+ self.n_heads = n_heads
249
+ self.n_layers = n_layers
250
+ self.kernel_size = kernel_size
251
+ self.p_dropout = p_dropout
252
+ self.window_size = window_size
253
+
254
+ self.drop = torch.nn.Dropout(p_dropout)
255
+ self.attn_layers = torch.nn.ModuleList()
256
+ self.norm_layers_1 = torch.nn.ModuleList()
257
+ self.ffn_layers = torch.nn.ModuleList()
258
+ self.norm_layers_2 = torch.nn.ModuleList()
259
+ for _ in range(self.n_layers):
260
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels,
261
+ n_heads, window_size=window_size, p_dropout=p_dropout))
262
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
263
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels,
264
+ filter_channels, kernel_size, p_dropout=p_dropout))
265
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
266
+
267
+ def forward(self, x, x_mask):
268
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
269
+ for i in range(self.n_layers):
270
+ x = x * x_mask
271
+ y = self.attn_layers[i](x, x, attn_mask)
272
+ y = self.drop(y)
273
+ x = self.norm_layers_1[i](x + y)
274
+ y = self.ffn_layers[i](x, x_mask)
275
+ y = self.drop(y)
276
+ x = self.norm_layers_2[i](x + y)
277
+ x = x * x_mask
278
+ return x
279
+
280
+
281
+ class TextEncoder(BaseModule):
282
+ def __init__(self, n_vocab, n_feats, n_channels, filter_channels,
283
+ filter_channels_dp, n_heads, n_layers, kernel_size,
284
+ p_dropout, window_size=None, spk_emb_dim=64, n_spks=1):
285
+ super(TextEncoder, self).__init__()
286
+ self.n_vocab = n_vocab
287
+ self.n_feats = n_feats
288
+ self.n_channels = n_channels
289
+ self.filter_channels = filter_channels
290
+ self.filter_channels_dp = filter_channels_dp
291
+ self.n_heads = n_heads
292
+ self.n_layers = n_layers
293
+ self.kernel_size = kernel_size
294
+ self.p_dropout = p_dropout
295
+ self.window_size = window_size
296
+ self.spk_emb_dim = spk_emb_dim
297
+ self.n_spks = n_spks
298
+
299
+ self.emb = torch.nn.Embedding(n_vocab, n_channels)
300
+ torch.nn.init.normal_(self.emb.weight, 0.0, n_channels**-0.5)
301
+
302
+ self.prenet = ConvReluNorm(n_channels, n_channels, n_channels,
303
+ kernel_size=5, n_layers=3, p_dropout=0.5)
304
+
305
+ self.encoder = Encoder(n_channels + (spk_emb_dim if n_spks > 1 else 0), filter_channels, n_heads, n_layers,
306
+ kernel_size, p_dropout, window_size=window_size)
307
+
308
+ self.proj_m = torch.nn.Conv1d(n_channels + (spk_emb_dim if n_spks > 1 else 0), n_feats, 1)
309
+ self.proj_w = DurationPredictor(n_channels + (spk_emb_dim if n_spks > 1 else 0), filter_channels_dp,
310
+ kernel_size, p_dropout)
311
+
312
+ def forward(self, x, x_lengths, spk=None):
313
+ x = self.emb(x) * math.sqrt(self.n_channels)
314
+ x = torch.transpose(x, 1, -1)
315
+ x_mask = torch.unsqueeze(sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
316
+
317
+ x = self.prenet(x, x_mask)
318
+ if self.n_spks > 1:
319
+ x = torch.cat([x, spk.unsqueeze(-1).repeat(1, 1, x.shape[-1])], dim=1)
320
+ x = self.encoder(x, x_mask)
321
+ mu = self.proj_m(x) * x_mask
322
+
323
+ x_dp = torch.detach(x)
324
+ logw = self.proj_w(x_dp, x_mask)
325
+
326
+ return mu, logw, x_mask
Grad-TTS/model/tts.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import math
10
+ import random
11
+
12
+ import torch
13
+
14
+ from model import monotonic_align
15
+ from model.base import BaseModule
16
+ from model.text_encoder import TextEncoder
17
+ from model.diffusion import Diffusion
18
+ from model.utils import sequence_mask, generate_path, duration_loss, fix_len_compatibility
19
+
20
+
21
+ class GradTTS(BaseModule):
22
+ def __init__(self, n_vocab, n_spks, spk_emb_dim, n_enc_channels, filter_channels, filter_channels_dp,
23
+ n_heads, n_enc_layers, enc_kernel, enc_dropout, window_size,
24
+ n_feats, dec_dim, beta_min, beta_max, pe_scale):
25
+ super(GradTTS, self).__init__()
26
+ self.n_vocab = n_vocab
27
+ self.n_spks = n_spks
28
+ self.spk_emb_dim = spk_emb_dim
29
+ self.n_enc_channels = n_enc_channels
30
+ self.filter_channels = filter_channels
31
+ self.filter_channels_dp = filter_channels_dp
32
+ self.n_heads = n_heads
33
+ self.n_enc_layers = n_enc_layers
34
+ self.enc_kernel = enc_kernel
35
+ self.enc_dropout = enc_dropout
36
+ self.window_size = window_size
37
+ self.n_feats = n_feats
38
+ self.dec_dim = dec_dim
39
+ self.beta_min = beta_min
40
+ self.beta_max = beta_max
41
+ self.pe_scale = pe_scale
42
+
43
+ if n_spks > 1:
44
+ self.spk_emb = torch.nn.Embedding(n_spks, spk_emb_dim)
45
+ self.encoder = TextEncoder(n_vocab, n_feats, n_enc_channels,
46
+ filter_channels, filter_channels_dp, n_heads,
47
+ n_enc_layers, enc_kernel, enc_dropout, window_size)
48
+ self.decoder = Diffusion(n_feats, dec_dim, n_spks, spk_emb_dim, beta_min, beta_max, pe_scale)
49
+
50
+ @torch.no_grad()
51
+ def forward(self, x, x_lengths, n_timesteps, temperature=1.0, stoc=False, spk=None, length_scale=1.0):
52
+ """
53
+ Generates mel-spectrogram from text. Returns:
54
+ 1. encoder outputs
55
+ 2. decoder outputs
56
+ 3. generated alignment
57
+
58
+ Args:
59
+ x (torch.Tensor): batch of texts, converted to a tensor with phoneme embedding ids.
60
+ x_lengths (torch.Tensor): lengths of texts in batch.
61
+ n_timesteps (int): number of steps to use for reverse diffusion in decoder.
62
+ temperature (float, optional): controls variance of terminal distribution.
63
+ stoc (bool, optional): flag that adds stochastic term to the decoder sampler.
64
+ Usually, does not provide synthesis improvements.
65
+ length_scale (float, optional): controls speech pace.
66
+ Increase value to slow down generated speech and vice versa.
67
+ """
68
+ x, x_lengths = self.relocate_input([x, x_lengths])
69
+
70
+ if self.n_spks > 1:
71
+ # Get speaker embedding
72
+ spk = self.spk_emb(spk)
73
+
74
+ # Get encoder_outputs `mu_x` and log-scaled token durations `logw`
75
+ mu_x, logw, x_mask = self.encoder(x, x_lengths, spk)
76
+
77
+ w = torch.exp(logw) * x_mask
78
+ w_ceil = torch.ceil(w) * length_scale
79
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
80
+ y_max_length = int(y_lengths.max())
81
+ y_max_length_ = fix_len_compatibility(y_max_length)
82
+
83
+ # Using obtained durations `w` construct alignment map `attn`
84
+ y_mask = sequence_mask(y_lengths, y_max_length_).unsqueeze(1).to(x_mask.dtype)
85
+ attn_mask = x_mask.unsqueeze(-1) * y_mask.unsqueeze(2)
86
+ attn = generate_path(w_ceil.squeeze(1), attn_mask.squeeze(1)).unsqueeze(1)
87
+
88
+ # Align encoded text and get mu_y
89
+ mu_y = torch.matmul(attn.squeeze(1).transpose(1, 2), mu_x.transpose(1, 2))
90
+ mu_y = mu_y.transpose(1, 2)
91
+ encoder_outputs = mu_y[:, :, :y_max_length]
92
+
93
+ # Sample latent representation from terminal distribution N(mu_y, I)
94
+ z = mu_y + torch.randn_like(mu_y, device=mu_y.device) / temperature
95
+ # Generate sample by performing reverse dynamics
96
+ decoder_outputs = self.decoder(z, y_mask, mu_y, n_timesteps, stoc, spk)
97
+ decoder_outputs = decoder_outputs[:, :, :y_max_length]
98
+
99
+ return encoder_outputs, decoder_outputs, attn[:, :, :y_max_length]
100
+
101
+ def compute_loss(self, x, x_lengths, y, y_lengths, spk=None, out_size=None):
102
+ """
103
+ Computes 3 losses:
104
+ 1. duration loss: loss between predicted token durations and those extracted by Monotinic Alignment Search (MAS).
105
+ 2. prior loss: loss between mel-spectrogram and encoder outputs.
106
+ 3. diffusion loss: loss between gaussian noise and its reconstruction by diffusion-based decoder.
107
+
108
+ Args:
109
+ x (torch.Tensor): batch of texts, converted to a tensor with phoneme embedding ids.
110
+ x_lengths (torch.Tensor): lengths of texts in batch.
111
+ y (torch.Tensor): batch of corresponding mel-spectrograms.
112
+ y_lengths (torch.Tensor): lengths of mel-spectrograms in batch.
113
+ out_size (int, optional): length (in mel's sampling rate) of segment to cut, on which decoder will be trained.
114
+ Should be divisible by 2^{num of UNet downsamplings}. Needed to increase batch size.
115
+ """
116
+ x, x_lengths, y, y_lengths = self.relocate_input([x, x_lengths, y, y_lengths])
117
+
118
+ if self.n_spks > 1:
119
+ # Get speaker embedding
120
+ spk = self.spk_emb(spk)
121
+
122
+ # Get encoder_outputs `mu_x` and log-scaled token durations `logw`
123
+ mu_x, logw, x_mask = self.encoder(x, x_lengths, spk)
124
+ y_max_length = y.shape[-1]
125
+
126
+ y_mask = sequence_mask(y_lengths, y_max_length).unsqueeze(1).to(x_mask)
127
+ attn_mask = x_mask.unsqueeze(-1) * y_mask.unsqueeze(2)
128
+
129
+ # Use MAS to find most likely alignment `attn` between text and mel-spectrogram
130
+ with torch.no_grad():
131
+ const = -0.5 * math.log(2 * math.pi) * self.n_feats
132
+ factor = -0.5 * torch.ones(mu_x.shape, dtype=mu_x.dtype, device=mu_x.device)
133
+ y_square = torch.matmul(factor.transpose(1, 2), y ** 2)
134
+ y_mu_double = torch.matmul(2.0 * (factor * mu_x).transpose(1, 2), y)
135
+ mu_square = torch.sum(factor * (mu_x ** 2), 1).unsqueeze(-1)
136
+ log_prior = y_square - y_mu_double + mu_square + const
137
+
138
+ attn = monotonic_align.maximum_path(log_prior, attn_mask.squeeze(1))
139
+ attn = attn.detach()
140
+
141
+ # Compute loss between predicted log-scaled durations and those obtained from MAS
142
+ logw_ = torch.log(1e-8 + torch.sum(attn.unsqueeze(1), -1)) * x_mask
143
+ dur_loss = duration_loss(logw, logw_, x_lengths)
144
+
145
+ # Cut a small segment of mel-spectrogram in order to increase batch size
146
+ if not isinstance(out_size, type(None)):
147
+ max_offset = (y_lengths - out_size).clamp(0)
148
+ offset_ranges = list(zip([0] * max_offset.shape[0], max_offset.cpu().numpy()))
149
+ out_offset = torch.LongTensor([
150
+ torch.tensor(random.choice(range(start, end)) if end > start else 0)
151
+ for start, end in offset_ranges
152
+ ]).to(y_lengths)
153
+
154
+ attn_cut = torch.zeros(attn.shape[0], attn.shape[1], out_size, dtype=attn.dtype, device=attn.device)
155
+ y_cut = torch.zeros(y.shape[0], self.n_feats, out_size, dtype=y.dtype, device=y.device)
156
+ y_cut_lengths = []
157
+ for i, (y_, out_offset_) in enumerate(zip(y, out_offset)):
158
+ y_cut_length = out_size + (y_lengths[i] - out_size).clamp(None, 0)
159
+ y_cut_lengths.append(y_cut_length)
160
+ cut_lower, cut_upper = out_offset_, out_offset_ + y_cut_length
161
+ y_cut[i, :, :y_cut_length] = y_[:, cut_lower:cut_upper]
162
+ attn_cut[i, :, :y_cut_length] = attn[i, :, cut_lower:cut_upper]
163
+ y_cut_lengths = torch.LongTensor(y_cut_lengths)
164
+ y_cut_mask = sequence_mask(y_cut_lengths).unsqueeze(1).to(y_mask)
165
+
166
+ attn = attn_cut
167
+ y = y_cut
168
+ y_mask = y_cut_mask
169
+
170
+ # Align encoded text with mel-spectrogram and get mu_y segment
171
+ mu_y = torch.matmul(attn.squeeze(1).transpose(1, 2), mu_x.transpose(1, 2))
172
+ mu_y = mu_y.transpose(1, 2)
173
+
174
+ # Compute loss of score-based decoder
175
+ diff_loss, xt = self.decoder.compute_loss(y, y_mask, mu_y, spk)
176
+
177
+ # Compute loss between aligned encoder outputs and mel-spectrogram
178
+ prior_loss = torch.sum(0.5 * ((y - mu_y) ** 2 + math.log(2 * math.pi)) * y_mask)
179
+ prior_loss = prior_loss / (torch.sum(y_mask) * self.n_feats)
180
+
181
+ return dur_loss, prior_loss, diff_loss
Grad-TTS/model/utils.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/jaywalnut310/glow-tts """
2
+
3
+ import torch
4
+
5
+
6
+ def sequence_mask(length, max_length=None):
7
+ if max_length is None:
8
+ max_length = length.max()
9
+ x = torch.arange(int(max_length), dtype=length.dtype, device=length.device)
10
+ return x.unsqueeze(0) < length.unsqueeze(1)
11
+
12
+
13
+ def fix_len_compatibility(length, num_downsamplings_in_unet=2):
14
+ while True:
15
+ if length % (2**num_downsamplings_in_unet) == 0:
16
+ return length
17
+ length += 1
18
+
19
+
20
+ def convert_pad_shape(pad_shape):
21
+ l = pad_shape[::-1]
22
+ pad_shape = [item for sublist in l for item in sublist]
23
+ return pad_shape
24
+
25
+
26
+ def generate_path(duration, mask):
27
+ device = duration.device
28
+
29
+ b, t_x, t_y = mask.shape
30
+ cum_duration = torch.cumsum(duration, 1)
31
+ path = torch.zeros(b, t_x, t_y, dtype=mask.dtype).to(device=device)
32
+
33
+ cum_duration_flat = cum_duration.view(b * t_x)
34
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
35
+ path = path.view(b, t_x, t_y)
36
+ path = path - torch.nn.functional.pad(path, convert_pad_shape([[0, 0],
37
+ [1, 0], [0, 0]]))[:, :-1]
38
+ path = path * mask
39
+ return path
40
+
41
+
42
+ def duration_loss(logw, logw_, lengths):
43
+ loss = torch.sum((logw - logw_)**2) / torch.sum(lengths)
44
+ return loss
Grad-TTS/out/sample_0.wav ADDED
Binary file (230 kB). View file
 
Grad-TTS/out/sample_1.wav ADDED
Binary file (397 kB). View file
 
Grad-TTS/out/sample_2.wav ADDED
Binary file (274 kB). View file
 
Grad-TTS/params.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ from model.utils import fix_len_compatibility
10
+
11
+
12
+ # data parameters
13
+ train_filelist_path = "../../id/train.txt"
14
+ valid_filelist_path = "../../id/valid.txt"
15
+ # test_filelist_path = 'resources/filelists/ljspeech/test.txt'
16
+ cmudict_path = "resources/ipa_dictionary_id"
17
+ add_blank = True
18
+ n_feats = 80
19
+ n_spks = 2 # 247 for Libri-TTS filelist and 1 for LJSpeech
20
+ spk_emb_dim = 64
21
+ n_feats = 80
22
+ n_fft = 1024
23
+ sample_rate = 22050
24
+ hop_length = 256
25
+ win_length = 1024
26
+ f_min = 0
27
+ f_max = 8000
28
+
29
+ # encoder parameters
30
+ n_enc_channels = 192
31
+ filter_channels = 768
32
+ filter_channels_dp = 256
33
+ n_enc_layers = 6
34
+ enc_kernel = 3
35
+ enc_dropout = 0.1
36
+ n_heads = 2
37
+ window_size = 4
38
+
39
+ # decoder parameters
40
+ dec_dim = 64
41
+ beta_min = 0.05
42
+ beta_max = 20.0
43
+ pe_scale = 1000 # 1 for `grad-tts-old.pt` checkpoint
44
+
45
+ # training parameters
46
+ log_dir = "logs/grad-tts-bookbot-id"
47
+ test_size = 4
48
+ n_epochs = 2000
49
+ batch_size = 16
50
+ learning_rate = 1e-4
51
+ seed = 37
52
+ save_every = 100
53
+ out_size = fix_len_compatibility(2 * 22050 // 256)
54
+ num_workers = 6
Grad-TTS/params_en.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ from model.utils import fix_len_compatibility
10
+
11
+
12
+ # data parameters
13
+ train_filelist_path = "../../en/train.txt"
14
+ valid_filelist_path = "../../en/valid.txt"
15
+ # test_filelist_path = 'resources/filelists/ljspeech/test.txt'
16
+ cmudict_path = "resources/cmu_dictionary"
17
+ add_blank = True
18
+ n_feats = 80
19
+ n_spks = 3 # 247 for Libri-TTS filelist and 1 for LJSpeech
20
+ spk_emb_dim = 64
21
+ n_feats = 80
22
+ n_fft = 1024
23
+ sample_rate = 22050
24
+ hop_length = 256
25
+ win_length = 1024
26
+ f_min = 0
27
+ f_max = 8000
28
+
29
+ # encoder parameters
30
+ n_enc_channels = 192
31
+ filter_channels = 768
32
+ filter_channels_dp = 256
33
+ n_enc_layers = 6
34
+ enc_kernel = 3
35
+ enc_dropout = 0.1
36
+ n_heads = 2
37
+ window_size = 4
38
+
39
+ # decoder parameters
40
+ dec_dim = 64
41
+ beta_min = 0.05
42
+ beta_max = 20.0
43
+ pe_scale = 1000 # 1 for `grad-tts-old.pt` checkpoint
44
+
45
+ # training parameters
46
+ log_dir = "logs/grad-tts-bookbot-en"
47
+ test_size = 4
48
+ n_epochs = 1000
49
+ batch_size = 16
50
+ learning_rate = 1e-4
51
+ seed = 37
52
+ save_every = 100
53
+ out_size = fix_len_compatibility(2 * 22050 // 256)
54
+ num_workers = 6
Grad-TTS/requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Cython
2
+ numpy
3
+ torch
4
+ torchaudio
5
+ matplotlib
6
+ einops
7
+ inflect
8
+ Unidecode
9
+ librosa
10
+ scipy
11
+ tqdm
12
+ tensorboard
Grad-TTS/resources/cmu_dictionary ADDED
The diff for this file is too large to render. See raw diff
 
Grad-TTS/resources/cmu_dictionary_id ADDED
The diff for this file is too large to render. See raw diff
 
Grad-TTS/resources/cmu_dictionary_id_en ADDED
The diff for this file is too large to render. See raw diff
 
Grad-TTS/resources/filelists/libri-tts/train.txt ADDED
The diff for this file is too large to render. See raw diff
 
Grad-TTS/resources/filelists/libri-tts/valid.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ DUMMY/train-clean-100/103/1241/103_1241_000000_000001.wav|Matthew Cuthbert is surprised|46
2
+ DUMMY/train-clean-100/3857/182317/3857_182317_000028_000002.wav|That is the kind of hold that curiosity has on the monkeys.|120
3
+ DUMMY/train-clean-100/4406/16882/4406_16882_000025_000001.wav|I was at this time knitting a pair of white cotton stockings for my mistress; and had not yet wrought upon a Sabbath day.|94
4
+ DUMMY/train-clean-100/5339/14134/5339_14134_000041_000008.wav|The thought of poor dead Annie Coulson flashed into Philip's mind.|216
Grad-TTS/resources/filelists/ljspeech/test.txt ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DUMMY/LJ045-0096.wav|Mrs. De Mohrenschildt thought that Oswald,
2
+ DUMMY/LJ049-0022.wav|The Secret Service believed that it was very doubtful that any President would ride regularly in a vehicle with a fixed top, even though transparent.
3
+ DUMMY/LJ033-0042.wav|Between the hours of eight and nine p.m. they were occupied with the children in the bedrooms located at the extreme east end of the house.
4
+ DUMMY/LJ016-0117.wav|The prisoner had nothing to deal with but wooden panels, and by dint of cutting and chopping he got both the lower panels out.
5
+ DUMMY/LJ025-0157.wav|Under these circumstances, unnatural as they are, with proper management, the bean will thrust forth its radicle and its plumule;
6
+ DUMMY/LJ042-0219.wav|Oswald demonstrated his thinking in connection with his return to the United States by preparing two sets of identical questions of the type which he might have thought
7
+ DUMMY/LJ032-0164.wav|it is not possible to state with scientific certainty that a particular small group of fibers come from a certain piece of clothing
8
+ DUMMY/LJ046-0092.wav|has confidence in the dedicated Secret Service men who are ready to lay down their lives for him
9
+ DUMMY/LJ050-0118.wav|Since these agencies are already obliged constantly to evaluate the activities of such groups,
10
+ DUMMY/LJ043-0016.wav|Jeanne De Mohrenschildt said, quote,
11
+ DUMMY/LJ021-0078.wav|no economic panacea, which could simply revive over-night the heavy industries and the trades dependent upon them.
12
+ DUMMY/LJ039-0148.wav|Examination of the cartridge cases found on the sixth floor of the Depository Building
13
+ DUMMY/LJ047-0202.wav|testified that the information available to the Federal Government about Oswald before the assassination would, if known to PRS,
14
+ DUMMY/LJ023-0056.wav|It is an easy document to understand when you remember that it was called into being
15
+ DUMMY/LJ021-0025.wav|And in many directions, the intervention of that organized control which we call government
16
+ DUMMY/LJ030-0105.wav|Communications in the motorcade.
17
+ DUMMY/LJ021-0012.wav|with respect to industry and business, but nearly all are agreed that private enterprise in times such as these
18
+ DUMMY/LJ019-0169.wav|and one or two men were allowed to mend clothes and make shoes. The rules made by the Secretary of State were hung up in conspicuous parts of the prison;
19
+ DUMMY/LJ039-0088.wav|It just is an aid in seeing in the fact that you only have the one element, the crosshair,
20
+ DUMMY/LJ016-0192.wav|"I think I could do that sort of job," said Calcraft, on the spur of the moment.
21
+ DUMMY/LJ014-0142.wav|was strewn in front of the dock, and sprinkled it towards the bench with a contemptuous gesture.
22
+ DUMMY/LJ012-0015.wav|Weedon and Lecasser to twelve and six months respectively in Coldbath Fields.
23
+ DUMMY/LJ048-0033.wav|Prior to November twenty-two, nineteen sixty-three
24
+ DUMMY/LJ028-0349.wav|who were each required to send so large a number to Babylon, that in all there were collected no fewer than fifty thousand.
25
+ DUMMY/LJ030-0197.wav|At first Mrs. Connally thought that her husband had been killed,
26
+ DUMMY/LJ017-0133.wav|Palmer speedily found imitators.
27
+ DUMMY/LJ034-0123.wav|Although Brennan testified that the man in the window was standing when he fired the shots, most probably he was either sitting or kneeling.
28
+ DUMMY/LJ003-0282.wav|Many years were to elapse before these objections should be fairly met and universally overcome.
29
+ DUMMY/LJ032-0204.wav|Special Agent Lyndal L. Shaneyfelt, a photography expert with the FBI,
30
+ DUMMY/LJ016-0241.wav|Calcraft served the city of London till eighteen seventy-four, when he was pensioned at the rate of twenty-five shillings per week.
31
+ DUMMY/LJ023-0033.wav|we will not allow ourselves to run around in new circles of futile discussion and debate, always postponing the day of decision.
32
+ DUMMY/LJ009-0286.wav|There has never been much science in the system of carrying out the extreme penalty in this country; the "finisher of the law"
33
+ DUMMY/LJ008-0181.wav|he had his pockets filled with bread and cheese, and it was generally supposed that he had come a long distance to see the fatal show.
34
+ DUMMY/LJ015-0052.wav|to the value of twenty thousand pounds.
35
+ DUMMY/LJ016-0314.wav|Sir George Grey thought there was a growing feeling in favor of executions within the prison precincts.
36
+ DUMMY/LJ047-0056.wav|From August nineteen sixty-two
37
+ DUMMY/LJ010-0027.wav|Nor did the methods by which they were perpetrated greatly vary from those in times past.
38
+ DUMMY/LJ010-0065.wav|At the former the "Provisional Government" was to be established,
39
+ DUMMY/LJ046-0113.wav|The Commission has concluded that at the time of the assassination
40
+ DUMMY/LJ028-0410.wav|There among the ruins they still live in the same kind of houses,
41
+ DUMMY/LJ044-0137.wav|More seriously, the facts of his defection had become known, leaving him open to almost unanswerable attack by those who opposed his views.
42
+ DUMMY/LJ008-0215.wav|One by one the huge uprights of black timber were fitted together,
43
+ DUMMY/LJ030-0084.wav|or when the press of the crowd made it impossible for the escort motorcycles to stay in position on the car's rear flanks.
44
+ DUMMY/LJ020-0092.wav|Have yourself called on biscuit mornings an hour earlier than usual.
45
+ DUMMY/LJ029-0096.wav|On November fourteen, Lawson and Sorrels attended a meeting at Love Field
46
+ DUMMY/LJ015-0308.wav|and others who swore to the meetings of the conspirators and their movements. Saward was found guilty,
47
+ DUMMY/LJ012-0067.wav|But Mrs. Solomons could not resist the temptation to dabble in stolen goods, and she was found shipping watches of the wrong category to New York.
48
+ DUMMY/LJ018-0231.wav|namely, to suppress it and substitute another.
49
+ DUMMY/LJ014-0265.wav|and later he became manager of the newly rebuilt Olympic at Wych Street.
50
+ DUMMY/LJ024-0102.wav|would be the first to exclaim as soon as an amendment was proposed
51
+ DUMMY/LJ007-0233.wav|it consists of several circular perforations, about two inches in diameter,
52
+ DUMMY/LJ032-0045.wav|This price included nineteen dollars, ninety-five cents for the rifle and the scope, and one dollar, fifty cents for postage and handling.
53
+ DUMMY/LJ011-0048.wav|Wherefore let him that thinketh he standeth take heed lest he fall," and was full of the most pointed allusions to the culprit.
54
+ DUMMY/LJ005-0294.wav|It was frequently stated in evidence that the jail of the borough was in so unfit a state for the reception of prisoners,
55
+ DUMMY/LJ016-0007.wav|There were others less successful.
56
+ DUMMY/LJ028-0138.wav|perhaps the tales that travelers told him were exaggerated as travelers' tales are likely to be,
57
+ DUMMY/LJ050-0029.wav|that is reflected in definite and comprehensive operating procedures.
58
+ DUMMY/LJ014-0121.wav|The prisoners were in due course transferred to Newgate, to be put upon their trial at the Central Criminal Court.
59
+ DUMMY/LJ014-0146.wav|They had to handcuff her by force against the most violent resistance, and still she raged and stormed,
60
+ DUMMY/LJ046-0111.wav|The Secret Service has attempted to perform this function through the activities of its Protective Research Section
61
+ DUMMY/LJ012-0257.wav|But the affair still remained a profound mystery. No light was thrown upon it till, towards the end of March,
62
+ DUMMY/LJ002-0260.wav|Yet the public opinion of the whole body seems to have checked dissipation.
63
+ DUMMY/LJ031-0014.wav|the Presidential limousine arrived at the emergency entrance of the Parkland Hospital at about twelve:thirty-five p.m.
64
+ DUMMY/LJ047-0093.wav|Oswald was arrested and jailed by the New Orleans Police Department for disturbing the peace, in connection with a street fight which broke out when he was accosted
65
+ DUMMY/LJ003-0324.wav|gaming of all sorts should be peremptorily forbidden under heavy pains and penalties.
66
+ DUMMY/LJ021-0115.wav|we have reached into the heart of the problem which is to provide such annual earnings for the lowest paid worker as will meet his minimum needs.
67
+ DUMMY/LJ046-0191.wav|it had established periodic regular review of the status of four hundred individuals;
68
+ DUMMY/LJ034-0197.wav|who was one of the first witnesses to alert the police to the Depository as the source of the shots, as has been discussed in chapter three.
69
+ DUMMY/LJ002-0253.wav|were governed by rules which they themselves had framed, and under which subscriptions were levied
70
+ DUMMY/LJ048-0288.wav|might have been more alert in the Dallas motorcade if they had retired promptly in Fort Worth.
71
+ DUMMY/LJ007-0112.wav|Many of the old customs once prevalent in the State Side, so properly condemned and abolished,
72
+ DUMMY/LJ017-0189.wav|who was presently attacked in the same way as the others, but, but, thanks to the prompt administration of remedies, he recovered.
73
+ DUMMY/LJ042-0230.wav|basically, although I hate the USSR and socialist system I still think marxism can work under different circumstances, end quote.
74
+ DUMMY/LJ050-0161.wav|The Secret Service should not and does not plan to develop its own intelligence gathering facilities to duplicate the existing facilities of other Federal agencies.
75
+ DUMMY/LJ003-0011.wav|that not more than one bottle of wine or one quart of beer could be issued at one time. No account was taken of the amount of liquors admitted in one day,
76
+ DUMMY/LJ008-0206.wav|and caused a number of stout additional barriers to be erected in front of the scaffold,
77
+ DUMMY/LJ002-0261.wav|The poorer prisoners were not in abject want, as in other prisons,
78
+ DUMMY/LJ019-0317.wav|The former, which consisted principally of the tread-wheel, cranks, capstans, shot-drill,
79
+ DUMMY/LJ011-0041.wav|Visited Mr. Fauntleroy. My application for books for him not having been attended, I had no prayer-book to give him.
80
+ DUMMY/LJ023-0089.wav|That is not only my accusation.
81
+ DUMMY/LJ044-0224.wav|would not agree with that particular wording, end quote.
82
+ DUMMY/LJ013-0104.wav|He found them at length residing at the latter place, one as a landed proprietor, the other as a publican.
83
+ DUMMY/LJ013-0055.wav|The jury did not believe him, and the verdict was for the defendants.
84
+ DUMMY/LJ014-0306.wav|These had been attributed to political action; some thought that the large purchases in foreign grains, effected at losing prices,
85
+ DUMMY/LJ029-0052.wav|To supplement the PRS files, the Secret Service depends largely on local police departments and local offices of other Federal agencies
86
+ DUMMY/LJ028-0459.wav|Its bricks, measuring about thirteen inches square and three inches in thickness, were burned and stamped with the usual short inscription:
87
+ DUMMY/LJ017-0183.wav|Soon afterwards Dixon died, showing all the symptoms already described.
88
+ DUMMY/LJ009-0084.wav|At length the ordinary pauses, and then, in a deep tone, which, though hardly above a whisper, is audible to all, says,
89
+ DUMMY/LJ007-0170.wav|That in this vast metropolis, the center of wealth, civilization, and information;
90
+ DUMMY/LJ019-0201.wav|to select a sufficiently spacious piece of ground, and erect a prison which from foundations to roofs should be in conformity with the newest ideas.
91
+ DUMMY/LJ030-0063.wav|He had repeated this wish only a few days before, during his visit to Tampa, Florida.
92
+ DUMMY/LJ010-0257.wav|a third miscreant made a similar but far less serious attempt in the month of July following.
93
+ DUMMY/LJ009-0106.wav|The keeper tries to appear unmoved, but his eye wanders anxiously over the combustible assembly.
94
+ DUMMY/LJ008-0121.wav|After the construction and action of the machine had been explained, the doctor asked the governor what kind of men he had commanded at Goree,
95
+ DUMMY/LJ050-0069.wav|the Secret Service had received from the FBI some nine thousand reports on members of the Communist Party.
96
+ DUMMY/LJ006-0202.wav|The news-vendor was also a tobacconist,
97
+ DUMMY/LJ012-0230.wav|Shortly before the day fixed for execution, Bishop made a full confession, the bulk of which bore the impress of truth,
98
+ DUMMY/LJ005-0248.wav|and stated that in his opinion Newgate, as the common jail of Middlesex, was wholly inadequate to the proper confinement of its prisoners.
99
+ DUMMY/LJ037-0053.wav|who had been greatly upset by her experience, was able to view a lineup of four men handcuffed together at the police station.
100
+ DUMMY/LJ045-0177.wav|For the first time
101
+ DUMMY/LJ004-0036.wav|it was hoped that their rulers would hire accommodation in the county prisons, and that the inferior establishments would in course of time disappear.
102
+ DUMMY/LJ026-0054.wav|carbohydrates (starch, cellulose) and fats.
103
+ DUMMY/LJ020-0085.wav|Break apart from one another and pile on a plate, throwing a clean doily or a small napkin over them. Break open at table.
104
+ DUMMY/LJ046-0226.wav|The several military intelligence agencies reported crank mail and similar threats involving the President.
105
+ DUMMY/LJ014-0233.wav|he shot an old soldier who had attempted to detain him. He was convicted and executed.
106
+ DUMMY/LJ033-0152.wav|The portion of the palm which was identified was the heel of the right palm, i.e., the area near the wrist, on the little finger side.
107
+ DUMMY/LJ004-0009.wav|as indefatigable and self-sacrificing, found by personal visitation that the condition of jails throughout the kingdom was,
108
+ DUMMY/LJ017-0134.wav|Within a few weeks occurred the Leeds poisoning case, in which the murderer undoubtedly was inspired by the facts made public at Palmer's trial.
109
+ DUMMY/LJ019-0318.wav|was to be the rule for all convicted prisoners throughout the early stages of their detention;
110
+ DUMMY/LJ020-0093.wav|Rise, wash face and hands, rinse the mouth out and brush back the hair.
111
+ DUMMY/LJ012-0188.wav|Probert was then admitted as a witness, and the case was fully proved against Thurtell, who was hanged in front of Hertford Jail.
112
+ DUMMY/LJ019-0202.wav|The preference given to the Pentonville system destroyed all hopes of a complete reformation of Newgate.
113
+ DUMMY/LJ039-0027.wav|Oswald's revolver
114
+ DUMMY/LJ040-0176.wav|He admitted to fantasies about being powerful and sometimes hurting and killing people, but refused to elaborate on them.
115
+ DUMMY/LJ018-0354.wav|Doubts were long entertained whether Thomas Wainwright,
116
+ DUMMY/LJ031-0185.wav|From the Presidential airplane, the Vice President telephoned Attorney General Robert F. Kennedy,
117
+ DUMMY/LJ006-0137.wav|They were not obliged to attend chapel, and seldom if ever went; "prisoners," said one of them under examination, "did not like the trouble of going to chapel."
118
+ DUMMY/LJ032-0085.wav|The Hidell signature on the notice of classification was in the handwriting of Oswald.
119
+ DUMMY/LJ009-0037.wav|the schoolmaster and the juvenile prisoners being seated round the communion-table, opposite the pulpit.
120
+ DUMMY/LJ006-0021.wav|Later on he had devoted himself to the personal investigation of the prisons of the United States.
121
+ DUMMY/LJ006-0082.wav|and this particular official took excellent care to select as residents for his own ward those most suitable from his own point of view.
122
+ DUMMY/LJ016-0380.wav|with hope to the last. There is always the chance of a flaw in the indictment, of a missing witness, or extenuating circumstances.
123
+ DUMMY/LJ019-0344.wav|monitor, or schoolmaster, nor to be engaged in the service of any officer of the prison.
124
+ DUMMY/LJ019-0161.wav|These disciplinary improvements were, however, only slowly and gradually introduced.
125
+ DUMMY/LJ028-0145.wav|And here I may not omit to tell the use to which the mould dug out of the great moat was turned, nor the manner wherein the wall was wrought.
126
+ DUMMY/LJ018-0349.wav|His disclaimer, distinct and detailed on every point, was intended simply for effect.
127
+ DUMMY/LJ043-0010.wav|Some of the members of that group saw a good deal of the Oswalds through the fall of nineteen sixty-three,
128
+ DUMMY/LJ027-0178.wav|These were undoubtedly perennibranchs. In the Permian and Triassic higher forms appeared, which were certainly caducibranch.
129
+ DUMMY/LJ041-0070.wav|He did not rise above the rank of private first class, even though he had passed a qualifying examination for the rank of corporal.
130
+ DUMMY/LJ008-0266.wav|Thus in the years between May first, eighteen twenty-seven, and thirtieth April, eighteen thirty-one,
131
+ DUMMY/LJ021-0091.wav|In this recent reorganization we have recognized three distinct functions:
132
+ DUMMY/LJ019-0129.wav|which marked the growth of public interest in prison affairs, and which was the germ of the new system
133
+ DUMMY/LJ018-0215.wav|William Roupell was the eldest but illegitimate son of a wealthy man who subsequently married Roupell's mother, and had further legitimate issue.
134
+ DUMMY/LJ015-0194.wav|and behaved so as to justify a belief that he had been a jail-bird all his life.
135
+ DUMMY/LJ016-0137.wav|that numbers of men, "lifers," and others with ten, fourteen, or twenty years to do, can be trusted to work out of doors without bolts and bars
136
+ DUMMY/LJ002-0289.wav|the latter raised eighteen pence among them to pay for a truss of straw for the poor woman to lie on.
137
+ DUMMY/LJ023-0016.wav|In nineteen thirty-three you and I knew that we must never let our economic system get completely out of joint again
138
+ DUMMY/LJ011-0141.wav|There were at the moment in Newgate six convicts sentenced to death for forging wills.
139
+ DUMMY/LJ016-0283.wav|to do them mere justice, there was at least till then a half-drunken ribald gaiety among the crowd that made them all akin."
140
+ DUMMY/LJ035-0082.wav|The only interval was the time necessary to ride in the elevator from the second to the sixth floor and walk back to the southeast corner.
141
+ DUMMY/LJ045-0194.wav|Anyone who was familiar with that area of Dallas would have known that the motorcade would probably pass the Texas School Book Depository to get from Main Street
142
+ DUMMY/LJ009-0124.wav|occupied when they saw it last, but a few hours ago, by their comrades who are now dead;
143
+ DUMMY/LJ030-0162.wav|In the Presidential Limousine
144
+ DUMMY/LJ050-0223.wav|The plan provides for an additional two hundred five agents for the Secret Service. Seventeen of this number are proposed for the Protective Research Section;
145
+ DUMMY/LJ008-0228.wav|their harsh and half-cracked voices full of maudlin, besotted sympathy for those about to die.
146
+ DUMMY/LJ002-0096.wav|The eight courts above enumerated were well supplied with water;
147
+ DUMMY/LJ018-0288.wav|After this the other conspirators traveled to obtain genuine bills and master the system of the leading houses at home and abroad.
148
+ DUMMY/LJ002-0106.wav|in which latterly a copper had been fixed for the cooking of provisions sent in by charitable persons.
149
+ DUMMY/LJ025-0129.wav|On each lobe of the bi-lobed leaf of Venus flytrap are three delicate filaments which stand out at right angles from the surface of the leaf.
150
+ DUMMY/LJ044-0013.wav|Hands Off Cuba, end quote, an application form for, and a membership card in,
151
+ DUMMY/LJ049-0115.wav|of the person who is actually in the exercise of the executive power, or
152
+ DUMMY/LJ019-0145.wav|But reformation was only skin deep. Below the surface many of the old evils still rankled.
153
+ DUMMY/LJ019-0355.wav|came up in all respects to modern requirements.
154
+ DUMMY/LJ019-0289.wav|There was unrestrained association of untried and convicted, juvenile with adult prisoners, vagrants, misdemeanants, felons.
155
+ DUMMY/LJ048-0222.wav|in Fort Worth, there occurred a breach of discipline by some members of the Secret Service who were officially traveling with the President.
156
+ DUMMY/LJ016-0367.wav|Under the new system the whole of the arrangements from first to last fell upon the officers.
157
+ DUMMY/LJ047-0097.wav|Agent Quigley did not know of Oswald's prior FBI record when he interviewed him,
158
+ DUMMY/LJ007-0075.wav|as effectually to rebuke and abash the profane spirit of the more insolent and daring of the criminals.
159
+ DUMMY/LJ047-0022.wav|provided by other agencies.
160
+ DUMMY/LJ007-0085.wav|at Newgate and York Castle as long as five years; "at Ilchester and Morpeth for seven years; at Warwick for eight years,
161
+ DUMMY/LJ047-0075.wav|Hosty had inquired earlier and found no evidence that it was functioning in the Dallas area.
162
+ DUMMY/LJ008-0098.wav|One was the "yeoman of the halter," a Newgate official, the executioner's assistant, whom Mr. J. T. Smith, who was present at the execution,
163
+ DUMMY/LJ017-0102.wav|The second attack was fatal, and ended in Cook's death from tetanus.
164
+ DUMMY/LJ046-0105.wav|Second, the adequacy of other advance preparations for the security of the President, during his visit to Dallas,
165
+ DUMMY/LJ018-0206.wav|He was a tall, slender man, with a long face and iron-gray hair.
166
+ DUMMY/LJ012-0271.wav|Whether it was greed or a quarrel that drove Greenacre to the desperate deed remains obscure.
167
+ DUMMY/LJ005-0086.wav|with such further separation as the justices should deem conducive to good order and discipline.
168
+ DUMMY/LJ042-0097.wav|and considerably better living quarters than those accorded to Soviet citizens of equal age and station.
169
+ DUMMY/LJ047-0126.wav|we would handle it in due course, in accord with the whole context of the investigation. End quote.
170
+ DUMMY/LJ041-0022.wav|Oswald first wrote, quote, Edward Vogel, end quote, an obvious misspelling of Voebel's name,
171
+ DUMMY/LJ015-0025.wav|The bank enjoyed an excellent reputation, it had a good connection, and was supposed to be perfectly sound.
172
+ DUMMY/LJ012-0194.wav|But Burke and Hare had their imitators further south,
173
+ DUMMY/LJ028-0416.wav|(if man may speak so confidently of His great impenetrable counsels), for an eternal Testimony of His great work in the confusion of Man's pride,
174
+ DUMMY/LJ007-0130.wav|are all huddled together without discrimination, oversight, or control."
175
+ DUMMY/LJ015-0005.wav|About this time Davidson and Gordon, the people above-mentioned,
176
+ DUMMY/LJ014-0224.wav|As Dwyer survived, Cannon escaped the death sentence, which was commuted to penal servitude for life.
177
+ DUMMY/LJ005-0019.wav|refuted by abundant evidence, and having no foundation whatever in truth.
178
+ DUMMY/LJ042-0221.wav|With either great ambivalence, or cold calculation he prepared completely different answers to the same questions.
179
+ DUMMY/LJ001-0063.wav|which was generally more formally Gothic than the printing of the German workmen,
180
+ DUMMY/LJ030-0006.wav|They took off in the Presidential plane, Air Force One, at eleven a.m., arriving at San Antonio at one:thirty p.m., Eastern Standard Time.
181
+ DUMMY/LJ024-0054.wav|democracy will have failed far beyond the importance to it of any king of precedent concerning the judiciary.
182
+ DUMMY/LJ006-0044.wav|the same callous indifference to the moral well-being of the prisoners, the same want of employment and of all disciplinary control.
183
+ DUMMY/LJ039-0154.wav|four point eight to five point six seconds if the second shot missed,
184
+ DUMMY/LJ050-0090.wav|they seem unduly restrictive in continuing to require some manifestation of animus against a Government official.
185
+ DUMMY/LJ028-0421.wav|it was the beginning of the great collections of Babylonian antiquities in the museums of the Western world.
186
+ DUMMY/LJ033-0205.wav|then I would say the possibility exists, these fibers could have come from this blanket, end quote.
187
+ DUMMY/LJ019-0335.wav|The books and journals he was to keep were minutely specified, and his constant presence in or near the jail was insisted upon.
188
+ DUMMY/LJ013-0045.wav|Wallace's relations warned him against his Liverpool friend,
189
+ DUMMY/LJ037-0002.wav|Chapter four. The Assassin: Part six.
190
+ DUMMY/LJ018-0159.wav|This was all the police wanted to know.
191
+ DUMMY/LJ026-0140.wav|In the plant as in the animal metabolism must consist of anabolic and catabolic processes.
192
+ DUMMY/LJ014-0171.wav|I will briefly describe one or two of the more remarkable murders in the years immediately following, then pass on to another branch of crime.
193
+ DUMMY/LJ037-0007.wav|Three others subsequently identified Oswald from a photograph.
194
+ DUMMY/LJ033-0174.wav|microscopic and UV (ultra violet) characteristics, end quote.
195
+ DUMMY/LJ040-0110.wav|he apparently adjusted well enough there to have had an average, although gradually deteriorating, school record
196
+ DUMMY/LJ039-0192.wav|he had a total of between four point eight and five point six seconds between the two shots which hit
197
+ DUMMY/LJ032-0261.wav|When he appeared before the Commission, Michael Paine lifted the blanket
198
+ DUMMY/LJ040-0097.wav|Lee was brought up in this atmosphere of constant money problems, and I am sure it had quite an effect on him, and also Robert, end quote.
199
+ DUMMY/LJ037-0249.wav|Mrs. Earlene Roberts, the housekeeper at Oswald's roominghouse and the last person known to have seen him before he reached tenth Street and Patton Avenue,
200
+ DUMMY/LJ016-0248.wav|Marwood was proud of his calling, and when questioned as to whether his process was satisfactory, replied that he heard "no complaints."
201
+ DUMMY/LJ004-0083.wav|As Mr. Buxton pointed out, many old acts of parliament designed to protect the prisoner were still in full force.
202
+ DUMMY/LJ014-0029.wav|This was Delarue's watch, fully identified as such, which Hocker told his brother Delarue had given him the morning of the murder.
203
+ DUMMY/LJ021-0110.wav|have been best calculated to promote industrial recovery and a permanent improvement of business and labor conditions.
204
+ DUMMY/LJ039-0076.wav|Ronald Simmons, chief of the U.S. Army Infantry Weapons Evaluation Branch of the Ballistics Research Laboratory, said, quote,
205
+ DUMMY/LJ016-0347.wav|had undoubtedly a solemn, impressive effect upon those outside.
206
+ DUMMY/LJ001-0072.wav|After the end of the fifteenth century the degradation of printing, especially in Germany and Italy,
207
+ DUMMY/LJ024-0018.wav|Consequently, although there never can be more than fifteen, there may be only fourteen, or thirteen, or twelve.
208
+ DUMMY/LJ032-0180.wav|that the fibers were caught in the crevice of the rifle's butt plate, quote, in the recent past, end quote,
209
+ DUMMY/LJ010-0083.wav|and measures taken to arrest them when their plans were so far developed that no doubt could remain as to their guilt.
210
+ DUMMY/LJ002-0299.wav|and gave the garnish for the common side at that sum, which is five shillings more than Mr. Neild says was extorted on the common side.
211
+ DUMMY/LJ048-0143.wav|the Secret Service did not at the time of the assassination have any established procedure governing its relationships with them.
212
+ DUMMY/LJ012-0054.wav|Solomons, while waiting to appear in court, persuaded the turnkeys to take him to a public-house, where all might "refresh."
213
+ DUMMY/LJ019-0270.wav|Vegetables, especially the potato, that most valuable anti-scorbutic, was too often omitted.
214
+ DUMMY/LJ035-0164.wav|three minutes after the shooting.
215
+ DUMMY/LJ014-0326.wav|Maltby and Co. would issue warrants on them deliverable to the importer, and the goods were then passed to be stored in neighboring warehouses.
216
+ DUMMY/LJ001-0173.wav|The essential point to be remembered is that the ornament, whatever it is, whether picture or pattern-work, should form part of the page,
217
+ DUMMY/LJ050-0056.wav|On December twenty-six, nineteen sixty-three, the FBI circulated additional instructions to all its agents,
218
+ DUMMY/LJ003-0319.wav|provided only that their security was not jeopardized, and dependent upon the enforcement of another new rule,
219
+ DUMMY/LJ006-0040.wav|The fact was that the years as they passed, nearly twenty in all, had worked but little permanent improvement in this detestable prison.
220
+ DUMMY/LJ017-0231.wav|His body was found lying in a pool of blood in a night-dress, stabbed over and over again in the left side.
221
+ DUMMY/LJ004-0239.wav|He had been committed for an offense for which he was acquitted.
222
+ DUMMY/LJ048-0112.wav|The Commission also regards the security arrangements worked out by Lawson and Sorrels at Love Field as entirely adequate.
223
+ DUMMY/LJ039-0125.wav|that Oswald was a good shot, somewhat better than or equal to -- better than the average let us say.
224
+ DUMMY/LJ030-0196.wav|He cried out, quote, Oh, no, no, no. My God, they are going to kill us all, end quote,
225
+ DUMMY/LJ010-0228.wav|He was released from Broadmoor in eighteen seventy-eight, and went abroad.
226
+ DUMMY/LJ045-0228.wav|On the other hand, he could have traveled some distance with the money he did have and he did return to his room where he obtained his revolver.
227
+ DUMMY/LJ028-0168.wav|in the other was the sacred precinct of Jupiter Belus,
228
+ DUMMY/LJ021-0140.wav|and in such an effort we should be able to secure for employers and employees and consumers
229
+ DUMMY/LJ003-0159.wav|To constitute this the aristocratic quarter, unwarrantable demands were made upon the space properly allotted to the female felons,
230
+ DUMMY/LJ016-0274.wav|and the windows of the opposite houses, which commanded a good view, as usual fetched high prices.
231
+ DUMMY/LJ035-0014.wav|it sounded high and I immediately kind of looked up,
232
+ DUMMY/LJ033-0120.wav|which he believed was where the bag reached when it was laid on the seat with one edge against the door.
233
+ DUMMY/LJ045-0015.wav|which Johnson said he did not receive until after the assassination. The letter said in part, quote,
234
+ DUMMY/LJ003-0299.wav|the latter end of the nineteenth century, several of which still fall far short of our English ideal,
235
+ DUMMY/LJ032-0206.wav|After comparing the rifle in the simulated photograph with the rifle in Exhibit Number one thirty-three A, Shaneyfelt testified, quote,
236
+ DUMMY/LJ028-0494.wav|Between the several sections were wide spaces where foot soldiers and charioteers might fight.
237
+ DUMMY/LJ005-0099.wav|and report at length upon the condition of the prisons of the country.
238
+ DUMMY/LJ015-0144.wav|developed to a colossal extent the frauds he had already practiced as a subordinate.
239
+ DUMMY/LJ019-0221.wav|It was intended as far as possible that, except awaiting trial, no prisoner should find himself relegated to Newgate.
240
+ DUMMY/LJ003-0088.wav|in one, for seven years -- that of a man sentenced to death, for whom great interest had been made, but whom it was not thought right to pardon.
241
+ DUMMY/LJ045-0216.wav|nineteen sixty-three, merely to disarm her and to provide a justification of sorts,
242
+ DUMMY/LJ042-0135.wav|that he was not yet twenty years old when he went to the Soviet Union with such high hopes and not quite twenty-three when he returned bitterly disappointed.
243
+ DUMMY/LJ049-0196.wav|On the other hand, it is urged that all features of the protection of the President and his family should be committed to an elite and independent corps.
244
+ DUMMY/LJ018-0278.wav|This was the well and astutely devised plot of the brothers Bidwell,
245
+ DUMMY/LJ030-0238.wav|and then looked around again and saw more of this movement, and so I proceeded to go to the back seat and get on top of him.
246
+ DUMMY/LJ018-0309.wav|where probably the money still remains.
247
+ DUMMY/LJ041-0199.wav|is shown most clearly by his employment relations after his return from the Soviet Union. Of course, he made his real problems worse to the extent
248
+ DUMMY/LJ007-0076.wav|The lax discipline maintained in Newgate was still further deteriorated by the presence of two other classes of prisoners who ought never to have been inmates of such a jail.
249
+ DUMMY/LJ039-0118.wav|He had high motivation. He had presumably a good to excellent rifle and good ammunition.
250
+ DUMMY/LJ024-0019.wav|And there may be only nine.
251
+ DUMMY/LJ008-0085.wav|The fire had not quite burnt out at twelve, in nearly four hours, that is to say.
252
+ DUMMY/LJ018-0031.wav|This fixed the crime pretty certainly upon Müller, who had already left the country, thus increasing suspicion under which he lay.
253
+ DUMMY/LJ030-0032.wav|Dallas police stood at intervals along the fence and Dallas plain clothes men mixed in the crowd.
254
+ DUMMY/LJ050-0004.wav|General Supervision of the Secret Service
255
+ DUMMY/LJ039-0096.wav|This is a definite advantage to the shooter, the vehicle moving directly away from him and the downgrade of the street, and he being in an elevated position
256
+ DUMMY/LJ041-0195.wav|Oswald's interest in Marxism led some people to avoid him,
257
+ DUMMY/LJ047-0158.wav|After a moment's hesitation, she told me that he worked at the Texas School Book Depository near the downtown area of Dallas.
258
+ DUMMY/LJ050-0162.wav|In planning its data processing techniques,
259
+ DUMMY/LJ001-0051.wav|and paying great attention to the "press work" or actual process of printing,
260
+ DUMMY/LJ028-0136.wav|Of all the ancient descriptions of the famous walls and the city they protected, that of Herodotus is the fullest.
261
+ DUMMY/LJ034-0134.wav|Shortly after the assassination Brennan noticed
262
+ DUMMY/LJ019-0348.wav|Every facility was promised. The sanction of the Secretary of State would not be withheld if plans and estimates were duly submitted,
263
+ DUMMY/LJ010-0219.wav|While one stood over the fire with the papers, another stood with lighted torch to fire the house.
264
+ DUMMY/LJ011-0245.wav|Mr. Mullay called again, taking with him five hundred pounds in cash. Howard discovered this, and his manner was very suspicious;
265
+ DUMMY/LJ030-0035.wav|Organization of the Motorcade
266
+ DUMMY/LJ044-0135.wav|While he had drawn some attention to himself and had actually appeared on two radio programs, he had been attacked by Cuban exiles and arrested,
267
+ DUMMY/LJ045-0090.wav|He was very much interested in autobiographical works of outstanding statesmen of the United States, to whom his wife thought he compared himself.
268
+ DUMMY/LJ026-0034.wav|When any given "protist" has to be classified the case must be decided on its individual merits;
269
+ DUMMY/LJ045-0092.wav|as to the fact that he was an outstanding man, end quote.
270
+ DUMMY/LJ036-0104.wav|Whaley picked Oswald.
271
+ DUMMY/LJ019-0055.wav|High authorities were in favor of continuous separation.
272
+ DUMMY/LJ010-0030.wav|The brutal ferocity of the wild beast once aroused, the same means, the same weapons were employed to do the dreadful deed,
273
+ DUMMY/LJ038-0047.wav|Some of the officers saw Oswald strike McDonald with his fist. Most of them heard a click which they assumed to be a click of the hammer of the revolver.
274
+ DUMMY/LJ009-0074.wav|Let us pass on.
275
+ DUMMY/LJ048-0069.wav|Efforts made by the Bureau since the assassination, on the other hand,
276
+ DUMMY/LJ003-0211.wav|They were never left quite alone for fear of suicide, and for the same reason they were searched for weapons or poisons.
277
+ DUMMY/LJ048-0053.wav|It is the conclusion of the Commission that, even in the absence of Secret Service criteria
278
+ DUMMY/LJ033-0093.wav|Frazier estimated that the bag was two feet long, quote, give and take a few inches, end quote, and about five or six inches wide.
279
+ DUMMY/LJ006-0149.wav|The turnkeys left the prisoners very much to themselves, never entering the wards after locking-up time, at dusk, till unlocking next morning,
280
+ DUMMY/LJ018-0211.wav|The false coin was bought by an agent from an agent, and dealings were carried on secretly at the "Clock House" in Seven Dials.
281
+ DUMMY/LJ008-0054.wav|This contrivance appears to have been copied with improvements from that which had been used in Dublin at a still earlier date,
282
+ DUMMY/LJ040-0052.wav|that his commitment to Marxism was an important factor influencing his conduct during his adult years.
283
+ DUMMY/LJ028-0023.wav|Two weeks pass, and at last you stand on the eastern edge of the plateau
284
+ DUMMY/LJ009-0184.wav|Lord Ferrers' body was brought to Surgeons' Hall after execution in his own carriage and six;
285
+ DUMMY/LJ005-0252.wav|A committee was appointed, under the presidency of the Duke of Richmond
286
+ DUMMY/LJ015-0266.wav|has probably no parallel in the annals of crime. Saward himself is a striking and in some respects an unique figure in criminal history.
287
+ DUMMY/LJ017-0059.wav|even after sentence, and until within a few hours of execution, he was buoyed up with the hope of reprieve.
288
+ DUMMY/LJ024-0034.wav|What do they mean by the words "packing the Court"?
289
+ DUMMY/LJ016-0089.wav|He was engaged in whitewashing and cleaning; the officer who had him in charge left him on the stairs leading to the gallery.
290
+ DUMMY/LJ039-0227.wav|with two hits, within four point eight and five point six seconds.
291
+ DUMMY/LJ001-0096.wav|have now come into general use and are obviously a great improvement on the ordinary "modern style" in use in England, which is in fact the Bodoni type
292
+ DUMMY/LJ018-0129.wav|who threatened to betray the theft. But Brewer, either before or after this, succumbed to temptation,
293
+ DUMMY/LJ010-0157.wav|and that, as he was starving, he had resolved on this desperate deed,
294
+ DUMMY/LJ038-0264.wav|He concluded that, quote, the general rifling characteristics of the rifle are of the same type as those found on the bullet
295
+ DUMMY/LJ031-0165.wav|When security arrangements at the airport were complete, the Secret Service made the necessary arrangements for the Vice President to leave the hospital.
296
+ DUMMY/LJ018-0244.wav|The effect of establishing the forgeries would be to restore to the Roupell family lands for which a price had already been paid
297
+ DUMMY/LJ007-0071.wav|in the face of impediments confessedly discouraging
298
+ DUMMY/LJ028-0340.wav|Such of the Babylonians as witnessed the treachery took refuge in the temple of Jupiter Belus;
299
+ DUMMY/LJ017-0164.wav|with the idea of subjecting her to the irritant poison slowly but surely until the desired effect, death, was achieved.
300
+ DUMMY/LJ048-0197.wav|I then told the officers that their primary duty was traffic and crowd control and that they should be alert for any persons who might attempt to throw anything
301
+ DUMMY/LJ013-0098.wav|Mr. Oxenford having denied that he had made any transfer of stock, the matter was at once put into the hands of the police.
302
+ DUMMY/LJ012-0049.wav|led him to think seriously of trying his fortunes in another land.
303
+ DUMMY/LJ030-0014.wav|quote, that the crowd was about the same as the one which came to see him before but there were one hundred thousand extra people on hand who came to see Mrs. Kennedy.
304
+ DUMMY/LJ014-0186.wav|A milliner's porter,
305
+ DUMMY/LJ015-0027.wav|Yet even so early as the death of the first Sir John Paul,
306
+ DUMMY/LJ047-0049.wav|Marina Oswald, however, recalled that her husband was upset by this interview.
307
+ DUMMY/LJ003-0140.wav|otherwise he would have been stripped of his clothes. End quote.
308
+ DUMMY/LJ042-0130.wav|Shortly thereafter, less than eighteen months after his defection, about six weeks before he met Marina Prusakova,
309
+ DUMMY/LJ017-0108.wav|He was struck with the appearance of the corpse, which was not emaciated, as after a long disease ending in death;
310
+ DUMMY/LJ006-0268.wav|Women saw men if they merely pretended to be wives; even boys were visited by their sweethearts.
311
+ DUMMY/LJ044-0125.wav|of residence in the U.S.S.R. against any cause which I join, by association,
312
+ DUMMY/LJ015-0231.wav|It was Tester's business, who had access to the railway company's books, to watch for this.
313
+ DUMMY/LJ002-0225.wav|The rentals of rooms and fees went to the warden, whose income was two thousand three hundred seventy-two pounds.
314
+ DUMMY/LJ034-0072.wav|The employees raced the elevators to the first floor. Givens saw Oswald standing at the gate on the fifth floor as the elevator went by.
315
+ DUMMY/LJ045-0033.wav|He began to treat me better. He helped me more -- although he always did help. But he was more attentive, end quote.
316
+ DUMMY/LJ031-0058.wav|to infuse blood and fluids into the circulatory system.
317
+ DUMMY/LJ029-0197.wav|During November the Dallas papers reported frequently on the plans for protecting the President, stressing the thoroughness of the preparations.
318
+ DUMMY/LJ043-0047.wav|Oswald and his family lived for a brief period with his mother at her urging, but Oswald soon decided to move out.
319
+ DUMMY/LJ021-0026.wav|seems necessary to produce the same result of justice and right conduct
320
+ DUMMY/LJ003-0230.wav|The prison allowances were eked out by the broken victuals generously given by several eating-house keepers in the city,
321
+ DUMMY/LJ037-0252.wav|Ted Callaway, who saw the gunman moments after the shooting, testified that Commission Exhibit Number one sixty-two
322
+ DUMMY/LJ031-0008.wav|Meanwhile, Chief Curry ordered the police base station to notify Parkland Hospital that the wounded President was en route.
323
+ DUMMY/LJ030-0021.wav|all one had to do was get a high building someday with a telescopic rifle, and there was nothing anybody could do to defend against such an attempt.
324
+ DUMMY/LJ046-0179.wav|being reviewed regularly.
325
+ DUMMY/LJ025-0118.wav|and that, however diverse may be the fabrics or tissues of which their bodies are composed, all these varied structures result
326
+ DUMMY/LJ028-0278.wav|Zopyrus, when they told him, not thinking that it could be true, went and saw the colt with his own eyes;
327
+ DUMMY/LJ007-0090.wav|Not only did their presence tend greatly to interfere with the discipline of the prison, but their condition was deplorable in the extreme.
328
+ DUMMY/LJ045-0045.wav|that she would be able to leave the Soviet Union. Marina Oswald has denied this.
329
+ DUMMY/LJ028-0289.wav|For he cut off his own nose and ears, and then, clipping his hair close and flogging himself with a scourge,
330
+ DUMMY/LJ009-0276.wav|Calcraft, the moment he had adjusted the cap and rope, ran down the steps, drew the bolt, and disappeared.
331
+ DUMMY/LJ031-0122.wav|treated the gunshot wound in the left thigh.
332
+ DUMMY/LJ016-0205.wav|he received a retaining fee of five pounds, five shillings, with the usual guinea for each job;
333
+ DUMMY/LJ019-0248.wav|leading to an inequality, uncertainty, and inefficiency of punishment productive of the most prejudicial results.
334
+ DUMMY/LJ033-0183.wav|it was not surprising that the replica sack made on December one, nineteen sixty-three,
335
+ DUMMY/LJ037-0001.wav|Report of the President's Commission on the Assassination of President Kennedy. The Warren Commission Report. By The President's Commission on the Assassination of President Kennedy.
336
+ DUMMY/LJ018-0218.wav|In eighteen fifty-five
337
+ DUMMY/LJ001-0102.wav|Here and there a book is printed in France or Germany with some pretension to good taste,
338
+ DUMMY/LJ007-0125.wav|It was diverted from its proper uses, and, as the "place of the greatest comfort," was allotted to persons who should not have been sent to Newgate at all.
339
+ DUMMY/LJ050-0022.wav|A formal and thorough description of the responsibilities of the advance agent is now in preparation by the Service.
340
+ DUMMY/LJ028-0212.wav|On the night of the eleventh day Gobrias killed the son of the King.
341
+ DUMMY/LJ028-0357.wav|yet we may be sure that Babylon was taken by Darius only by use of stratagem. Its walls were impregnable.
342
+ DUMMY/LJ014-0199.wav|there was no case to make out; why waste money on lawyers for the defense? His demeanor was cool and collected throughout;
343
+ DUMMY/LJ016-0077.wav|A man named Lears, under sentence of transportation for an attempt at murder on board ship, got up part of the way,
344
+ DUMMY/LJ009-0194.wav|and that executors or persons having lawful possession of the bodies
345
+ DUMMY/LJ014-0094.wav|Discovery of the murder came in this wise. O'Connor, a punctual and well-conducted official, was at once missed at the London Docks.
346
+ DUMMY/LJ001-0079.wav|Caslon's type is clear and neat, and fairly well designed;
347
+ DUMMY/LJ026-0052.wav|In the nutrition of the animal the most essential and characteristic part of the food supply is derived from vegetable
348
+ DUMMY/LJ013-0005.wav|One of the earliest of the big operators in fraudulent finance was Edward Beaumont Smith,
349
+ DUMMY/LJ033-0072.wav|I then stepped off of it and the officer picked it up in the middle and it bent so.
350
+ DUMMY/LJ036-0067.wav|According to McWatters, the Beckley bus was behind the Marsalis bus, but he did not actually see it.
351
+ DUMMY/LJ025-0098.wav|and it is probable that amyloid substances are universally present in the animal organism, though not in the precise form of starch.
352
+ DUMMY/LJ005-0257.wav|during which time a host of witnesses were examined, and the committee presented three separate reports,
353
+ DUMMY/LJ004-0024.wav|Thus in eighteen thirteen the exaction of jail fees had been forbidden by law,
354
+ DUMMY/LJ049-0154.wav|In eighteen ninety-four,
355
+ DUMMY/LJ039-0059.wav|(three) his experience and practice after leaving the Marine Corps, and (four) the accuracy of the weapon and the quality of the ammunition.
356
+ DUMMY/LJ007-0150.wav|He is allowed intercourse with prostitutes who, in nine cases out of ten, have originally conduced to his ruin;
357
+ DUMMY/LJ015-0001.wav|Chronicles of Newgate, Volume two. By Arthur Griffiths. Section eighteen: Newgate notorieties continued, part three.
358
+ DUMMY/LJ010-0158.wav|feeling, as he said, that he might as well be shot or hanged as remain in such a state.
359
+ DUMMY/LJ010-0281.wav|who had borne the Queen's commission, first as cornet, and then lieutenant, in the tenth Hussars.
360
+ DUMMY/LJ033-0055.wav|and he could disassemble it more rapidly.
361
+ DUMMY/LJ015-0218.wav|A new accomplice was now needed within the company's establishment, and Pierce looked about long before he found the right person.
362
+ DUMMY/LJ027-0006.wav|In all these lines the facts are drawn together by a strong thread of unity.
363
+ DUMMY/LJ016-0049.wav|He had here completed his ascent.
364
+ DUMMY/LJ006-0088.wav|It was not likely that a system which left innocent men -- for the great bulk of new arrivals were still untried
365
+ DUMMY/LJ042-0133.wav|a great change must have occurred in Oswald's thinking to induce him to return to the United States.
366
+ DUMMY/LJ045-0234.wav|While he did become enraged at at least one point in his interrogation,
367
+ DUMMY/LJ046-0033.wav|The adequacy of existing procedures can fairly be assessed only after full consideration of the difficulty of the protective assignment,
368
+ DUMMY/LJ037-0061.wav|and having, quote, somewhat bushy, end quote, hair.
369
+ DUMMY/LJ032-0025.wav|the officers of Klein's discovered that a rifle bearing serial number C two seven six six had been shipped to one A. Hidell,
370
+ DUMMY/LJ047-0197.wav|in view of all the information concerning Oswald in its files, should have alerted the Secret Service to Oswald's presence in Dallas
371
+ DUMMY/LJ018-0130.wav|and stole paper on a much larger scale than Brown.
372
+ DUMMY/LJ005-0265.wav|It was recommended that the dietaries should be submitted and approved like the rules; that convicted prisoners should not receive any food but the jail allowance;
373
+ DUMMY/LJ044-0105.wav|He presented Arnold Johnson, Gus Hall,
374
+ DUMMY/LJ015-0043.wav|This went on for some time, and might never have been discovered had some good stroke of luck provided any of the partners
375
+ DUMMY/LJ030-0125.wav|On several occasions when the Vice President's car was slowed down by the throng, Special Agent Youngblood stepped out to hold the crowd back.
376
+ DUMMY/LJ043-0140.wav|He also studied Dallas bus schedules to prepare for his later use of buses to travel to and from General Walker's house.
377
+ DUMMY/LJ002-0220.wav|In consequence of these disclosures, both Bambridge and Huggin, his predecessor in the office, were committed to Newgate,
378
+ DUMMY/LJ034-0117.wav|At one:twenty-nine p.m. the police radio reported
379
+ DUMMY/LJ018-0276.wav|The first plot was against Mr. Harry Emmanuel, but he escaped, and the attempt was made upon Loudon and Ryder.
380
+ DUMMY/LJ004-0077.wav|nor has he a right to poison or starve his fellow-creatures."
381
+ DUMMY/LJ042-0194.wav|they should not be confused with slowness, indecision or fear. Only the intellectually fearless could even be remotely attracted to our doctrine,
382
+ DUMMY/LJ029-0114.wav|The route chosen from the airport to Main Street was the normal one, except where Harwood Street was selected as the means of access to Main Street
383
+ DUMMY/LJ014-0194.wav|The policemen were now in possession;
384
+ DUMMY/LJ032-0027.wav|According to its microfilm records, Klein's received an order for a rifle on March thirteen, nineteen sixty-three,
385
+ DUMMY/LJ048-0289.wav|However, there is no evidence that these men failed to take any action in Dallas within their power that would have averted the tragedy.
386
+ DUMMY/LJ043-0188.wav|that he was the leader of a fascist organization, and when I said that even though all of that might be true, just the same he had no right to take his life,
387
+ DUMMY/LJ011-0118.wav|In eighteen twenty-nine the gallows claimed two more victims for this offense.
388
+ DUMMY/LJ040-0201.wav|After her interview with Mrs. Oswald,
389
+ DUMMY/LJ033-0056.wav|While the rifle may have already been disassembled when Oswald arrived home on Thursday, he had ample time that evening to disassemble the rifle
390
+ DUMMY/LJ047-0073.wav|Hosty considered the information to be, quote, stale, unquote, by that time, and did not attempt to verify Oswald's reported statement.
391
+ DUMMY/LJ001-0153.wav|only nominally so, however, in many cases, since when he uses a headline he counts that in,
392
+ DUMMY/LJ007-0158.wav|or any kind of moral improvement was impossible; the prisoner's career was inevitably downward, till he struck the lowest depths.
393
+ DUMMY/LJ028-0502.wav|The Ishtar gateway leading to the palace was encased with beautiful blue glazed bricks,
394
+ DUMMY/LJ028-0226.wav|Though Herodotus wrote nearly a hundred years after Babylon fell, his story seems to bear the stamp of truth.
395
+ DUMMY/LJ010-0038.wav|as there had been before; as in the year eighteen forty-nine, a year memorable for the Rush murders at Norwich,
396
+ DUMMY/LJ019-0241.wav|But in the interval very comprehensive and, I think it must be admitted, salutary changes were successively introduced into the management of prisons.
397
+ DUMMY/LJ001-0094.wav|were induced to cut punches for a series of "old style" letters.
398
+ DUMMY/LJ001-0015.wav|the forms of printed letters should be beautiful, and that their arrangement on the page should be reasonable and a help to the shapeliness of the letters themselves.
399
+ DUMMY/LJ047-0015.wav|From defection to return to Fort Worth.
400
+ DUMMY/LJ044-0139.wav|since there was no background to the New Orleans FPCC, quote, organization, end quote, which consisted solely of Oswald.
401
+ DUMMY/LJ050-0031.wav|that the Secret Service consciously set about the task of inculcating and maintaining the highest standard of excellence and esprit, for all of its personnel.
402
+ DUMMY/LJ050-0235.wav|It has also used other Federal law enforcement agents during Presidential visits to cities in which such agents are stationed.
403
+ DUMMY/LJ050-0137.wav|FBI, and the Secret Service.
404
+ DUMMY/LJ031-0109.wav|At one:thirty-five p.m., after Governor Connally had been moved to the operating room, Dr. Shaw started the first operation
405
+ DUMMY/LJ031-0041.wav|He noted that the President was blue-white or ashen in color; had slow, spasmodic, agonal respiration without any coordination;
406
+ DUMMY/LJ021-0139.wav|There should be at least a full and fair trial given to these means of ending industrial warfare;
407
+ DUMMY/LJ029-0004.wav|The narrative of these events is based largely on the recollections of the participants,
408
+ DUMMY/LJ023-0122.wav|It was said in last year's Democratic platform,
409
+ DUMMY/LJ005-0264.wav|inspectors of prisons should be appointed, who should visit all the prisons from time to time and report to the Secretary of State.
410
+ DUMMY/LJ002-0105.wav|and beyond it was a room called the "wine room," because formerly used for the sale of wine, but
411
+ DUMMY/LJ017-0035.wav|in the interests and for the due protection of the public, that the fullest and fairest inquiry should be made,
412
+ DUMMY/LJ048-0252.wav|Three of these agents occupied positions on the running boards of the car, and the fourth was seated in the car.
413
+ DUMMY/LJ013-0109.wav|The proceeds of the robbery were lodged in a Boston bank,
414
+ DUMMY/LJ039-0139.wav|Oswald obtained a hunting license, joined a hunting club and went hunting about six times, as discussed more fully in chapter six.
415
+ DUMMY/LJ044-0047.wav|that anyone ever attacked any street demonstration in which Oswald was involved, except for the Bringuier incident mentioned above,
416
+ DUMMY/LJ016-0417.wav|Catherine Wilson, the poisoner, was reserved and reticent to the last, expressing no contrition, but also no fear --
417
+ DUMMY/LJ045-0178.wav|he left his wedding ring in a cup on the dresser in his room. He also left one hundred seventy dollars in a wallet in one of the dresser drawers.
418
+ DUMMY/LJ009-0172.wav|While in London, for instance, in eighteen twenty-nine, twenty-four persons had been executed for crimes other than murder,
419
+ DUMMY/LJ049-0202.wav|incident to its responsibilities.
420
+ DUMMY/LJ032-0103.wav|The name "Hidell" was stamped on some of the "Chapter's" printed literature and on the membership application blanks.
421
+ DUMMY/LJ013-0091.wav|and Elder had to be assisted by two bank porters, who carried it for him to a carriage waiting near the Mansion House.
422
+ DUMMY/LJ037-0208.wav|nineteen dollars, ninety-five cents, plus one dollar, twenty-seven cents shipping charge, had been collected from the consignee, Hidell.
423
+ DUMMY/LJ014-0128.wav|her hair was dressed in long crepe bands. She had lace ruffles at her wrist, and wore primrose-colored kid gloves.
424
+ DUMMY/LJ015-0007.wav|This affected Cole's credit, and ugly reports were in circulation charging him with the issue of simulated warrants.
425
+ DUMMY/LJ036-0169.wav|he would have reached his destination at approximately twelve:fifty-four p.m.
426
+ DUMMY/LJ021-0040.wav|The second step we have taken in the restoration of normal business enterprise
427
+ DUMMY/LJ015-0036.wav|The bank was already insolvent,
428
+ DUMMY/LJ034-0041.wav|Although Bureau experiments had shown that twenty-four hours was a likely maximum time, Latona stated
429
+ DUMMY/LJ009-0192.wav|The dissection of executed criminals was abolished soon after the discovery of the crime of burking,
430
+ DUMMY/LJ015-0289.wav|As each transaction was carried out from a different address, and a different messenger always employed,
431
+ DUMMY/LJ005-0072.wav|After a few years of active exertion the Society was rewarded by fresh legislation.
432
+ DUMMY/LJ023-0047.wav|The three horses are, of course, the three branches of government -- the Congress, the Executive and the courts.
433
+ DUMMY/LJ009-0126.wav|Hardly any one.
434
+ DUMMY/LJ034-0097.wav|The window was approximately one hundred twenty feet away.
435
+ DUMMY/LJ028-0462.wav|They were laid in bitumen.
436
+ DUMMY/LJ046-0055.wav|It is now possible for Presidents to travel the length and breadth of a land far larger than the United States
437
+ DUMMY/LJ019-0371.wav|Yet the law was seldom if ever enforced.
438
+ DUMMY/LJ039-0207.wav|Although all of the shots were a few inches high and to the right of the target,
439
+ DUMMY/LJ002-0174.wav|Mr. Buxton's friends at once paid the forty shillings, and the boy was released.
440
+ DUMMY/LJ016-0233.wav|In his own profession
441
+ DUMMY/LJ026-0108.wav|It is clear that there are upward and downward currents of water containing food (comparable to blood of an animal),
442
+ DUMMY/LJ038-0035.wav|Oswald rose from his seat, bringing up both hands.
443
+ DUMMY/LJ026-0148.wav|water which is lost by evaporation, especially from the leaf surface through the stomata;
444
+ DUMMY/LJ001-0186.wav|the position of our Society that a work of utility might be also a work of art, if we cared to make it so.
445
+ DUMMY/LJ016-0264.wav|The upturned faces of the eager spectators resembled those of the 'gods' at Drury Lane on Boxing Night;
446
+ DUMMY/LJ009-0041.wav|The occupants of this terrible black pew were the last always to enter the chapel.
447
+ DUMMY/LJ010-0297.wav|But there were other notorious cases of forgery.
448
+ DUMMY/LJ040-0018.wav|the Commission is not able to reach any definite conclusions as to whether or not he was, quote, sane, unquote, under prevailing legal standards.
449
+ DUMMY/LJ005-0253.wav|"to inquire into and report upon the several jails and houses of correction in the counties, cities, and corporate towns within England and Wales
450
+ DUMMY/LJ027-0176.wav|Fishes first appeared in the Devonian and Upper Silurian in very reptilian or rather amphibian forms.
451
+ DUMMY/LJ034-0035.wav|The position of this palmprint on the carton was parallel with the long axis of the box, and at right angles with the short axis;
452
+ DUMMY/LJ016-0054.wav|But he did not like the risk of entering a room by the fireplace, and the chances of detection it offered.
453
+ DUMMY/LJ018-0262.wav|Roupell received the announcement with a cheerful countenance,
454
+ DUMMY/LJ044-0237.wav|with thirteen dollars, eighty-seven cents when considerably greater resources were available to him.
455
+ DUMMY/LJ034-0166.wav|Two other witnesses were able to offer partial descriptions of a man they saw in the southeast corner window
456
+ DUMMY/LJ016-0238.wav|"just to steady their legs a little;" in other words, to add his weight to that of the hanging bodies.
457
+ DUMMY/LJ042-0198.wav|The discussion above has already set forth examples of his expression of hatred for the United States.
458
+ DUMMY/LJ031-0189.wav|At two:thirty-eight p.m., Eastern Standard Time, Lyndon Baines Johnson took the oath of office as the thirty-sixth President of the United States.
459
+ DUMMY/LJ050-0084.wav|or, quote, other high government officials in the nature of a complaint coupled with an expressed or implied determination to use a means,
460
+ DUMMY/LJ044-0158.wav|As for my return entrance visa please consider it separately. End quote.
461
+ DUMMY/LJ045-0082.wav|it appears that Marina Oswald also complained that her husband was not able to provide more material things for her.
462
+ DUMMY/LJ045-0190.wav|appeared in The Dallas Times Herald on November fifteen, nineteen sixty-three.
463
+ DUMMY/LJ035-0155.wav|The only exit from the office in the direction Oswald was moving was through the door to the front stairway.
464
+ DUMMY/LJ044-0004.wav|Political Activities
465
+ DUMMY/LJ046-0016.wav|The Commission has not undertaken a comprehensive examination of all facets of this subject;
466
+ DUMMY/LJ019-0368.wav|The latter too was to be laid before the House of Commons.
467
+ DUMMY/LJ010-0062.wav|But they proceeded in all seriousness, and would have shrunk from no outrage or atrocity in furtherance of their foolhardy enterprise.
468
+ DUMMY/LJ033-0159.wav|It was from Oswald's right hand, in which he carried the long package as he walked from Frazier's car to the building.
469
+ DUMMY/LJ002-0171.wav|The boy declared he saw no one, and accordingly passed through without paying the toll of a penny.
470
+ DUMMY/LJ002-0298.wav|in his evidence in eighteen fourteen, said it was more,
471
+ DUMMY/LJ012-0219.wav|and in one corner, at some depth, a bundle of clothes were unearthed, which, with a hairy cap,
472
+ DUMMY/LJ017-0190.wav|After this came the charge of administering oil of vitriol, which failed, as has been described.
473
+ DUMMY/LJ019-0179.wav|This, with a scheme for limiting the jail to untried prisoners, had been urgently recommended by Lord John Russell in eighteen thirty.
474
+ DUMMY/LJ050-0188.wav|each patrolman might be given a prepared booklet of instructions explaining what is expected of him. The Secret Service has expressed concern
475
+ DUMMY/LJ006-0043.wav|The disgraceful overcrowding had been partially ended, but the same evils of indiscriminate association were still present; there was the old neglect of decency,
476
+ DUMMY/LJ029-0060.wav|A number of people who resembled some of those in the photographs were placed under surveillance at the Trade Mart.
477
+ DUMMY/LJ019-0052.wav|Both systems came to us from the United States. The difference was really more in degree than in principle,
478
+ DUMMY/LJ037-0081.wav|Later in the day each woman found an empty shell on the ground near the house. These two shells were delivered to the police.
479
+ DUMMY/LJ048-0200.wav|paying particular attention to the crowd for any unusual activity.
480
+ DUMMY/LJ016-0426.wav|come along, gallows.
481
+ DUMMY/LJ008-0182.wav|A tremendous crowd assembled when Bellingham was executed in eighteen twelve for the murder of Spencer Percival, at that time prime minister;
482
+ DUMMY/LJ043-0107.wav|Upon moving to New Orleans on April twenty-four, nineteen sixty-three,
483
+ DUMMY/LJ006-0084.wav|and so numerous were his opportunities of showing favoritism, that all the prisoners may be said to be in his power.
484
+ DUMMY/LJ025-0081.wav|has no permanent digestive cavity or mouth, but takes in its food anywhere and digests, so to speak, all over its body.
485
+ DUMMY/LJ019-0042.wav|These were either satisfied with a makeshift, and modified existing buildings, without close regard to their suitability, or for a long time did nothing at all.
486
+ DUMMY/LJ047-0240.wav|They agree that Hosty told Revill
487
+ DUMMY/LJ032-0012.wav|the resistance to arrest and the attempted shooting of another police officer by the man (Lee Harvey Oswald) subsequently accused of assassinating President Kennedy
488
+ DUMMY/LJ050-0209.wav|The assistant to the Director of the FBI testified that
Grad-TTS/resources/filelists/ljspeech/train.txt ADDED
The diff for this file is too large to render. See raw diff
 
Grad-TTS/resources/filelists/ljspeech/valid.txt ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DUMMY/LJ022-0023.wav|The overwhelming majority of people in this country know how to sift the wheat from the chaff in what they hear and what they read.
2
+ DUMMY/LJ005-0201.wav|as is shown by the report of the Commissioners to inquire into the state of the municipal corporations in eighteen thirty-five.
3
+ DUMMY/LJ001-0110.wav|Even the Caslon type when enlarged shows great shortcomings in this respect:
4
+ DUMMY/LJ003-0345.wav|All the committee could do in this respect was to throw the responsibility on others.
5
+ DUMMY/LJ007-0154.wav|These pungent and well-grounded strictures applied with still greater force to the unconvicted prisoner, the man who came to the prison innocent, and still uncontaminated,
6
+ DUMMY/LJ018-0098.wav|and recognized as one of the frequenters of the bogus law-stationers. His arrest led to that of others.
7
+ DUMMY/LJ047-0044.wav|Oswald was, however, willing to discuss his contacts with Soviet authorities. He denied having any involvement with Soviet intelligence agencies
8
+ DUMMY/LJ031-0038.wav|The first physician to see the President at Parkland Hospital was Dr. Charles J. Carrico, a resident in general surgery.
9
+ DUMMY/LJ048-0194.wav|during the morning of November twenty-two prior to the motorcade.
10
+ DUMMY/LJ049-0026.wav|On occasion the Secret Service has been permitted to have an agent riding in the passenger compartment with the President.
11
+ DUMMY/LJ004-0152.wav|although at Mr. Buxton's visit a new jail was in process of erection, the first step towards reform since Howard's visitation in seventeen seventy-four.
12
+ DUMMY/LJ008-0278.wav|or theirs might be one of many, and it might be considered necessary to "make an example."
13
+ DUMMY/LJ043-0002.wav|The Warren Commission Report. By The President's Commission on the Assassination of President Kennedy. Chapter seven. Lee Harvey Oswald:
14
+ DUMMY/LJ009-0114.wav|Mr. Wakefield winds up his graphic but somewhat sensational account by describing another religious service, which may appropriately be inserted here.
15
+ DUMMY/LJ028-0506.wav|A modern artist would have difficulty in doing such accurate work.
16
+ DUMMY/LJ050-0168.wav|with the particular purposes of the agency involved. The Commission recognizes that this is a controversial area
17
+ DUMMY/LJ039-0223.wav|Oswald's Marine training in marksmanship, his other rifle experience and his established familiarity with this particular weapon
18
+ DUMMY/LJ029-0032.wav|According to O'Donnell, quote, we had a motorcade wherever we went, end quote.
19
+ DUMMY/LJ031-0070.wav|Dr. Clark, who most closely observed the head wound,
20
+ DUMMY/LJ034-0198.wav|Euins, who was on the southwest corner of Elm and Houston Streets testified that he could not describe the man he saw in the window.
21
+ DUMMY/LJ026-0068.wav|Energy enters the plant, to a small extent,
22
+ DUMMY/LJ039-0075.wav|once you know that you must put the crosshairs on the target and that is all that is necessary.
23
+ DUMMY/LJ004-0096.wav|the fatal consequences whereof might be prevented if the justices of the peace were duly authorized
24
+ DUMMY/LJ005-0014.wav|Speaking on a debate on prison matters, he declared that
25
+ DUMMY/LJ012-0161.wav|he was reported to have fallen away to a shadow.
26
+ DUMMY/LJ018-0239.wav|His disappearance gave color and substance to evil reports already in circulation that the will and conveyance above referred to
27
+ DUMMY/LJ019-0257.wav|Here the tread-wheel was in use, there cellular cranks, or hard-labor machines.
28
+ DUMMY/LJ028-0008.wav|you tap gently with your heel upon the shoulder of the dromedary to urge her on.
29
+ DUMMY/LJ024-0083.wav|This plan of mine is no attack on the Court;
30
+ DUMMY/LJ042-0129.wav|No night clubs or bowling alleys, no places of recreation except the trade union dances. I have had enough.
31
+ DUMMY/LJ036-0103.wav|The police asked him whether he could pick out his passenger from the lineup.
32
+ DUMMY/LJ046-0058.wav|During his Presidency, Franklin D. Roosevelt made almost four hundred journeys and traveled more than three hundred fifty thousand miles.
33
+ DUMMY/LJ014-0076.wav|He was seen afterwards smoking and talking with his hosts in their back parlor, and never seen again alive.
34
+ DUMMY/LJ002-0043.wav|long narrow rooms -- one thirty-six feet, six twenty-three feet, and the eighth eighteen,
35
+ DUMMY/LJ009-0076.wav|We come to the sermon.
36
+ DUMMY/LJ017-0131.wav|even when the high sheriff had told him there was no possibility of a reprieve, and within a few hours of execution.
37
+ DUMMY/LJ046-0184.wav|but there is a system for the immediate notification of the Secret Service by the confining institution when a subject is released or escapes.
38
+ DUMMY/LJ014-0263.wav|When other pleasures palled he took a theatre, and posed as a munificent patron of the dramatic art.
39
+ DUMMY/LJ042-0096.wav|(old exchange rate) in addition to his factory salary of approximately equal amount
40
+ DUMMY/LJ049-0050.wav|Hill had both feet on the car and was climbing aboard to assist President and Mrs. Kennedy.
41
+ DUMMY/LJ028-0307.wav|then let twenty days pass, and at the end of that time station near the Chaldasan gates a body of four thousand.
42
+ DUMMY/LJ012-0235.wav|While they were in a state of insensibility the murder was committed.
43
+ DUMMY/LJ034-0053.wav|reached the same conclusion as Latona that the prints found on the cartons were those of Lee Harvey Oswald.
44
+ DUMMY/LJ014-0030.wav|These were damnatory facts which well supported the prosecution.
45
+ DUMMY/LJ015-0203.wav|but were the precautions too minute, the vigilance too close to be eluded or overcome?
46
+ DUMMY/LJ028-0093.wav|but his scribe wrote it in the manner customary for the scribes of those days to write of their royal masters.
47
+ DUMMY/LJ002-0018.wav|The inadequacy of the jail was noticed and reported upon again and again by the grand juries of the city of London,
48
+ DUMMY/LJ028-0275.wav|At last, in the twentieth month,
49
+ DUMMY/LJ011-0096.wav|He married a lady also belonging to the Society of Friends, who brought him a large fortune, which, and his own money, he put into a city firm,
50
+ DUMMY/LJ036-0077.wav|Roger D. Craig, a deputy sheriff of Dallas County,
51
+ DUMMY/LJ016-0318.wav|Other officials, great lawyers, governors of prisons, and chaplains supported this view.
52
+ DUMMY/LJ013-0164.wav|who came from his room ready dressed, a suspicious circumstance, as he was always late in the morning.
53
+ DUMMY/LJ027-0141.wav|is closely reproduced in the life-history of existing deer. Or, in other words,
54
+ DUMMY/LJ028-0335.wav|accordingly they committed to him the command of their whole army, and put the keys of their city into his hands.
55
+ DUMMY/LJ031-0202.wav|Mrs. Kennedy chose the hospital in Bethesda for the autopsy because the President had served in the Navy.
56
+ DUMMY/LJ021-0145.wav|From those willing to join in establishing this hoped-for period of peace,
57
+ DUMMY/LJ016-0288.wav|"Müller, Müller, He's the man," till a diversion was created by the appearance of the gallows, which was received with continuous yells.
58
+ DUMMY/LJ028-0081.wav|Years later, when the archaeologists could readily distinguish the false from the true,
59
+ DUMMY/LJ018-0081.wav|his defense being that he had intended to commit suicide, but that, on the appearance of this officer who had wronged him,
60
+ DUMMY/LJ021-0066.wav|together with a great increase in the payrolls, there has come a substantial rise in the total of industrial profits
61
+ DUMMY/LJ009-0238.wav|After this the sheriffs sent for another rope, but the spectators interfered, and the man was carried back to jail.
62
+ DUMMY/LJ005-0079.wav|and improve the morals of the prisoners, and shall insure the proper measure of punishment to convicted offenders.
63
+ DUMMY/LJ035-0019.wav|drove to the northwest corner of Elm and Houston, and parked approximately ten feet from the traffic signal.
64
+ DUMMY/LJ036-0174.wav|This is the approximate time he entered the roominghouse, according to Earlene Roberts, the housekeeper there.
65
+ DUMMY/LJ046-0146.wav|The criteria in effect prior to November twenty-two, nineteen sixty-three, for determining whether to accept material for the PRS general files
66
+ DUMMY/LJ017-0044.wav|and the deepest anxiety was felt that the crime, if crime there had been, should be brought home to its perpetrator.
67
+ DUMMY/LJ017-0070.wav|but his sporting operations did not prosper, and he became a needy man, always driven to desperate straits for cash.
68
+ DUMMY/LJ016-0020.wav|He never reached the cistern, but fell back into the yard, injuring his legs severely.
69
+ DUMMY/LJ045-0230.wav|when he was finally apprehended in the Texas Theatre. Although it is not fully corroborated by others who were present,
70
+ DUMMY/LJ035-0129.wav|and she must have run down the stairs ahead of Oswald and would probably have seen or heard him.
71
+ DUMMY/LJ008-0307.wav|afterwards express a wish to murder the Recorder for having kept them so long in suspense.
72
+ DUMMY/LJ008-0294.wav|nearly indefinitely deferred.
73
+ DUMMY/LJ047-0148.wav|On October twenty-five,
74
+ DUMMY/LJ008-0111.wav|They entered a "stone cold room," and were presently joined by the prisoner.
75
+ DUMMY/LJ034-0042.wav|that he could only testify with certainty that the print was less than three days old.
76
+ DUMMY/LJ037-0234.wav|Mrs. Mary Brock, the wife of a mechanic who worked at the station, was there at the time and she saw a white male,
77
+ DUMMY/LJ040-0002.wav|Chapter seven. Lee Harvey Oswald: Background and Possible Motives, Part one.
78
+ DUMMY/LJ045-0140.wav|The arguments he used to justify his use of the alias suggest that Oswald may have come to think that the whole world was becoming involved
79
+ DUMMY/LJ012-0035.wav|the number and names on watches, were carefully removed or obliterated after the goods passed out of his hands.
80
+ DUMMY/LJ012-0250.wav|On the seventh July, eighteen thirty-seven,
81
+ DUMMY/LJ016-0179.wav|contracted with sheriffs and conveners to work by the job.
82
+ DUMMY/LJ016-0138.wav|at a distance from the prison.
83
+ DUMMY/LJ027-0052.wav|These principles of homology are essential to a correct interpretation of the facts of morphology.
84
+ DUMMY/LJ031-0134.wav|On one occasion Mrs. Johnson, accompanied by two Secret Service agents, left the room to see Mrs. Kennedy and Mrs. Connally.
85
+ DUMMY/LJ019-0273.wav|which Sir Joshua Jebb told the committee he considered the proper elements of penal discipline.
86
+ DUMMY/LJ014-0110.wav|At the first the boxes were impounded, opened, and found to contain many of O'Connor's effects.
87
+ DUMMY/LJ034-0160.wav|on Brennan's subsequent certain identification of Lee Harvey Oswald as the man he saw fire the rifle.
88
+ DUMMY/LJ038-0199.wav|eleven. If I am alive and taken prisoner,
89
+ DUMMY/LJ014-0010.wav|yet he could not overcome the strange fascination it had for him, and remained by the side of the corpse till the stretcher came.
90
+ DUMMY/LJ033-0047.wav|I noticed when I went out that the light was on, end quote,
91
+ DUMMY/LJ040-0027.wav|He was never satisfied with anything.
92
+ DUMMY/LJ048-0228.wav|and others who were present say that no agent was inebriated or acted improperly.
93
+ DUMMY/LJ003-0111.wav|He was in consequence put out of the protection of their internal law, end quote. Their code was a subject of some curiosity.
94
+ DUMMY/LJ008-0258.wav|Let me retrace my steps, and speak more in detail of the treatment of the condemned in those bloodthirsty and brutally indifferent days,
95
+ DUMMY/LJ029-0022.wav|The original plan called for the President to spend only one day in the State, making whirlwind visits to Dallas, Fort Worth, San Antonio, and Houston.
Grad-TTS/resources/filelists/synthesis.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ In all these lines the facts are drawn together by a strong thread of unity.
2
+ After the construction and action of the machine had been explained, the doctor asked the governor what kind of men he had commanded at Goree.
3
+ After a few years of active exertion the Society was rewarded by fresh legislation.
Grad-TTS/resources/ipa_dictionary_id ADDED
The diff for this file is too large to render. See raw diff
 
Grad-TTS/text/LICENSE ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CMUdict
2
+ -------
3
+
4
+ CMUdict (the Carnegie Mellon Pronouncing Dictionary) is a free
5
+ pronouncing dictionary of English, suitable for uses in speech
6
+ technology and is maintained by the Speech Group in the School of
7
+ Computer Science at Carnegie Mellon University.
8
+
9
+ The Carnegie Mellon Speech Group does not guarantee the accuracy of
10
+ this dictionary, nor its suitability for any specific purpose. In
11
+ fact, we expect a number of errors, omissions and inconsistencies to
12
+ remain in the dictionary. We intend to continually update the
13
+ dictionary by correction existing entries and by adding new ones. From
14
+ time to time a new major version will be released.
15
+
16
+ We welcome input from users: Please send email to Alex Rudnicky
17
+ (air+cmudict@cs.cmu.edu).
18
+
19
+ The Carnegie Mellon Pronouncing Dictionary, in its current and
20
+ previous versions is Copyright (C) 1993-2014 by Carnegie Mellon
21
+ University. Use of this dictionary for any research or commercial
22
+ purpose is completely unrestricted. If you make use of or
23
+ redistribute this material we request that you acknowledge its
24
+ origin in your descriptions.
25
+
26
+ If you add words to or correct words in your version of this
27
+ dictionary, we would appreciate it if you could send these additions
28
+ and corrections to us (air+cmudict@cs.cmu.edu) for consideration in a
29
+ subsequent version. All submissions will be reviewed and approved by
30
+ the current maintainer, Alex Rudnicky at Carnegie Mellon.
Grad-TTS/text/__init__.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+
3
+ import re
4
+ from text import cleaners
5
+ from text.symbols import symbols
6
+
7
+
8
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
9
+ _id_to_symbol = {i: s for i, s in enumerate(symbols)}
10
+
11
+ _curly_re = re.compile(r'(.*?)\{(.+?)\}(.*)')
12
+
13
+
14
+ def get_arpabet(word, dictionary):
15
+ word_arpabet = dictionary.lookup(word)
16
+ if word_arpabet is not None:
17
+ return "{" + word_arpabet[0] + "}"
18
+ else:
19
+ return word
20
+
21
+
22
+ def text_to_sequence(text, cleaner_names=["english_cleaners"], dictionary=None):
23
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
24
+
25
+ The text can optionally have ARPAbet sequences enclosed in curly braces embedded
26
+ in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street."
27
+
28
+ Args:
29
+ text: string to convert to a sequence
30
+ cleaner_names: names of the cleaner functions to run the text through
31
+ dictionary: arpabet class with arpabet dictionary
32
+
33
+ Returns:
34
+ List of integers corresponding to the symbols in the text
35
+ '''
36
+ sequence = []
37
+ space = _symbols_to_sequence(' ')
38
+ # Check for curly braces and treat their contents as ARPAbet:
39
+ while len(text):
40
+ m = _curly_re.match(text)
41
+ if not m:
42
+ clean_text = _clean_text(text, cleaner_names)
43
+ if dictionary is not None:
44
+ clean_text = [get_arpabet(w, dictionary) for w in clean_text.split(" ")]
45
+ for i in range(len(clean_text)):
46
+ t = clean_text[i]
47
+ if t.startswith("{"):
48
+ sequence += _arpabet_to_sequence(t[1:-1])
49
+ else:
50
+ sequence += _symbols_to_sequence(t)
51
+ sequence += space
52
+ else:
53
+ sequence += _symbols_to_sequence(clean_text)
54
+ break
55
+ sequence += _symbols_to_sequence(_clean_text(m.group(1), cleaner_names))
56
+ sequence += _arpabet_to_sequence(m.group(2))
57
+ text = m.group(3)
58
+
59
+ # remove trailing space
60
+ if dictionary is not None:
61
+ sequence = sequence[:-1] if sequence[-1] == space[0] else sequence
62
+ return sequence
63
+
64
+
65
+ def sequence_to_text(sequence):
66
+ '''Converts a sequence of IDs back to a string'''
67
+ result = ''
68
+ for symbol_id in sequence:
69
+ if symbol_id in _id_to_symbol:
70
+ s = _id_to_symbol[symbol_id]
71
+ # Enclose ARPAbet back in curly braces:
72
+ if len(s) > 1 and s[0] == '@':
73
+ s = '{%s}' % s[1:]
74
+ result += s
75
+ return result.replace('}{', ' ')
76
+
77
+
78
+ def _clean_text(text, cleaner_names):
79
+ for name in cleaner_names:
80
+ cleaner = getattr(cleaners, name)
81
+ if not cleaner:
82
+ raise Exception('Unknown cleaner: %s' % name)
83
+ text = cleaner(text)
84
+ return text
85
+
86
+
87
+ def _symbols_to_sequence(symbols):
88
+ return [_symbol_to_id[s] for s in symbols if _should_keep_symbol(s)]
89
+
90
+
91
+ def _arpabet_to_sequence(text):
92
+ return _symbols_to_sequence(['@' + s for s in text.split()])
93
+
94
+
95
+ def _should_keep_symbol(s):
96
+ return s in _symbol_to_id and s != '_' and s != '~'
Grad-TTS/text/cleaners.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+
3
+ import re
4
+ from unidecode import unidecode
5
+ from .numbers import normalize_numbers
6
+
7
+
8
+ _whitespace_re = re.compile(r'\s+')
9
+
10
+ _abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
11
+ ('mrs', 'misess'),
12
+ ('mr', 'mister'),
13
+ ('dr', 'doctor'),
14
+ ('st', 'saint'),
15
+ ('co', 'company'),
16
+ ('jr', 'junior'),
17
+ ('maj', 'major'),
18
+ ('gen', 'general'),
19
+ ('drs', 'doctors'),
20
+ ('rev', 'reverend'),
21
+ ('lt', 'lieutenant'),
22
+ ('hon', 'honorable'),
23
+ ('sgt', 'sergeant'),
24
+ ('capt', 'captain'),
25
+ ('esq', 'esquire'),
26
+ ('ltd', 'limited'),
27
+ ('col', 'colonel'),
28
+ ('ft', 'fort'),
29
+ ]]
30
+
31
+
32
+ def expand_abbreviations(text):
33
+ for regex, replacement in _abbreviations:
34
+ text = re.sub(regex, replacement, text)
35
+ return text
36
+
37
+
38
+ def expand_numbers(text):
39
+ return normalize_numbers(text)
40
+
41
+
42
+ def lowercase(text):
43
+ return text.lower()
44
+
45
+
46
+ def collapse_whitespace(text):
47
+ return re.sub(_whitespace_re, ' ', text)
48
+
49
+
50
+ def convert_to_ascii(text):
51
+ return unidecode(text)
52
+
53
+
54
+ def basic_cleaners(text):
55
+ text = lowercase(text)
56
+ text = collapse_whitespace(text)
57
+ return text
58
+
59
+
60
+ def transliteration_cleaners(text):
61
+ text = convert_to_ascii(text)
62
+ text = lowercase(text)
63
+ text = collapse_whitespace(text)
64
+ return text
65
+
66
+
67
+ def english_cleaners(text):
68
+ text = convert_to_ascii(text)
69
+ text = lowercase(text)
70
+ text = expand_numbers(text)
71
+ text = expand_abbreviations(text)
72
+ text = collapse_whitespace(text)
73
+ return text
Grad-TTS/text/cmudict.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+
3
+ import re
4
+
5
+
6
+ valid_symbols = [
7
+ 'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
8
+ 'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
9
+ 'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'ER2', 'EY',
10
+ 'EY0', 'EY1', 'EY2', 'F', 'G', 'HH', 'IH', 'IH0', 'IH1', 'IH2', 'IY', 'IY0', 'IY1',
11
+ 'IY2', 'JH', 'K', 'L', 'M', 'N', 'NG', 'OW', 'OW0', 'OW1', 'OW2', 'OY', 'OY0',
12
+ 'OY1', 'OY2', 'P', 'R', 'S', 'SH', 'T', 'TH', 'UH', 'UH0', 'UH1', 'UH2', 'UW',
13
+ 'UW0', 'UW1', 'UW2', 'V', 'W', 'Y', 'Z', 'ZH'
14
+ ]
15
+
16
+ _valid_symbol_set = set(valid_symbols)
17
+
18
+
19
+ class CMUDict:
20
+ def __init__(self, file_or_path, keep_ambiguous=True):
21
+ if isinstance(file_or_path, str):
22
+ with open(file_or_path, encoding='latin-1') as f:
23
+ entries = _parse_cmudict(f)
24
+ else:
25
+ entries = _parse_cmudict(file_or_path)
26
+ if not keep_ambiguous:
27
+ entries = {word: pron for word, pron in entries.items() if len(pron) == 1}
28
+ self._entries = entries
29
+
30
+ def __len__(self):
31
+ return len(self._entries)
32
+
33
+ def lookup(self, word):
34
+ return self._entries.get(word.upper())
35
+
36
+
37
+ _alt_re = re.compile(r'\([0-9]+\)')
38
+
39
+
40
+ def _parse_cmudict(file):
41
+ cmudict = {}
42
+ for line in file:
43
+ if len(line) and (line[0] >= 'A' and line[0] <= 'Z' or line[0] == "'"):
44
+ parts = line.split(' ')
45
+ word = re.sub(_alt_re, '', parts[0])
46
+ pronunciation = _get_pronunciation(parts[1])
47
+ if pronunciation:
48
+ if word in cmudict:
49
+ cmudict[word].append(pronunciation)
50
+ else:
51
+ cmudict[word] = [pronunciation]
52
+ return cmudict
53
+
54
+
55
+ def _get_pronunciation(s):
56
+ parts = s.strip().split(' ')
57
+ for part in parts:
58
+ if part not in _valid_symbol_set:
59
+ return None
60
+ return ' '.join(parts)
Grad-TTS/text/numbers.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+
3
+ import inflect
4
+ import re
5
+
6
+
7
+ _inflect = inflect.engine()
8
+ _comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])')
9
+ _decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)')
10
+ _pounds_re = re.compile(r'£([0-9\,]*[0-9]+)')
11
+ _dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)')
12
+ _ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)')
13
+ _number_re = re.compile(r'[0-9]+')
14
+
15
+
16
+ def _remove_commas(m):
17
+ return m.group(1).replace(',', '')
18
+
19
+
20
+ def _expand_decimal_point(m):
21
+ return m.group(1).replace('.', ' point ')
22
+
23
+
24
+ def _expand_dollars(m):
25
+ match = m.group(1)
26
+ parts = match.split('.')
27
+ if len(parts) > 2:
28
+ return match + ' dollars'
29
+ dollars = int(parts[0]) if parts[0] else 0
30
+ cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
31
+ if dollars and cents:
32
+ dollar_unit = 'dollar' if dollars == 1 else 'dollars'
33
+ cent_unit = 'cent' if cents == 1 else 'cents'
34
+ return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit)
35
+ elif dollars:
36
+ dollar_unit = 'dollar' if dollars == 1 else 'dollars'
37
+ return '%s %s' % (dollars, dollar_unit)
38
+ elif cents:
39
+ cent_unit = 'cent' if cents == 1 else 'cents'
40
+ return '%s %s' % (cents, cent_unit)
41
+ else:
42
+ return 'zero dollars'
43
+
44
+
45
+ def _expand_ordinal(m):
46
+ return _inflect.number_to_words(m.group(0))
47
+
48
+
49
+ def _expand_number(m):
50
+ num = int(m.group(0))
51
+ if num > 1000 and num < 3000:
52
+ if num == 2000:
53
+ return 'two thousand'
54
+ elif num > 2000 and num < 2010:
55
+ return 'two thousand ' + _inflect.number_to_words(num % 100)
56
+ elif num % 100 == 0:
57
+ return _inflect.number_to_words(num // 100) + ' hundred'
58
+ else:
59
+ return _inflect.number_to_words(num, andword='', zero='oh',
60
+ group=2).replace(', ', ' ')
61
+ else:
62
+ return _inflect.number_to_words(num, andword='')
63
+
64
+
65
+ def normalize_numbers(text):
66
+ text = re.sub(_comma_number_re, _remove_commas, text)
67
+ text = re.sub(_pounds_re, r'\1 pounds', text)
68
+ text = re.sub(_dollars_re, _expand_dollars, text)
69
+ text = re.sub(_decimal_number_re, _expand_decimal_point, text)
70
+ text = re.sub(_ordinal_re, _expand_ordinal, text)
71
+ text = re.sub(_number_re, _expand_number, text)
72
+ return text
Grad-TTS/text/symbols.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+
3
+ from text import cmudict
4
+
5
+ _pad = '_'
6
+ _punctuation = '!\'(),.:;? '
7
+ _special = '-'
8
+ _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
9
+
10
+ # Prepend "@" to ARPAbet symbols to ensure uniqueness:
11
+ _arpabet = ['@' + s for s in cmudict.valid_symbols]
12
+
13
+ # Export all symbols:
14
+ symbols = [_pad] + list(_special) + list(_punctuation) + list(_letters) + _arpabet
Grad-TTS/train.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import numpy as np
10
+ from tqdm import tqdm
11
+
12
+ import torch
13
+ from torch.utils.data import DataLoader
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+ import params
17
+ from model import GradTTS
18
+ from data import TextMelDataset, TextMelBatchCollate
19
+ from utils import plot_tensor, save_plot
20
+ from text.symbols import symbols
21
+
22
+
23
+ train_filelist_path = params.train_filelist_path
24
+ valid_filelist_path = params.valid_filelist_path
25
+ cmudict_path = params.cmudict_path
26
+ add_blank = params.add_blank
27
+
28
+ log_dir = params.log_dir
29
+ n_epochs = params.n_epochs
30
+ batch_size = params.batch_size
31
+ out_size = params.out_size
32
+ learning_rate = params.learning_rate
33
+ random_seed = params.seed
34
+ n_workers = params.n_workers
35
+
36
+ nsymbols = len(symbols) + 1 if add_blank else len(symbols)
37
+ n_enc_channels = params.n_enc_channels
38
+ filter_channels = params.filter_channels
39
+ filter_channels_dp = params.filter_channels_dp
40
+ n_enc_layers = params.n_enc_layers
41
+ enc_kernel = params.enc_kernel
42
+ enc_dropout = params.enc_dropout
43
+ n_heads = params.n_heads
44
+ window_size = params.window_size
45
+
46
+ n_feats = params.n_feats
47
+ n_fft = params.n_fft
48
+ sample_rate = params.sample_rate
49
+ hop_length = params.hop_length
50
+ win_length = params.win_length
51
+ f_min = params.f_min
52
+ f_max = params.f_max
53
+
54
+ dec_dim = params.dec_dim
55
+ beta_min = params.beta_min
56
+ beta_max = params.beta_max
57
+ pe_scale = params.pe_scale
58
+
59
+ num_workers = params.num_workers
60
+
61
+ if __name__ == "__main__":
62
+ torch.manual_seed(random_seed)
63
+ np.random.seed(random_seed)
64
+
65
+ print('Initializing logger...')
66
+ logger = SummaryWriter(log_dir=log_dir)
67
+
68
+ print('Initializing data loaders...')
69
+ train_dataset = TextMelDataset(train_filelist_path, cmudict_path, add_blank,
70
+ n_fft, n_feats, sample_rate, hop_length,
71
+ win_length, f_min, f_max)
72
+ batch_collate = TextMelBatchCollate()
73
+ loader = DataLoader(dataset=train_dataset, batch_size=batch_size,
74
+ collate_fn=batch_collate, drop_last=True,
75
+ num_workers=num_workers, shuffle=False)
76
+ test_dataset = TextMelDataset(valid_filelist_path, cmudict_path, add_blank,
77
+ n_fft, n_feats, sample_rate, hop_length,
78
+ win_length, f_min, f_max)
79
+
80
+ print('Initializing model...')
81
+ model = GradTTS(nsymbols, 1, None, n_enc_channels, filter_channels, filter_channels_dp,
82
+ n_heads, n_enc_layers, enc_kernel, enc_dropout, window_size,
83
+ n_feats, dec_dim, beta_min, beta_max, pe_scale).cuda()
84
+ print('Number of encoder + duration predictor parameters: %.2fm' % (model.encoder.nparams/1e6))
85
+ print('Number of decoder parameters: %.2fm' % (model.decoder.nparams/1e6))
86
+ print('Total parameters: %.2fm' % (model.nparams/1e6))
87
+
88
+ print('Initializing optimizer...')
89
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=learning_rate)
90
+
91
+ print('Logging test batch...')
92
+ test_batch = test_dataset.sample_test_batch(size=params.test_size)
93
+ for i, item in enumerate(test_batch):
94
+ mel = item['y']
95
+ logger.add_image(f'image_{i}/ground_truth', plot_tensor(mel.squeeze()),
96
+ global_step=0, dataformats='HWC')
97
+ save_plot(mel.squeeze(), f'{log_dir}/original_{i}.png')
98
+
99
+ print('Start training...')
100
+ iteration = 0
101
+ for epoch in range(1, n_epochs + 1):
102
+ model.train()
103
+ dur_losses = []
104
+ prior_losses = []
105
+ diff_losses = []
106
+ with tqdm(loader, total=len(train_dataset)//batch_size) as progress_bar:
107
+ for batch_idx, batch in enumerate(progress_bar):
108
+ model.zero_grad()
109
+ x, x_lengths = batch['x'].cuda(), batch['x_lengths'].cuda()
110
+ y, y_lengths = batch['y'].cuda(), batch['y_lengths'].cuda()
111
+ dur_loss, prior_loss, diff_loss = model.compute_loss(x, x_lengths,
112
+ y, y_lengths,
113
+ out_size=out_size)
114
+ loss = sum([dur_loss, prior_loss, diff_loss])
115
+ loss.backward()
116
+
117
+ enc_grad_norm = torch.nn.utils.clip_grad_norm_(model.encoder.parameters(),
118
+ max_norm=1)
119
+ dec_grad_norm = torch.nn.utils.clip_grad_norm_(model.decoder.parameters(),
120
+ max_norm=1)
121
+ optimizer.step()
122
+
123
+ logger.add_scalar('training/duration_loss', dur_loss.item(),
124
+ global_step=iteration)
125
+ logger.add_scalar('training/prior_loss', prior_loss.item(),
126
+ global_step=iteration)
127
+ logger.add_scalar('training/diffusion_loss', diff_loss.item(),
128
+ global_step=iteration)
129
+ logger.add_scalar('training/encoder_grad_norm', enc_grad_norm,
130
+ global_step=iteration)
131
+ logger.add_scalar('training/decoder_grad_norm', dec_grad_norm,
132
+ global_step=iteration)
133
+
134
+ dur_losses.append(dur_loss.item())
135
+ prior_losses.append(prior_loss.item())
136
+ diff_losses.append(diff_loss.item())
137
+
138
+ if batch_idx % 5 == 0:
139
+ msg = f'Epoch: {epoch}, iteration: {iteration} | dur_loss: {dur_loss.item()}, prior_loss: {prior_loss.item()}, diff_loss: {diff_loss.item()}'
140
+ progress_bar.set_description(msg)
141
+
142
+ iteration += 1
143
+
144
+ log_msg = 'Epoch %d: duration loss = %.3f ' % (epoch, np.mean(dur_losses))
145
+ log_msg += '| prior loss = %.3f ' % np.mean(prior_losses)
146
+ log_msg += '| diffusion loss = %.3f\n' % np.mean(diff_losses)
147
+ with open(f'{log_dir}/train.log', 'a') as f:
148
+ f.write(log_msg)
149
+
150
+ if epoch % params.save_every > 0:
151
+ continue
152
+
153
+ model.eval()
154
+ print('Synthesis...')
155
+ with torch.no_grad():
156
+ for i, item in enumerate(test_batch):
157
+ x = item['x'].to(torch.long).unsqueeze(0).cuda()
158
+ x_lengths = torch.LongTensor([x.shape[-1]]).cuda()
159
+ y_enc, y_dec, attn = model(x, x_lengths, n_timesteps=50)
160
+ logger.add_image(f'image_{i}/generated_enc',
161
+ plot_tensor(y_enc.squeeze().cpu()),
162
+ global_step=iteration, dataformats='HWC')
163
+ logger.add_image(f'image_{i}/generated_dec',
164
+ plot_tensor(y_dec.squeeze().cpu()),
165
+ global_step=iteration, dataformats='HWC')
166
+ logger.add_image(f'image_{i}/alignment',
167
+ plot_tensor(attn.squeeze().cpu()),
168
+ global_step=iteration, dataformats='HWC')
169
+ save_plot(y_enc.squeeze().cpu(),
170
+ f'{log_dir}/generated_enc_{i}.png')
171
+ save_plot(y_dec.squeeze().cpu(),
172
+ f'{log_dir}/generated_dec_{i}.png')
173
+ save_plot(attn.squeeze().cpu(),
174
+ f'{log_dir}/alignment_{i}.png')
175
+
176
+ ckpt = model.state_dict()
177
+ torch.save(ckpt, f=f"{log_dir}/grad_{epoch}.pt")
Grad-TTS/train_multi_speaker.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import numpy as np
10
+ from tqdm import tqdm
11
+
12
+ import torch
13
+ from torch.utils.data import DataLoader
14
+ from torch.utils.tensorboard import SummaryWriter
15
+
16
+ import params
17
+ from model import GradTTS
18
+ from data import TextMelSpeakerDataset, TextMelSpeakerBatchCollate
19
+ from utils import plot_tensor, save_plot
20
+ from text.symbols import symbols
21
+
22
+
23
+ train_filelist_path = params.train_filelist_path
24
+ valid_filelist_path = params.valid_filelist_path
25
+ cmudict_path = params.cmudict_path
26
+ add_blank = params.add_blank
27
+ n_spks = params.n_spks
28
+ spk_emb_dim = params.spk_emb_dim
29
+
30
+ log_dir = params.log_dir
31
+ n_epochs = params.n_epochs
32
+ batch_size = params.batch_size
33
+ out_size = params.out_size
34
+ learning_rate = params.learning_rate
35
+ random_seed = params.seed
36
+
37
+ nsymbols = len(symbols) + 1 if add_blank else len(symbols)
38
+ n_enc_channels = params.n_enc_channels
39
+ filter_channels = params.filter_channels
40
+ filter_channels_dp = params.filter_channels_dp
41
+ n_enc_layers = params.n_enc_layers
42
+ enc_kernel = params.enc_kernel
43
+ enc_dropout = params.enc_dropout
44
+ n_heads = params.n_heads
45
+ window_size = params.window_size
46
+
47
+ n_feats = params.n_feats
48
+ n_fft = params.n_fft
49
+ sample_rate = params.sample_rate
50
+ hop_length = params.hop_length
51
+ win_length = params.win_length
52
+ f_min = params.f_min
53
+ f_max = params.f_max
54
+
55
+ dec_dim = params.dec_dim
56
+ beta_min = params.beta_min
57
+ beta_max = params.beta_max
58
+ pe_scale = params.pe_scale
59
+
60
+ num_workers = params.num_workers
61
+
62
+
63
+ if __name__ == "__main__":
64
+ torch.manual_seed(random_seed)
65
+ np.random.seed(random_seed)
66
+
67
+ print('Initializing logger...')
68
+ logger = SummaryWriter(log_dir=log_dir)
69
+
70
+ print('Initializing data loaders...')
71
+ train_dataset = TextMelSpeakerDataset(train_filelist_path, cmudict_path, add_blank,
72
+ n_fft, n_feats, sample_rate, hop_length,
73
+ win_length, f_min, f_max)
74
+ batch_collate = TextMelSpeakerBatchCollate()
75
+ loader = DataLoader(dataset=train_dataset, batch_size=batch_size,
76
+ collate_fn=batch_collate, drop_last=True,
77
+ num_workers=num_workers, shuffle=True)
78
+ test_dataset = TextMelSpeakerDataset(valid_filelist_path, cmudict_path, add_blank,
79
+ n_fft, n_feats, sample_rate, hop_length,
80
+ win_length, f_min, f_max)
81
+
82
+ print('Initializing model...')
83
+ model = GradTTS(nsymbols, n_spks, spk_emb_dim, n_enc_channels,
84
+ filter_channels, filter_channels_dp,
85
+ n_heads, n_enc_layers, enc_kernel, enc_dropout, window_size,
86
+ n_feats, dec_dim, beta_min, beta_max, pe_scale).cuda()
87
+ print('Number of encoder parameters = %.2fm' % (model.encoder.nparams/1e6))
88
+ print('Number of decoder parameters = %.2fm' % (model.decoder.nparams/1e6))
89
+
90
+ print('Initializing optimizer...')
91
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=learning_rate)
92
+
93
+ print('Logging test batch...')
94
+ test_batch = test_dataset.sample_test_batch(size=params.test_size)
95
+ for item in test_batch:
96
+ mel, spk = item['y'], item['spk']
97
+ i = int(spk.cpu())
98
+ logger.add_image(f'image_{i}/ground_truth', plot_tensor(mel.squeeze()),
99
+ global_step=0, dataformats='HWC')
100
+ save_plot(mel.squeeze(), f'{log_dir}/original_{i}.png')
101
+
102
+ print('Start training...')
103
+ iteration = 0
104
+ for epoch in range(1, n_epochs + 1):
105
+ model.eval()
106
+ print('Synthesis...')
107
+ with torch.no_grad():
108
+ for item in test_batch:
109
+ x = item['x'].to(torch.long).unsqueeze(0).cuda()
110
+ x_lengths = torch.LongTensor([x.shape[-1]]).cuda()
111
+ spk = item['spk'].to(torch.long).cuda()
112
+ i = int(spk.cpu())
113
+
114
+ y_enc, y_dec, attn = model(x, x_lengths, n_timesteps=50, spk=spk)
115
+ logger.add_image(f'image_{i}/generated_enc',
116
+ plot_tensor(y_enc.squeeze().cpu()),
117
+ global_step=iteration, dataformats='HWC')
118
+ logger.add_image(f'image_{i}/generated_dec',
119
+ plot_tensor(y_dec.squeeze().cpu()),
120
+ global_step=iteration, dataformats='HWC')
121
+ logger.add_image(f'image_{i}/alignment',
122
+ plot_tensor(attn.squeeze().cpu()),
123
+ global_step=iteration, dataformats='HWC')
124
+ save_plot(y_enc.squeeze().cpu(),
125
+ f'{log_dir}/generated_enc_{i}.png')
126
+ save_plot(y_dec.squeeze().cpu(),
127
+ f'{log_dir}/generated_dec_{i}.png')
128
+ save_plot(attn.squeeze().cpu(),
129
+ f'{log_dir}/alignment_{i}.png')
130
+
131
+ model.train()
132
+ dur_losses = []
133
+ prior_losses = []
134
+ diff_losses = []
135
+ with tqdm(loader, total=len(train_dataset)//batch_size) as progress_bar:
136
+ for batch in progress_bar:
137
+ model.zero_grad()
138
+ x, x_lengths = batch['x'].cuda(), batch['x_lengths'].cuda()
139
+ y, y_lengths = batch['y'].cuda(), batch['y_lengths'].cuda()
140
+ spk = batch['spk'].cuda()
141
+ dur_loss, prior_loss, diff_loss = model.compute_loss(x, x_lengths,
142
+ y, y_lengths,
143
+ spk=spk, out_size=out_size)
144
+ loss = sum([dur_loss, prior_loss, diff_loss])
145
+ loss.backward()
146
+
147
+ enc_grad_norm = torch.nn.utils.clip_grad_norm_(model.encoder.parameters(),
148
+ max_norm=1)
149
+ dec_grad_norm = torch.nn.utils.clip_grad_norm_(model.decoder.parameters(),
150
+ max_norm=1)
151
+ optimizer.step()
152
+
153
+ logger.add_scalar('training/duration_loss', dur_loss,
154
+ global_step=iteration)
155
+ logger.add_scalar('training/prior_loss', prior_loss,
156
+ global_step=iteration)
157
+ logger.add_scalar('training/diffusion_loss', diff_loss,
158
+ global_step=iteration)
159
+ logger.add_scalar('training/encoder_grad_norm', enc_grad_norm,
160
+ global_step=iteration)
161
+ logger.add_scalar('training/decoder_grad_norm', dec_grad_norm,
162
+ global_step=iteration)
163
+
164
+ msg = f'Epoch: {epoch}, iteration: {iteration} | dur_loss: {dur_loss.item()}, prior_loss: {prior_loss.item()}, diff_loss: {diff_loss.item()}'
165
+ progress_bar.set_description(msg)
166
+
167
+ dur_losses.append(dur_loss.item())
168
+ prior_losses.append(prior_loss.item())
169
+ diff_losses.append(diff_loss.item())
170
+ iteration += 1
171
+
172
+ msg = 'Epoch %d: duration loss = %.3f ' % (epoch, np.mean(dur_losses))
173
+ msg += '| prior loss = %.3f ' % np.mean(prior_losses)
174
+ msg += '| diffusion loss = %.3f\n' % np.mean(diff_losses)
175
+ with open(f'{log_dir}/train.log', 'a') as f:
176
+ f.write(msg)
177
+
178
+ if epoch % params.save_every > 0:
179
+ continue
180
+
181
+ ckpt = model.state_dict()
182
+ torch.save(ckpt, f=f"{log_dir}/grad_{epoch}.pt")
Grad-TTS/utils.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
2
+ # This program is free software; you can redistribute it and/or modify
3
+ # it under the terms of the MIT License.
4
+ # This program is distributed in the hope that it will be useful,
5
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
6
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7
+ # MIT License for more details.
8
+
9
+ import os
10
+ import glob
11
+ import numpy as np
12
+ import matplotlib.pyplot as plt
13
+
14
+ import torch
15
+
16
+
17
+ def intersperse(lst, item):
18
+ # Adds blank symbol
19
+ result = [item] * (len(lst) * 2 + 1)
20
+ result[1::2] = lst
21
+ return result
22
+
23
+
24
+ def parse_filelist(filelist_path, split_char="|"):
25
+ with open(filelist_path, encoding='utf-8') as f:
26
+ filepaths_and_text = [line.strip().split(split_char) for line in f]
27
+ return filepaths_and_text
28
+
29
+
30
+ def latest_checkpoint_path(dir_path, regex="grad_*.pt"):
31
+ f_list = glob.glob(os.path.join(dir_path, regex))
32
+ f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
33
+ x = f_list[-1]
34
+ return x
35
+
36
+
37
+ def load_checkpoint(logdir, model, num=None):
38
+ if num is None:
39
+ model_path = latest_checkpoint_path(logdir, regex="grad_*.pt")
40
+ else:
41
+ model_path = os.path.join(logdir, f"grad_{num}.pt")
42
+ print(f'Loading checkpoint {model_path}...')
43
+ model_dict = torch.load(model_path, map_location=lambda loc, storage: loc)
44
+ model.load_state_dict(model_dict, strict=False)
45
+ return model
46
+
47
+
48
+ def save_figure_to_numpy(fig):
49
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
50
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
51
+ return data
52
+
53
+
54
+ def plot_tensor(tensor):
55
+ plt.style.use('default')
56
+ fig, ax = plt.subplots(figsize=(12, 3))
57
+ im = ax.imshow(tensor, aspect="auto", origin="lower", interpolation='none')
58
+ plt.colorbar(im, ax=ax)
59
+ plt.tight_layout()
60
+ fig.canvas.draw()
61
+ data = save_figure_to_numpy(fig)
62
+ plt.close()
63
+ return data
64
+
65
+
66
+ def save_plot(tensor, savepath):
67
+ plt.style.use('default')
68
+ fig, ax = plt.subplots(figsize=(12, 3))
69
+ im = ax.imshow(tensor, aspect="auto", origin="lower", interpolation='none')
70
+ plt.colorbar(im, ax=ax)
71
+ plt.tight_layout()
72
+ fig.canvas.draw()
73
+ plt.savefig(savepath)
74
+ plt.close()
75
+ return