def test_unsupported_language_check(self): """Raise ValueError on unsupported language (with language check)""" lang = 'xx' text = "Lorem ipsum" check = True with self.assertRaises(ValueError): gTTS(text=text, lang=lang, lang_check=check)
def test_no_text_parts(self): """Raises AssertionError on, no content to send to API (no text_parts)""" text = "..,\n" with self.assertRaises(AssertionError): filename = self.tmp_path / "no_content.txt" tts = gTTS(text=text) tts.save(filename)
def test_no_text_parts(self): """Raises AssertionError on no content to send to API (no text_parts)""" text = " ..,\n" with self.assertRaises(AssertionError): with tempfile.SpooledTemporaryFile() as f: tts = gTTS(text=text) tts.write_to_fp(f)
def test_get_bodies(): """get request bodies list""" tts = gTTS(text='test', tld='com', lang='en') body = tts.get_bodies()[0] assert 'test' in body # \"en\" url-encoded assert '%5C%22en%5C%22' in body
def test_no_text_parts(tmp_path): """Raises AssertionError on no content to send to API (no text_parts)""" text = " ..,\n" with pytest.raises(AssertionError): filename = tmp_path / 'no_content.txt' tts = gTTS(text=text) tts.save(filename)
def test_save(tmp_path): """Save .mp3 file successfully""" filename = tmp_path / 'save.mp3' # Create gTTS and save tts = gTTS(text='test') tts.save(filename) # Check if file created is > 2k assert filename.stat().st_size > 2000
def say(self, messageText, lang='zh-cn'): if messageText == '': messageText = 'No message to play' tts = gTTS(text=messageText, lang='en') tts.save("Message.mp3") os.system("mpg123 Message.mp3") #mpg321 return 1
def test_unsupported_language_no_check(self): """Raise gTTSError on unsupported language (without language check)""" lang = 'xx' check = False with self.assertRaises(gTTSError): with tempfile.SpooledTemporaryFile() as f: # Create gTTS tts = gTTS(text=self.text, lang=lang, lang_check=check) tts.write_to_fp(f)
def check_tts(self, lang): """Create output .mp3 file successfully""" for slow in (False, True): with tempfile.SpooledTemporaryFile(suffix='.mp3', prefix='test_{}_'.format(lang)) as f: # Create gTTS and save tts = gTTS(self.text, lang, slow=slow) tts.write_to_fp(f) # Check if files created is > 2k self.assertTrue(os.fstat(f.fileno()).st_size > 2000)
def test_save(self): """Save .mp3 file successfully""" (_, save_file_path) = tempfile.mkstemp(suffix='.mp3') # Create gTTS and save tts = gTTS(text='test') tts.save(save_file_path) # Check if file created is > 2k self.assertTrue(os.stat(save_file_path).st_size > 2000)
def test_get_urls(): """Get request URLs list""" tts = gTTS(text='test', tld='com', lang='en-uk') urls = tts.get_urls() # Check the url r = urllib.parse.urlparse(urls[0]) assert r.scheme == 'https' assert r.netloc == 'translate.google.com' assert r.path == '/_/TranslateWebserverUi/data/batchexecute'
def test_TTS(self): """Test a random language and save file""" text = "This is a test" """Create output .mp3 file successfully""" for slow in (False, True): filename = self.tmp_path / "test_{}_.mp3".format(self.lang) # Create gTTS and save tts = gTTS(text, self.lang, slow=slow) tts.save(filename) # Check if files created is > 2k self.assertGreater(filename.stat().st_size, 2000, "Check if files created is > 2k")
def audio(self): # путь к файлу path_name = 'media/poems/audio/' # имя файла mp3_name = '1.mp3' # Эта строка отправляет текст для озвучивания гуглу tts = gTTS(text=self.text, lang='ru') # Получаем от гугла озвученный текст в виде mp3 tts.save(path_name + mp3_name)
def test_TTS(tmp_path, lang): """Test all supported languages and file save""" text = "This is a test" """Create output .mp3 file successfully""" for slow in (False, True): filename = tmp_path / 'test_{}_.mp3'.format(lang) # Create gTTS and save tts = gTTS(text, lang, slow=slow) tts.save(filename) # Check if files created is > 2k assert filename.stat().st_size > 2000
def test_WebRequest(tmp_path): """Test Web Requests""" text = "Lorem ipsum" """Raise gTTSError on unsupported language (without language check)""" lang = 'xx' check = False with pytest.raises(gTTSError): filename = tmp_path / 'xx.txt' # Create gTTS tts = gTTS(text=text, lang=lang, lang_check=check) tts.save(filename)
def test_get_urls(): """Get request URLs list""" tts = gTTS(text='test', tld='com', lang='en-uk') urls = tts.get_urls() # Check the url r = urllib.parse.urlparse(urls[0]) assert r.scheme == 'https' assert r.netloc == 'translate.google.com' assert r.path == '/translate_tts' assert 'test' in urllib.parse.parse_qs(r.query)['q'] assert 'en-uk' in urllib.parse.parse_qs(r.query)['tl']
def waik_up_speaker(now): import os # The text that you want to convert to audio # Language in which you want to convert language = 'fr' # Passing the text and language to the engine, # here we have marked slow=False. Which tells # the module that the converted audio should # have a high speed # Saving the converted audio in a mp3 file named # welcome print("La date est ok : str 0") mytext = BJR[random.randint(0, len(BJR) - 1)] + " !" mytext += REVEIL[random.randint(0, len(REVEIL) - 1)] + " !" mytext += "Il est " + str(now.hour) + " heure et " + str( now.minute) + " minutes" mytext = weather(mytext) print("La date est ok : str 5") mytext = read_anec(mytext) print("La date est ok : str 6") mytext = read_daily(mytext) print("La date est ok : str 7") myobj = gTTS(text=mytext, lang=language, slow=False) myobj.save("welcome.mp3") # Playing the converted file if os.name == 'nt': os.system("cmdmp3.exe welcome.mp3") else: os.system("amixer set PCM -- 93%") os.system("mpg123 welcome.mp3")
def tee(bot, update): chat_id = update.message.chat_id subscription = Subscription.get_or_none(chat_id == chat_id) if not subscription: update.message.reply_text('No games added to this chat') return if not subscription.game.ongoing(): update.message.reply_text('Game is over') return message = 'Teetkö sen vuoros {}'.format( subscription.game.current_player().get_name(bot) ) voice = tts.gTTS(text=message, lang='fi') mp3_fp = io.BytesIO() voice.write_to_fp(mp3_fp) mp3_fp.seek(0) bot.send_voice(chat_id=chat_id, voice=mp3_fp)
def __init__(self, stop): Thread.__init__(self) self.stop = stop self.audio = tts.gTTS("bip", lang="fr") self.audio.save("bip.mp3")
PORT = 1111 vitesse = 150 direction = 1 etatLed = 0 stop = False continuer = True socket = network.newServerSocket() socket.bind((IP,PORT)) threadDetecteur = detecteur.newDetecteur(stop) threadDetecteur.daemon = True threadDetecteur.start() text = "Initialisation du programme" audio = tts.gTTS(text= text, lang="fr") audio.save("init.mp3") os.system("mpg321 init.mp3") while continuer : socket.listen(10) print("en ecoute...") thread = network.newThread(socket.accept()) message = thread.clientsocket.recv(4096) lettre = message.decode("utf-8") print("message recu :", lettre) if stop == False:
from gtts.tts import gTTS if __name__ == "__main__": tts = gTTS('test a b c d e f g',lang='en') tts.save('tts.mp3') print('Finished!')
import network import click from gtts import tts import os ADDRESS ="192.168.1.209" PORT=1111 audio = tts.gTTS("initialisation du programme",lang="fr") audio.save("init.mp3") os.system("mpg321 init.mp3") print("z : avancer\nq : gauche\ns : reculer\nd : droite\ne/r : led\na : stop\nc : exit") audio= tts.gTTS("entre une lettre pour piloter le robot comme dans la description", lang="fr") audio.save("pilote.mp3") os.system("mpg321 pilote.mp3") continuer = True while continuer: socket = network.newClientSocket() socket.connect((ADDRESS,PORT)) lettre = click.getchar() socket.send(lettre.encode()) reponse = socket.recv(4096) print(reponse)
def test_get_bodies(): """get request bodies list""" tts = gTTS(text='test', tld='com', lang='en-uk') body = tts.get_bodies()[0] assert 'test' in body assert 'en-uk' in body
def test_empty_string(self): """Raise AssertionError on empty string""" text = "" with self.assertRaises(AssertionError): gTTS(text=text)
def test_empty_string(): """Raise AssertionError on empty string""" text = "" with pytest.raises(AssertionError): gTTS(text=text)
def test_bad_fp_type(self): """Raise TypeError if fp is not a file-like object (no .write())""" # Create gTTS and save tts = gTTS(text='test') with self.assertRaises(TypeError): tts.write_to_fp(5)
def speak(text, language, slow=False): if not os.path.exists('saved'): os.makedirs('saved') if not os.path.exists("saved/" + language): os.makedirs("saved/" + language) code2lang = { 'af': 'Afrikaans', 'sq': 'Albanian', 'ar': 'Arabic', 'hy': 'Armenian', 'bn': 'Bengali', 'bs': 'Bosnian', 'ca': 'Catalan', 'hr': 'Croatian', 'cs': 'Czech', 'da': 'Danish', 'nl': 'Dutch', 'en': 'English', 'eo': 'Esperanto', 'et': 'Estonian', 'tl': 'Filipino', 'fi': 'Finnish', 'fr': 'French Normal', 'de': 'German', 'el': 'Greek', 'gu': 'Gujarati', 'hi': 'Hindi', 'hu': 'Hungarian', 'is': 'Icelandic', 'id': 'Indonesian', 'it': 'Italian', 'ja': 'Japanese', 'jw': 'Javanese', 'kn': 'Kannada', 'km': 'Khmer', 'ko': 'Korean', 'la': 'Latin', 'lv': 'Latvian', 'mk': 'Macedonian', 'ml': 'Malayalam', 'mr': 'Marathi', 'my': 'Myanmar', 'ne': 'Nepali', 'no': 'Norwegian', 'pl': 'Polish', 'pt': 'Portuguese', 'ro': 'Romanian', 'ru': 'Russian', 'sr': 'Serbian', 'si': 'Sinhala', 'sk': 'Slovak', 'es': 'Spanish', 'su': 'Sundanese', 'sw': 'Swahili', 'sv': 'Swedish', 'ta': 'Tamil', 'te': 'Telugu', 'th': 'Thai', 'tr': 'Turkish', 'uk': 'Ukrainian', 'ur': 'Urdu', 'vi': 'Vietnamese', 'cy': 'Welsh', 'zh-cn': 'Mandarin', 'zh-tw': 'Chinese (Mandarin/Taiwan)', 'en-us': 'English (US)', 'en-ca': 'English (Canada)', 'en-uk': 'English (UK)', 'en-gb': 'English (UK)', 'en-au': 'English (Australia)', 'en-gh': 'English (Ghana)', 'en-in': 'English (India)', 'en-ie': 'English (Ireland)', 'en-nz': 'English (New Zealand)', 'en-ng': 'English (Nigeria)', 'en-ph': 'English (Philippines)', 'en-za': 'English (South Africa)', 'en-tz': 'English (Tanzania)', 'fr-ca': 'French (Canada)', 'fr-fr': 'French', 'pt-br': 'Portuguese (Brazil)', 'pt-pt': 'Portuguese (Portugal)', 'es-es': 'Spanish', 'es-us': 'Spanish (United States)' } lang2code = {v: k for k, v in code2lang.items()} try: gTTS(text, lang=lang2code[language], slow=slow).save( os.path.join( "saved", language, functools.reduce(lambda a, b: a + "_" + b, re.sub(r'[^\w\s]', "", text.lower()).split()) + '.mp3')) except ValueError: print("Connectivity Error! Try Again.")