|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2022 Mycroft AI Inc. |
| 3 | +# |
| 4 | +# This program is free software: you can redistribute it and/or modify |
| 5 | +# it under the terms of the GNU Affero General Public License as published by |
| 6 | +# the Free Software Foundation, either version 3 of the License, or |
| 7 | +# (at your option) any later version. |
| 8 | +# |
| 9 | +# This program is distributed in the hope that it will be useful, |
| 10 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | +# GNU Affero General Public License for more details. |
| 13 | +# |
| 14 | +# You should have received a copy of the GNU Affero General Public License |
| 15 | +# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | +# |
| 17 | +""" |
| 18 | +Generates sha256 hashs of audio samples for all languages/voices. |
| 19 | +""" |
| 20 | +import argparse |
| 21 | +import contextlib |
| 22 | +import functools |
| 23 | +import hashlib |
| 24 | +import logging |
| 25 | +import re |
| 26 | +import tempfile |
| 27 | +import typing |
| 28 | +from multiprocessing import Pool |
| 29 | +from pathlib import Path |
| 30 | + |
| 31 | +from mimic3_tts import Mimic3Settings, Mimic3TextToSpeechSystem, Voice |
| 32 | + |
| 33 | +# ----------------------------------------------------------------------------- |
| 34 | + |
| 35 | +_TEST_SENTENCES = { |
| 36 | + "de": """Der Regenbogen ist ein atmosphärisch-optisches Phänomen, das als |
| 37 | + kreisbogenförmiges farbiges Lichtband in einer von der Sonne |
| 38 | + beschienenen Regenwand oder -wolke wahrgenommen wird.""", |
| 39 | + "en": """A rainbow is a meteorological phenomenon that is caused by |
| 40 | + reflection, refraction and dispersion of light in water droplets |
| 41 | + resulting in a spectrum of light appearing in the sky.""", |
| 42 | + "el": """Οι επιστήμονες μελετούν ακόμη το ουράνιο τόξο.""", |
| 43 | + "es": """Un arcoíris o arco iris es un fenómeno óptico y meteorológico que |
| 44 | + consiste en la aparición en el cielo de un arco de luz multicolor, |
| 45 | + originado por la descomposición de la luz solar en el espectro visible, |
| 46 | + la cual se produce por refracción, cuando los rayos del sol atraviesan |
| 47 | + pequeñas gotas de agua contenidas en la atmósfera terrestre.""", |
| 48 | + "fa": """برای دیگر کاربردها رنگینکمان (ابهامزدایی) را ببینید.""", |
| 49 | + "fi": """Sateenkaari on spektrin väreissä esiintyvä ilmakehän optinen ilmiö.""", |
| 50 | + "fr": """Un arc-en-ciel est un photométéore, un phénomène optique se |
| 51 | + produisant dans le ciel, visible dans la direction opposée au Soleil |
| 52 | + quand il brille pendant la pluie.""", |
| 53 | + "hu": """A szivárvány olyan optikai jelenség, melyet eső- vagy páracseppek |
| 54 | + okoznak, mikor a fény prizmaszerűen megtörik rajtuk és színeire bomlik, |
| 55 | + kialakul a színképe, más néven spektruma.""", |
| 56 | + "it": """In fisica dell'atmosfera e meteorologia l'arcobaleno è un fenomeno |
| 57 | + ottico atmosferico che produce uno spettro quasi continuo di luce nel |
| 58 | + cielo quando la luce del Sole attraversa le gocce d'acqua rimaste in |
| 59 | + sospensione dopo un temporale, o presso una cascata o una fontana.""", |
| 60 | + "ko": """무지개(문화어: 색동다리)는 하늘에 보이는 호(弧)를 이루는 색 띠를 말한다.""", |
| 61 | + "nl": """Een regenboog is een gekleurde cirkelboog die aan de hemel |
| 62 | + waargenomen kan worden als de, laagstaande, zon tegen een nevel van |
| 63 | + waterdruppeltjes aan schijnt en de zon zich achter de waarnemer bevindt.""", |
| 64 | + "pt": """Um arco-íris, também popularmente denominado arco-da-velha, é um |
| 65 | + fenômeno óptico e meteorológico que separa a luz do sol em seu espectro |
| 66 | + contínuo quando o sol brilha sobre gotículas de água suspensas no ar.""", |
| 67 | + "ru": """Ра́дуга, атмосферное, оптическое и метеорологическое явление, |
| 68 | + наблюдаемое при освещении ярким источником света множества водяных |
| 69 | + капель.""", |
| 70 | + "sv": """En regnbåge är ett optiskt, meteorologiskt fenomen som uppträder som |
| 71 | + ett fullständigt ljusspektrum i form av en båge på himlen då solen lyser |
| 72 | + på nedfallande regn.""", |
| 73 | + "sw": """Upinde wa mvua ni tao la rangi mbalimbali angani ambalo linaweza |
| 74 | + kuonekana wakati Jua huangaza kupitia matone ya mvua inayoanguka.""", |
| 75 | + "te": """ఇంద్ర ధనుస్సు దృష్టి విద్యా సంబంధమయిన వాతావరణ శాస్త్ర సంబంధమయిన దృగ్విషయం.""", |
| 76 | + "uk": """Весе́лка, також ра́йдуга оптичне явище в атмосфері, що являє собою |
| 77 | + одну, дві чи декілька різнокольорових дуг (або кіл, якщо дивитися з |
| 78 | + повітря), що спостерігаються на тлі хмари, якщо вона розташована проти |
| 79 | + Сонця. Червоний колір ми бачимо з зовнішнього боку первинної веселки, а |
| 80 | + фіолетовий — із внутрішнього.""", |
| 81 | + "vi": """Cầu vồng hay mống cũng như quang phổ là hiện tượng tán sắc của các |
| 82 | + ánh sáng từ Mặt Trời khi khúc xạ và phản xạ qua các giọt nước mưa.""", |
| 83 | + "yo": """E̟nì kò̟ò̟kan ló ní è̟tó̟ láti kó̟ è̟kó̟.""", |
| 84 | +} |
| 85 | + |
| 86 | +_LOGGER = logging.getLogger("get_samples") |
| 87 | + |
| 88 | +# ----------------------------------------------------------------------------- |
| 89 | + |
| 90 | + |
| 91 | +def synthesize(output_dir: Path, voice: Voice) -> typing.Iterable[str]: |
| 92 | + """Generate samples for voice in a separate process""" |
| 93 | + tts = Mimic3TextToSpeechSystem( |
| 94 | + Mimic3Settings( |
| 95 | + length_scale=1.0, |
| 96 | + noise_scale=0.0, |
| 97 | + noise_w=0.0, |
| 98 | + use_deterministic_compute=True, |
| 99 | + ) |
| 100 | + ) |
| 101 | + |
| 102 | + key = voice.key |
| 103 | + language = voice.language |
| 104 | + speakers = voice.speakers or [""] |
| 105 | + |
| 106 | + # Try en_US and en |
| 107 | + text = _TEST_SENTENCES.get(language, _TEST_SENTENCES.get(language.split("_")[0])) |
| 108 | + |
| 109 | + assert text, f"No sentences for {language}" |
| 110 | + |
| 111 | + # Normalize whitespace |
| 112 | + text = re.sub(r"\s+", " ", text) |
| 113 | + |
| 114 | + voice_dir = output_dir / key |
| 115 | + voice_dir.mkdir(parents=True, exist_ok=True) |
| 116 | + |
| 117 | + results = [] |
| 118 | + for speaker in sorted(speakers): |
| 119 | + if speaker: |
| 120 | + # Multi-speaker |
| 121 | + voice_key = f"{key}#{speaker}" |
| 122 | + sample_path = voice_dir / f"sample_{speaker}.wav" |
| 123 | + else: |
| 124 | + # Single speaker |
| 125 | + voice_key = key |
| 126 | + sample_path = voice_dir / "sample.wav" |
| 127 | + |
| 128 | + if not sample_path.is_file(): |
| 129 | + tts.voice = voice_key |
| 130 | + wav_bytes = tts.text_to_wav(text) |
| 131 | + sample_path.write_bytes(wav_bytes) |
| 132 | + |
| 133 | + wav_hash = hashlib.sha256(sample_path.read_bytes()).hexdigest() |
| 134 | + _LOGGER.info(sample_path) |
| 135 | + |
| 136 | + results.append(f"{voice_key} {wav_hash}") |
| 137 | + |
| 138 | + return results |
| 139 | + |
| 140 | + |
| 141 | +# ----------------------------------------------------------------------------- |
| 142 | + |
| 143 | + |
| 144 | +def main(): |
| 145 | + """Generate WAV samples from Mimic 3 in deterministic mode for testing""" |
| 146 | + parser = argparse.ArgumentParser() |
| 147 | + parser.add_argument("--output-dir", help="Directory to write samples") |
| 148 | + args = parser.parse_args() |
| 149 | + |
| 150 | + logging.basicConfig(level=logging.INFO) |
| 151 | + |
| 152 | + if args.output_dir: |
| 153 | + output_dir = Path(args.output_dir) |
| 154 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 155 | + temp_dir = contextlib.nullcontext() |
| 156 | + else: |
| 157 | + # Output to temp directory |
| 158 | + temp_dir = tempfile.TemporaryDirectory() |
| 159 | + output_dir = Path(temp_dir.name) |
| 160 | + |
| 161 | + tts = Mimic3TextToSpeechSystem(Mimic3Settings()) |
| 162 | + |
| 163 | + # ------------------------------------------------------------------------- |
| 164 | + # Generate samples |
| 165 | + # ------------------------------------------------------------------------- |
| 166 | + |
| 167 | + with temp_dir, Pool() as pool: |
| 168 | + voices = sorted(tts.get_voices(), key=lambda v: v.key) |
| 169 | + for results in pool.map(functools.partial(synthesize, output_dir), voices): |
| 170 | + for result in results: |
| 171 | + print(result) |
| 172 | + |
| 173 | + |
| 174 | +# ----------------------------------------------------------------------------- |
| 175 | + |
| 176 | +if __name__ == "__main__": |
| 177 | + main() |
0 commit comments