stefantaubert commited on
Commit
a31f9ef
1 Parent(s): 2b946cf
.gitignore CHANGED
@@ -1,2 +1,111 @@
1
  flagged/
2
  .vscode/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  flagged/
2
  .vscode/
3
+ .vscode
4
+ .ipynb_checkpoints
5
+
6
+ # Byte-compiled / optimized / DLL files
7
+ __pycache__/
8
+ *.py[cod]
9
+ *$py.class
10
+ .mypy
11
+ # C extensions
12
+ *.so
13
+
14
+ # Distribution / packaging
15
+ .Python
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ lib64/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ .hypothesis/
53
+ .pytest_cache/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # pyenv
81
+ .python-version
82
+
83
+ # celery beat schedule file
84
+ celerybeat-schedule
85
+
86
+ # SageMath parsed files
87
+ *.sage.py
88
+
89
+ # Environments
90
+ .env
91
+ .venv
92
+ env/
93
+ venv/
94
+ ENV/
95
+ env.bak/
96
+ venv.bak/
97
+
98
+ # Spyder project settings
99
+ .spyderproject
100
+ .spyproject
101
+
102
+ # Rope project settings
103
+ .ropeproject
104
+
105
+ # mkdocs documentation
106
+ /site
107
+
108
+ # mypy
109
+ .mypy_cache/
110
+
111
+ .vscode
app.py CHANGED
@@ -1,81 +1,309 @@
1
- from logging import getLogger
 
 
 
 
 
 
 
2
 
3
  import gradio as gr
4
- import numpy as np
5
- import numpy.typing as npt
6
- from en_tts import Synthesizer, Transcriber
7
 
8
- FLOAT32_64_MIN_WAV = -1.0
9
- FLOAT32_64_MAX_WAV = 1.0
10
- INT16_MIN = np.iinfo(np.int16).min # -32768 = -(2**15)
11
- INT16_MAX = np.iinfo(np.int16).max # 32767 = 2**15 - 1
12
- INT32_MIN = np.iinfo(np.int32).min # -2147483648 = -(2**31)
13
- INT32_MAX = np.iinfo(np.int32).max # 2147483647 = 2**31 - 1
14
 
15
 
16
- def synt(text: str) -> str:
17
- logger = getLogger(__name__)
18
- logger.info("Initializing transcriber...")
19
- transcriber = Transcriber()
20
 
21
- logger.info("Initializing synthesizer...")
22
- synthesizer = Synthesizer()
23
 
24
- logger.info("Transcribing...")
25
- text_ipa = transcriber.transcribe_to_ipa(text)
26
 
27
- logger.info("Synthesizing...")
28
- audio = synthesizer.synthesize(text_ipa)
29
- audio_int = convert_wav(audio, np.int16)
30
- return 22050, audio_int
31
 
 
32
 
33
- def get_max_value(dtype):
34
- # see wavfile.write() max positive eg. on 16-bit PCM is 32767
35
- if dtype == np.int16:
36
- return INT16_MAX
 
37
 
38
- if dtype == np.int32:
39
- return INT32_MAX
 
 
 
 
40
 
41
- if dtype in (np.float32, np.float64):
42
- return FLOAT32_64_MAX_WAV
 
43
 
44
- assert False
 
 
 
 
 
 
 
 
 
 
45
 
 
 
 
 
 
 
46
 
47
- def get_min_value(dtype):
48
- if dtype == np.int16:
49
- return INT16_MIN
 
 
50
 
51
- if dtype == np.int32:
52
- return INT32_MIN
 
 
 
 
 
 
53
 
54
- if dtype in (np.float32, np.float64):
55
- return FLOAT32_64_MIN_WAV
 
 
 
 
 
 
56
 
57
- assert False
 
 
 
 
 
 
58
 
 
 
 
 
 
 
 
 
59
 
60
- def convert_wav(wav: npt.NDArray[np.float64], to_dtype):
61
- '''
62
- if the wav is over-amplified the result will also be over-amplified.
63
- '''
64
- if wav.dtype != to_dtype:
65
- wav = wav / (-1 * get_min_value(wav.dtype)) * get_max_value(to_dtype)
66
- if to_dtype in (np.int16, np.int32):
67
- # the default seems to be np.fix instead of np.round on wav.astype()
68
- wav = np.round(wav, 0)
69
- wav = wav.astype(to_dtype)
70
 
71
- return wav
 
 
 
 
 
 
 
72
 
 
73
 
74
- example_text = "When the sunlight strikes raindrops in the air, they act as a prism and form a rainbow."
 
75
 
76
- iface = gr.Interface(
77
- fn=synt,
78
- inputs=[gr.Textbox(example_text, label="Text")],
79
- outputs=[gr.Audio(type="numpy", label="Speech", autoplay=True)],
80
- )
81
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import sys
3
+ import zipfile
4
+ from datetime import datetime
5
+ from functools import partial
6
+ from pathlib import Path
7
+ from tempfile import gettempdir
8
+ from typing import Dict
9
 
10
  import gradio as gr
11
+ from scipy.io.wavfile import read
 
 
12
 
13
+ from en_tts_app import (get_log_path, get_work_dir, initialize_app, load_models_to_cache, run_main,
14
+ synthesize_english)
 
 
 
 
15
 
16
 
17
+ def run():
18
+ exit_code = initialize_app()
19
+ if exit_code > 0:
20
+ sys.exit(exit_code)
21
 
22
+ exit_code = run_main(launch_interface)
23
+ sys.exit(exit_code)
24
 
 
 
25
 
26
+ def launch_interface():
27
+ cache = load_models_to_cache()
 
 
28
 
29
+ fn = partial(synt, cache=cache)
30
 
31
+ # iface = gr.Interface(
32
+ # fn=fn,
33
+ # inputs=[gr.Textbox(example_text, label="Text")],
34
+ # outputs=[gr.Audio(type="numpy", label="Speech", autoplay=True)],
35
+ # )
36
 
37
+ with gr.Blocks(
38
+ title="en-tts"
39
+ ) as demo:
40
+ gr.Markdown(
41
+ """
42
+ # English Speech Synthesis
43
 
44
+ Enter or paste your text into the provided text box and click the **Synthesize** button to convert it into speech. You can adjust settings as desired before synthesizing.
45
+ """
46
+ )
47
 
48
+ with gr.Tab("Synthesis"):
49
+ with gr.Row():
50
+ with gr.Column():
51
+ with gr.Group():
52
+ input_txt_box = gr.Textbox(
53
+ None,
54
+ label="Input",
55
+ placeholder="Enter the text you want to synthesize (or load an example from below).",
56
+ lines=10,
57
+ max_lines=5000,
58
+ )
59
 
60
+ with gr.Accordion("Settings", open=False):
61
+ sent_norm_check_box = gr.Checkbox(
62
+ False,
63
+ label="Skip normalization",
64
+ info="Skip normalization of numbers, units and abbreviations."
65
+ )
66
 
67
+ sent_sep_check_box = gr.Checkbox(
68
+ False,
69
+ label="Skip sentence separation",
70
+ info="Skip sentence separation after these characters: .?!"
71
+ )
72
 
73
+ sil_sent_txt_box = gr.Number(
74
+ 0.4,
75
+ minimum=0.0,
76
+ maximum=60,
77
+ step=0.1,
78
+ label="Silence between sentences (s)",
79
+ info="Insert silence between each sentence."
80
+ )
81
 
82
+ sil_para_txt_box = gr.Number(
83
+ 1.0,
84
+ minimum=0.0,
85
+ maximum=60,
86
+ step=0.1,
87
+ label="Silence between paragraphs (s)",
88
+ info="Insert silence between each paragraph."
89
+ )
90
 
91
+ seed_txt_box = gr.Number(
92
+ 0,
93
+ minimum=0,
94
+ maximum=999999,
95
+ label="Seed",
96
+ info="Seed used for inference in order to be able to reproduce the results."
97
+ )
98
 
99
+ sigma_txt_box = gr.Number(
100
+ 1.0,
101
+ minimum=0.0,
102
+ maximum=1.0,
103
+ step=0.001,
104
+ label="Sigma",
105
+ info="Sigma used for inference in WaveGlow."
106
+ )
107
 
108
+ max_decoder_steps_txt_box = gr.Number(
109
+ 5000,
110
+ minimum=1,
111
+ step=500,
112
+ label="Maximum decoder steps",
113
+ info="Stop the synthesis after this number of decoder steps at the latest."
114
+ )
 
 
 
115
 
116
+ denoiser_txt_box = gr.Number(
117
+ 0.005,
118
+ minimum=0.0,
119
+ maximum=1.0,
120
+ step=0.001,
121
+ label="Denoiser strength",
122
+ info="Level of noise reduction used to remove the noise bias from WaveGlow."
123
+ )
124
 
125
+ synt_btn = gr.Button("Synthesize", variant="primary")
126
 
127
+ with gr.Column():
128
+ with gr.Group():
129
 
130
+ with gr.Row():
131
+ with gr.Column():
132
+ out_audio = gr.Audio(
133
+ type="numpy",
134
+ label="Output",
135
+ autoplay=True,
136
+ )
137
+
138
+ with gr.Accordion(
139
+ "Log",
140
+ open=False,
141
+ ):
142
+ out_md = gr.Textbox(
143
+ interactive=False,
144
+ show_copy_button=True,
145
+ lines=15,
146
+ max_lines=10000,
147
+ placeholder="Log will be displayed here.",
148
+ show_label=False,
149
+ )
150
+
151
+ dl_btn = gr.DownloadButton(
152
+ "Download working directory",
153
+ variant="secondary",
154
+ )
155
+
156
+ with gr.Row():
157
+ gr.Examples(
158
+ examples=[
159
+ [
160
+ "When the sunlight strikes raindrops in the air, they act as a prism and form a rainbow.",
161
+ 5000, 1.0, 0.0005, 0, 0.4, 1.0, False, False
162
+ ],
163
+ [
164
+ "Please call Stella. Ask her to bring these things with her from the store: six spoons of fresh snow peas, five thick slabs of blue cheese, and maybe a snack for her brother Bob.\n\nWe also need a small plastic snake and a big toy frog for the kids. She can scoop these things into three red bags, and we will go meet her Wednesday at the train station.",
165
+ 5000, 1.0, 0.0005, 0, 0.4, 1.0, False, False
166
+ ],
167
+ # [
168
+ # "The North Wind and the Sun were disputing which was the stronger, when a traveler came along wrapped in a warm cloak. They agreed that the one who first succeeded in making the traveler take his cloak off should be considered stronger than the other. Then the North Wind blew as hard as he could, but the more he blew the more closely did the traveler fold his cloak around him; and at last the North Wind gave up the attempt. Then the Sun shined out warmly, and immediately the traveler took off his cloak. And so the North Wind was obliged to confess that the Sun was the stronger of the two.",
169
+ # ],
170
+ # [
171
+ # "When the sunlight strikes raindrops in the air, they act as a prism and form a rainbow. The rainbow is a division of white light into many beautiful colors. These take the shape of a long round arch, with its path high above, and its two ends apparently beyond the horizon. There is, according to legend, a boiling pot of gold at one end. People look, but no one ever finds it. When a man looks for something beyond his reach, his friends say he is looking for the pot of gold at the end of the rainbow. Throughout the centuries people have explained the rainbow in various ways. Some have accepted it as a miracle without physical explanation. To the Hebrews it was a token that there would be no more universal floods. The Greeks used to imagine that it was a sign from the gods to foretell war or heavy rain. The Norsemen considered the rainbow as a bridge over which the gods passed from earth to their home in the sky. Others have tried to explain the phenomenon physically. Aristotle thought that the rainbow was caused by reflection of the sun's rays by the rain. Since then physicists have found that it is not reflection, but refraction by the raindrops which causes the rainbows. Many complicated ideas about the rainbow have been formed. The difference in the rainbow depends considerably upon the size of the drops, and the width of the colored band increases as the size of the rops increases. The actual primary rainbow observed is said to be the effect of superimposition of a number of bows. If the red of the second bow falls upon the green of the first, the result is to give a bow with an abnormally wide yellow band, since red and green light when mixed form yellow. This is a very common type of bow, one showing mainly red and yellow, with little or no green or blue."
172
+ # ]
173
+ ],
174
+ fn=fn,
175
+ inputs=[
176
+ input_txt_box,
177
+ max_decoder_steps_txt_box,
178
+ sigma_txt_box,
179
+ denoiser_txt_box,
180
+ seed_txt_box,
181
+ sil_sent_txt_box,
182
+ sil_para_txt_box,
183
+ sent_norm_check_box,
184
+ sent_sep_check_box,
185
+ ],
186
+ outputs=[
187
+ out_audio,
188
+ out_md,
189
+ dl_btn,
190
+ ],
191
+ label="Examples",
192
+ cache_examples=False,
193
+ )
194
+
195
+ with gr.Tab("Info"):
196
+ with gr.Column():
197
+ gr.Markdown(
198
+ """
199
+ ### General information
200
+
201
+ - Speaker: Linda Johnson
202
+ - Language: English
203
+ - Accent: North American
204
+ - Supported special characters: `.?!,:;-—"'()[]`
205
+
206
+ ### Evaluation results
207
+
208
+ |Metric|Value|
209
+ |---|---|
210
+ |MOS naturalness|3.55 ± 0.28 (GT: 4.17 ± 0.23)|
211
+ |MOS intelligibility|4.44 ± 0.24 (GT: 4.63 ± 0.19)|
212
+ |Mean MCD-DTW|29.15|
213
+ |Mean penalty|0.1018|
214
+
215
+ ### Components
216
+
217
+ |Component|Name|URLs|
218
+ |---|---|---|
219
+ |Acoustic model|Tacotron|[Checkpoint](https://zenodo.org/records/10107104), [Code](https://github.com/stefantaubert/tacotron)|
220
+ |Vocoder|WaveGlow|[Checkpoint](https://catalog.ngc.nvidia.com/orgs/nvidia/models/waveglow_ljs_256channels/files?version=3), [Code](https://github.com/stefantaubert/waveglow)
221
+ |Dataset|LJ Speech|[Link](https://keithito.com/LJ-Speech-Dataset), [Transcriptions](https://zenodo.org/records/7499098)|
222
+
223
+ ### Citation
224
+
225
+ Taubert, S. (2024). en-tts (Version 0.0.1) [Computer software]. https://doi.org/10.5281/zenodo.10479347
226
+
227
+ ### Acknowledgments
228
+
229
+ Funded by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) – Project-ID 416228727 – [CRC 1410](https://gepris.dfg.de/gepris/projekt/416228727?context=projekt&task=showDetail&id=416228727)
230
+
231
+ The authors gratefully acknowledge the GWK support for funding this project by providing computing time through the Center for Information Services and HPC (ZIH) at TU Dresden.
232
+
233
+ The authors are grateful to the Center for Information Services and High Performance Computing [Zentrum fur Informationsdienste und Hochleistungsrechnen (ZIH)] at TU Dresden for providing its facilities for high throughput calculations.
234
+
235
+ ### App information
236
+
237
+ - Version: 0.0.1
238
+ - License: [MIT](https://github.com/stefantaubert/en-tts?tab=MIT-1-ov-file#readme)
239
+ - GitHub: [stefantaubert/en-tts](https://github.com/stefantaubert/en-tts)
240
+ """
241
+ )
242
+
243
+ synt_btn.click(
244
+ fn=fn,
245
+ inputs=[
246
+ input_txt_box,
247
+ max_decoder_steps_txt_box,
248
+ sigma_txt_box,
249
+ denoiser_txt_box,
250
+ seed_txt_box,
251
+ sil_sent_txt_box,
252
+ sil_para_txt_box,
253
+ sent_norm_check_box,
254
+ sent_sep_check_box,
255
+ ],
256
+ outputs=[
257
+ out_audio,
258
+ out_md,
259
+ dl_btn,
260
+ ],
261
+ )
262
+
263
+ demo.launch(
264
+ share=False,
265
+ debug=True,
266
+ inbrowser=True,
267
+ quiet=False,
268
+ show_api=False,
269
+ )
270
+
271
+
272
+ def synt(text: str, max_decoder_steps: int, sigma: float, denoiser_strength: float, seed: int, silence_sentences: float, silence_paragraphs: float, skip_normalization: bool, skip_sentence_separation: bool, cache: Dict) -> str:
273
+ result_path = synthesize_english(
274
+ text, cache,
275
+ max_decoder_steps=max_decoder_steps,
276
+ seed=seed,
277
+ sigma=sigma,
278
+ denoiser_strength=denoiser_strength,
279
+ silence_paragraphs=silence_paragraphs,
280
+ silence_sentences=silence_sentences,
281
+ skip_normalization=skip_normalization,
282
+ skip_sentence_separation=skip_sentence_separation,
283
+ )
284
+
285
+ rate, audio_int = read(result_path)
286
+ logs = get_log_path().read_text("utf-8")
287
+ zip_dl_path = create_zip_file_of_output()
288
+ return (rate, audio_int), logs, zip_dl_path
289
+
290
+
291
+ def create_zip_file_of_output() -> Path:
292
+ work_dir = get_work_dir()
293
+
294
+ name = f"en-tts-{datetime.now().strftime('%Y-%m-%dT%H-%M-%S')}"
295
+
296
+ res = shutil.make_archive(Path(gettempdir()) / name, 'zip', root_dir=work_dir)
297
+
298
+ resulting_zip = Path(res)
299
+
300
+ with zipfile.ZipFile(resulting_zip, "a", compression=zipfile.ZIP_DEFLATED) as zipf:
301
+ source_path = get_log_path()
302
+ destination = 'output.log'
303
+ zipf.write(source_path, destination)
304
+
305
+ return resulting_zip
306
+
307
+
308
+ if __name__ == "__main__":
309
+ run()
app_old.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import getLogger
2
+
3
+ import gradio as gr
4
+ import numpy as np
5
+ import numpy.typing as npt
6
+ from en_tts import Synthesizer, Transcriber
7
+
8
+ FLOAT32_64_MIN_WAV = -1.0
9
+ FLOAT32_64_MAX_WAV = 1.0
10
+ INT16_MIN = np.iinfo(np.int16).min # -32768 = -(2**15)
11
+ INT16_MAX = np.iinfo(np.int16).max # 32767 = 2**15 - 1
12
+ INT32_MIN = np.iinfo(np.int32).min # -2147483648 = -(2**31)
13
+ INT32_MAX = np.iinfo(np.int32).max # 2147483647 = 2**31 - 1
14
+
15
+ logger = getLogger(__name__)
16
+ logger.info("Initializing transcriber...")
17
+ transcriber = Transcriber()
18
+
19
+ logger.info("Initializing synthesizer...")
20
+ synthesizer = Synthesizer()
21
+
22
+
23
+ def synt(text: str) -> str:
24
+ logger.info("Transcribing...")
25
+ text_ipa = transcriber.transcribe_to_ipa(text)
26
+
27
+ logger.info("Synthesizing...")
28
+ audio = synthesizer.synthesize(text_ipa)
29
+ audio_int = convert_wav(audio, np.int16)
30
+ return 22050, audio_int
31
+
32
+
33
+ def get_max_value(dtype):
34
+ # see wavfile.write() max positive eg. on 16-bit PCM is 32767
35
+ if dtype == np.int16:
36
+ return INT16_MAX
37
+
38
+ if dtype == np.int32:
39
+ return INT32_MAX
40
+
41
+ if dtype in (np.float32, np.float64):
42
+ return FLOAT32_64_MAX_WAV
43
+
44
+ assert False
45
+
46
+
47
+ def get_min_value(dtype):
48
+ if dtype == np.int16:
49
+ return INT16_MIN
50
+
51
+ if dtype == np.int32:
52
+ return INT32_MIN
53
+
54
+ if dtype in (np.float32, np.float64):
55
+ return FLOAT32_64_MIN_WAV
56
+
57
+ assert False
58
+
59
+
60
+ def convert_wav(wav: npt.NDArray[np.float64], to_dtype):
61
+ '''
62
+ if the wav is over-amplified the result will also be over-amplified.
63
+ '''
64
+ if wav.dtype != to_dtype:
65
+ wav = wav / (-1 * get_min_value(wav.dtype)) * get_max_value(to_dtype)
66
+ if to_dtype in (np.int16, np.int32):
67
+ # the default seems to be np.fix instead of np.round on wav.astype()
68
+ wav = np.round(wav, 0)
69
+ wav = wav.astype(to_dtype)
70
+
71
+ return wav
72
+
73
+
74
+ example_text = "When the sunlight strikes raindrops in the air, they act as a prism and form a rainbow."
75
+
76
+ iface = gr.Interface(
77
+ fn=synt,
78
+ inputs=[gr.Textbox(example_text, label="Text")],
79
+ outputs=[gr.Audio(type="numpy", label="Speech", autoplay=True)],
80
+ )
81
+ iface.launch()
en_tts_app/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from en_tts_app.app import initialize_app, run_main
2
+ from en_tts_app.globals import get_conf_dir, get_log_path, get_work_dir, reset_log
3
+ from en_tts_app.main import load_models_to_cache, synthesize_english
en_tts_app/app.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+ from logging import getLogger
4
+ from time import perf_counter
5
+ from typing import Callable
6
+
7
+ from en_tts_app.globals import get_conf_dir, get_log_path
8
+ from en_tts_app.logging_configuration import (configure_app_logger, configure_file_logger,
9
+ configure_root_logger, get_file_logger)
10
+ from en_tts_app.main import load_models_to_cache
11
+
12
+ INITIALIZED = False
13
+
14
+
15
+ def ensure_conf_dir_exists():
16
+ conf_dir = get_conf_dir()
17
+ if not conf_dir.is_dir():
18
+ root_logger = getLogger()
19
+ root_logger.debug("Creating configuration directory ...")
20
+ conf_dir.mkdir(parents=False, exist_ok=False)
21
+
22
+
23
+ def configure_external_loggers() -> None:
24
+ file_logger = get_file_logger()
25
+ for logger_name in ("httpcore", "httpx", "asyncio", "matplotlib"):
26
+ logger = getLogger(logger_name)
27
+ logger.parent = file_logger
28
+ logger.disabled = False
29
+ logger.propagate = True
30
+ logger.level = logging.DEBUG
31
+
32
+
33
+ def initialize_app() -> int:
34
+ global INITIALIZED
35
+ assert not INITIALIZED
36
+ # CLI logging = INFO
37
+ # External loggers go to file-logger
38
+ # file-logger = DEBUG
39
+
40
+ # # disable mpl temporarily
41
+ # mpl_logger = getLogger("matplotlib")
42
+ # mpl_logger.disabled = True
43
+ # mpl_logger.propagate = False
44
+
45
+ configure_root_logger(logging.INFO)
46
+ root_logger = getLogger()
47
+
48
+ logfile = get_log_path()
49
+ try:
50
+ configure_file_logger(logfile, logging.DEBUG)
51
+ except Exception as ex:
52
+ root_logger.exception("Logging to file is not possible. Exiting.", exc_info=ex, stack_info=True)
53
+ return 1
54
+
55
+ configure_app_logger(logging.INFO)
56
+ configure_external_loggers()
57
+
58
+ ensure_conf_dir_exists()
59
+
60
+ # path not encapsulated in "" because it is only console out
61
+ root_logger.info(f"Log will be written to: {logfile.absolute()}")
62
+ INITIALIZED = True
63
+ return 0
64
+
65
+
66
+ def run_main(method: Callable) -> int:
67
+ global INITIALIZED
68
+ assert INITIALIZED
69
+
70
+ flogger = get_file_logger()
71
+
72
+ start = perf_counter()
73
+ success = True
74
+
75
+ try:
76
+ method()
77
+ except ValueError as error:
78
+ success = False
79
+ logger = getLogger(__name__)
80
+ logger.debug("ValueError occurred.", exc_info=error)
81
+ except Exception as error:
82
+ success = False
83
+ logger = getLogger(__name__)
84
+ logger.debug("Exception occurred.", exc_info=error)
85
+
86
+ duration = perf_counter() - start
87
+ flogger.debug(f"Total duration (seconds): {duration}")
88
+
89
+ exit_code = 0 if success else 1
90
+ return exit_code
en_tts_app/globals.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ from pathlib import Path
3
+ from tempfile import gettempdir
4
+
5
+ from en_tts_cli.logging_configuration import get_cli_logger
6
+
7
+
8
+ def get_conf_dir() -> Path:
9
+ conf_dir = Path.home() / ".en-tts"
10
+ return conf_dir
11
+
12
+
13
+ def get_work_dir() -> Path:
14
+ work_dir = Path(gettempdir()) / "en-tts"
15
+ return work_dir
16
+
17
+
18
+ def get_log_path() -> Path:
19
+ return Path(gettempdir()) / "en-tts.log"
20
+
21
+
22
+ def reset_log() -> None:
23
+ get_log_path().write_text("", "utf-8")
24
+
25
+
26
+ def reset_work_dir():
27
+ root_logger = get_cli_logger()
28
+ work_dir = get_work_dir()
29
+
30
+ if work_dir.is_dir():
31
+ root_logger.debug("Deleting working directory ...")
32
+ shutil.rmtree(work_dir)
33
+ root_logger.debug("Creating working directory ...")
34
+ work_dir.mkdir(parents=False, exist_ok=False)
en_tts_app/helper.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Generator
5
+
6
+
7
+ def get_all_files_in_all_subfolders(directory: Path) -> Generator[Path, None, None]:
8
+ for root, _, files in os.walk(directory):
9
+ for name in files:
10
+ file_path = Path(root) / name
11
+ yield file_path
en_tts_app/logging_configuration.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import platform
4
+ import sys
5
+ from importlib.metadata import version
6
+ from logging import Formatter, Handler, Logger, StreamHandler, getLogger
7
+ from logging.handlers import MemoryHandler
8
+ from pathlib import Path
9
+ from pkgutil import iter_modules
10
+
11
+ __APP_NAME = "en-tts"
12
+
13
+ __version__ = version(__APP_NAME)
14
+
15
+
16
+ class ConsoleFormatter(logging.Formatter):
17
+ """Logging colored formatter, adapted from https://stackoverflow.com/a/56944256/3638629"""
18
+
19
+ purple = '\x1b[34m'
20
+ blue = '\x1b[36m'
21
+ # blue = '\x1b[38;5;39m'
22
+ yellow = '\x1b[38;5;226m'
23
+ red = '\x1b[1;49;31m'
24
+ bold_red = '\x1b[1;49;31m'
25
+ reset = '\x1b[0m'
26
+
27
+ collected_loggers = set()
28
+
29
+ def __init__(self):
30
+ super().__init__()
31
+ self.datefmt = '%H:%M:%S'
32
+ fmt = '(%(levelname)s) %(message)s'
33
+ fmt_info = '%(message)s'
34
+
35
+ self.fmts = {
36
+ logging.NOTSET: self.purple + fmt + self.reset,
37
+ logging.DEBUG: self.blue + fmt + self.reset,
38
+ logging.INFO: fmt_info,
39
+ logging.WARNING: self.yellow + fmt + self.reset,
40
+ logging.ERROR: self.red + fmt + self.reset,
41
+ logging.CRITICAL: self.bold_red + fmt + self.reset,
42
+ }
43
+
44
+ def format(self, record):
45
+ log_fmt = self.fmts.get(record.levelno)
46
+ formatter = logging.Formatter(log_fmt, self.datefmt)
47
+ self.collected_loggers.add(record.name)
48
+
49
+ return formatter.format(record)
50
+
51
+
52
+ def add_console_out(logger: Logger) -> StreamHandler:
53
+ console = StreamHandler()
54
+ logger.addHandler(console)
55
+ set_console_formatter(console)
56
+ return console
57
+
58
+
59
+ def set_console_formatter(handler: Handler) -> None:
60
+ logging_formatter = ConsoleFormatter()
61
+ handler.setFormatter(logging_formatter)
62
+
63
+
64
+ def set_logfile_formatter(handler: Handler) -> None:
65
+ fmt = '[%(asctime)s.%(msecs)03d] %(name)s (%(levelname)s) %(message)s'
66
+ datefmt = '%Y/%m/%d %H:%M:%S'
67
+ logging_formatter = Formatter(fmt, datefmt)
68
+ handler.setFormatter(logging_formatter)
69
+
70
+
71
+ def get_app_logger() -> Logger:
72
+ logger = getLogger("en_tts_app")
73
+ return logger
74
+
75
+
76
+ def get_file_logger() -> Logger:
77
+ flogger = getLogger("file.en_tts_app")
78
+ return flogger
79
+
80
+
81
+ def configure_app_logger(level: int) -> None:
82
+ app_logger = get_app_logger()
83
+ app_logger.handlers.clear()
84
+ assert len(app_logger.handlers) == 0
85
+ console_handler = add_console_out(app_logger)
86
+ # console_handler.setLevel(logging.DEBUG if debug else logging.INFO)
87
+ app_logger.setLevel(level)
88
+
89
+ core_logger = getLogger("en_tts")
90
+ core_logger.parent = app_logger
91
+
92
+ file_logger = get_file_logger()
93
+ app_logger.parent = file_logger
94
+
95
+
96
+ def configure_root_logger(level: int) -> None:
97
+ # productive = False
98
+ # loglevel = logging.INFO if productive else logging.DEBUG
99
+ root_logger = getLogger()
100
+ root_logger.setLevel(level)
101
+ root_logger.manager.disable = logging.NOTSET
102
+ if len(root_logger.handlers) > 0:
103
+ console = root_logger.handlers[0]
104
+ set_console_formatter(console)
105
+ else:
106
+ console = add_console_out(root_logger)
107
+
108
+ # console.setLevel(logging.DEBUG if debug else logging.INFO)
109
+
110
+
111
+ def configure_file_logger(path: Path, level: int):
112
+ flogger = get_file_logger()
113
+ assert len(flogger.handlers) == 0
114
+ path.parent.mkdir(parents=True, exist_ok=True)
115
+ if path.is_file():
116
+ os.remove(path)
117
+ path.write_text("")
118
+ fh = logging.FileHandler(path)
119
+ set_logfile_formatter(fh)
120
+ # fh.setLevel(logging.DEBUG if debug else logging.INFO)
121
+ flogger.setLevel(level)
122
+ # mh = MemoryHandler(buffer_capacity, logging.ERROR, fh, True)
123
+ flogger.addHandler(fh)
124
+
125
+ if flogger.propagate:
126
+ flogger.propagate = False
127
+
128
+
129
+ def log_sysinfo():
130
+ flogger = get_file_logger()
131
+
132
+ sys_version = sys.version.replace('\n', '')
133
+ flogger.debug(f"CLI version: {__version__}")
134
+ flogger.debug(f"Python version: {sys_version}")
135
+ flogger.debug("Modules: %s", ', '.join(sorted(p.name for p in iter_modules())))
136
+
137
+ my_system = platform.uname()
138
+ flogger.debug(f"System: {my_system.system}")
139
+ flogger.debug(f"Node Name: {my_system.node}")
140
+ flogger.debug(f"Release: {my_system.release}")
141
+ flogger.debug(f"Version: {my_system.version}")
142
+ flogger.debug(f"Machine: {my_system.machine}")
143
+ flogger.debug(f"Processor: {my_system.processor}")
en_tts_app/main.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import shutil
3
+ from pathlib import Path
4
+ from typing import Dict, Optional
5
+
6
+ from ordered_set import OrderedSet
7
+ from pronunciation_dictionary import PronunciationDict, SerializationOptions, save_dict
8
+
9
+ from en_tts.helper import get_default_device, normalize_audio
10
+ from en_tts.io import save_audio
11
+ from en_tts.synthesizer import Synthesizer
12
+ from en_tts.transcriber import Transcriber
13
+ from en_tts_app.globals import get_conf_dir, get_work_dir, reset_log, reset_work_dir
14
+ from en_tts_app.logging_configuration import get_app_logger, get_file_logger, log_sysinfo
15
+
16
+ CACHE_TRANSCRIBER = "transcriber"
17
+ CACHE_SYNTHESIZER = "synthesizer"
18
+
19
+
20
+ def load_models_to_cache() -> Dict:
21
+ cli_logger = get_app_logger()
22
+ cache = {}
23
+
24
+ conf_dir = get_conf_dir()
25
+ device = get_default_device()
26
+
27
+ cli_logger.info("Initializing Transcriber...")
28
+ cache[CACHE_TRANSCRIBER] = Transcriber(conf_dir)
29
+
30
+ cli_logger.info("Initializing Synthesizer...")
31
+ cache[CACHE_SYNTHESIZER] = Synthesizer(conf_dir, device)
32
+ return cache
33
+
34
+
35
+ def synthesize_english(text: str, cache: Dict, *, max_decoder_steps: int = 5000, sigma: float = 1.0, denoiser_strength: float = 0.0005, seed: int = 0, silence_sentences: float = 0.4, silence_paragraphs: float = 1.0, loglevel: int = 2, skip_normalization: bool = False, skip_sentence_separation: bool = False, custom_output: Optional[Path] = None) -> Path:
36
+ cli_logger = get_app_logger()
37
+ reset_log()
38
+ reset_work_dir()
39
+ log_sysinfo()
40
+
41
+ if loglevel == 0:
42
+ cli_logger.setLevel(logging.WARNING)
43
+
44
+ if custom_output is None:
45
+ custom_output = get_work_dir() / "output.wav"
46
+
47
+ text_ipa = convert_eng_to_ipa(
48
+ text, cache[CACHE_TRANSCRIBER],
49
+ loglevel=loglevel,
50
+ skip_normalization=skip_normalization,
51
+ skip_sentence_separation=skip_sentence_separation
52
+ )
53
+
54
+ output_path = synthesize_ipa_core(
55
+ text_ipa, cache[CACHE_SYNTHESIZER], custom_output,
56
+ max_decoder_steps=max_decoder_steps, sigma=sigma, denoiser_strength=denoiser_strength,
57
+ seed=seed, silence_sentences=silence_sentences, silence_paragraphs=silence_paragraphs, loglevel=loglevel
58
+ )
59
+
60
+ return output_path
61
+
62
+
63
+ def convert_eng_to_ipa(text: str, transcriber: Transcriber, *, loglevel: int = 1, skip_normalization: bool = False, skip_sentence_separation: bool = False) -> str:
64
+ t = transcriber
65
+ text_ipa = t.transcribe_to_ipa(text, skip_normalization, skip_sentence_separation)
66
+
67
+ if loglevel >= 1:
68
+ for txt, name in (
69
+ (text, "text"),
70
+ (t.text_normed, "text.normed"),
71
+ (t.text_sentenced, "text.sentenced"),
72
+ (t.text_ipa, "text.ipa"),
73
+ (t.text_ipa_readable, "text.ipa.readable"),
74
+ (text_ipa, "text.ipa.silenced"),
75
+ ):
76
+ try_log_text(txt, name)
77
+
78
+ for v, name in (
79
+ (t.vocabulary, "vocabulary"),
80
+ (t.oov1, "oov1"),
81
+ (t.oov2, "oov2"),
82
+ (t.oov3, "oov3"),
83
+ ):
84
+ try_log_voc(v, name)
85
+
86
+ for d, name in (
87
+ (t.dict1, "dict1"),
88
+ (t.dict1_single, "dict1.single"),
89
+ (t.dict2, "dict2"),
90
+ (t.dict2_single, "dict2.single"),
91
+ (t.dict1_2, "dict1+2"),
92
+ (t.dict3, "dict3"),
93
+ (t.dict3_single, "dict3.single"),
94
+ (t.dict1_2_3, "dict1+2+3"),
95
+ (t.dict4_arpa, "dict4.arpa"),
96
+ (t.dict4, "dict4"),
97
+ (t.dict4_single, "dict4.single"),
98
+ (t.dict1_2_3_4, "dict1+2+3+4"),
99
+ ):
100
+ try_log_dict(d, name)
101
+ return text_ipa
102
+
103
+
104
+ def synthesize_ipa_core(text_ipa: str, synthesizer: Synthesizer, output: Path, *, max_decoder_steps: int = 5000, sigma: float = 1.0, denoiser_strength: float = 0.0005, seed: int = 0, silence_sentences: float = 0.4, silence_paragraphs: float = 1.0, loglevel: int = 1) -> Path:
105
+ logger = logging.getLogger(__name__)
106
+ work_dir = get_work_dir()
107
+
108
+ audio = synthesizer.synthesize(text_ipa, max_decoder_steps, seed, sigma,
109
+ denoiser_strength, silence_sentences, silence_paragraphs, silent=loglevel == 0)
110
+ unnormed_out = work_dir / "output.unnormed.wav"
111
+ save_audio(audio, unnormed_out)
112
+ work_dir_output = unnormed_out
113
+
114
+ try:
115
+ normalize_audio(unnormed_out, work_dir / "output.wav")
116
+ work_dir_output = work_dir / "output.wav"
117
+ except Exception as error:
118
+ logger.warning("Normalization was not possible!", exc_info=error, stack_info=True)
119
+ logger.info(f"Saved audio to: '{unnormed_out.absolute()}'")
120
+
121
+ if output != work_dir_output:
122
+ try:
123
+ output.parent.mkdir(parents=True, exist_ok=True)
124
+ shutil.copyfile(work_dir_output, output)
125
+ except Exception as ex:
126
+ logger.exception(
127
+ f"Output couldn't be created at: '{output.absolute()}'", exc_info=ex, stack_info=True)
128
+ logger.info(f"Saved audio to: '{work_dir_output.absolute()}'")
129
+ logger.info(f"Saved audio to: '{output.absolute()}'")
130
+ return output
131
+
132
+
133
+ def try_log_dict(dictionary: Optional[PronunciationDict], name: str) -> None:
134
+ if dictionary:
135
+ work_dir = get_work_dir()
136
+ logfile = work_dir / f"{name}.dict"
137
+ save_dict(dictionary, logfile, "utf-8", SerializationOptions("TAB", False, True))
138
+ flogger = get_file_logger()
139
+ flogger.info(f"{name}: {logfile.absolute()}")
140
+
141
+
142
+ def try_log_voc(vocabulary: Optional[OrderedSet[str]], name: str) -> None:
143
+ if vocabulary:
144
+ work_dir = get_work_dir()
145
+ logfile = work_dir / f"{name}.txt"
146
+ logfile.write_text("\n".join(vocabulary), "utf-8")
147
+ flogger = get_file_logger()
148
+ flogger.info(f"{name}: {logfile.absolute()}")
149
+
150
+
151
+ def try_log_text(text: Optional[str], name: str) -> None:
152
+ if text:
153
+ work_dir = get_work_dir()
154
+ logfile = work_dir / f"{name}.txt"
155
+ logfile.write_text(text, "utf-8")
156
+ flogger = get_file_logger()
157
+ flogger.info(f"{name}: {logfile.absolute()}")
en_tts_app/py.typed ADDED
File without changes