def convert(): api_text_2_speech = IAMAuthenticator("paste here") #paste your text to speech api key text_2_speech = TextToSpeechV1(authenticator=api_text_2_speech) text_2_speech.set_service_url("paste here") #paste your text to speech service url if var.get() == "male voice": try: audio_result = asksaveasfilename(defaultextension=".mp3",filetypes=[("mp3 file","*.mp3")]) with open(audio_result,"wb") as audio: audio.write(text_2_speech.synthesize(text,accept="audio/mp3",voice="en-US_HenryV3Voice").get_result().content) audio.close() messagebox.showinfo("Done","Your text file is successfully converted into audio file. Your audio file saved in male voice at " + audio_result) except: pass elif var.get() == "female voice": try: audio_result = asksaveasfilename(defaultextension=".mp3",filetypes=[("mp3 file","*.MP3")]) with open(audio_result,"wb") as audio: audio.write(text_2_speech.synthesize(text,accept="audio/mp3",voice="en-US_AllisonVoice").get_result().content) audio.close() messagebox.showinfo("Done","Your text file is successfully converted into audio file. Your audio file is saved in female voice at " + audio_result) except: pass else: messagebox.showwarning(title="Voice Error", message=f'''Please select the voice and save again.''')
def __init__(self): """ Constants for watson """ self.WATSON_URL = os.getenv("WATSON_URL") self.WATSON_API = os.getenv("WATSON_API") self.JANNY_VOICE = "es-LA_SofiaV3Voice" """ News API """ # https://newsapi.org/ self.NEWS_APIKEY = os.getenv("NEWS_APIKEY") # Init news API self.newsapi = NewsApiClient(api_key=self.NEWS_APIKEY) # Get the last news self.top_headlines = self.newsapi.get_top_headlines(language='es') """ Weather API """ self.WEATHER_API = os.getenv("WEATHER_API") # Set names of the days and moths in spanish self.MONTH_NAMES = [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre" ] self.DAY_NAMES = [ "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo" ] #Set Service self.authenticator = IAMAuthenticator(self.WATSON_API) #TextToSpeech Watson self.wtts = TextToSpeechV1(authenticator=self.authenticator) # Service URL self.wtts.set_service_url(self.WATSON_URL)
def tts_ibm(text='Hello, this is a first system to synthesize speech with IBM API', url='https://gateway-lon.watsonplatform.net/text-to-speech/api', save=False, path='tts_ibm/test.wav'): from ibm_watson import TextToSpeechV1 text_to_speech = TextToSpeechV1( iam_apikey=apikey, url=url ) speech_bytes = text_to_speech.synthesize( text, voice='en-US_AllisonVoice', accept='audio/mp3' ).get_result() # .content if save: with open(path, 'wb') as audio_file: audio_file.write(speech_bytes.content) # Write print(len(speech_bytes.content)) from pygame import mixer from tempfile import TemporaryFile sf = TemporaryFile() for chunk in speech_bytes.iter_content(): sf.write(chunk) sf.seek(0) mixer.init() mixer.music.load(sf) mixer.music.play() return speech_bytes
def speechreg(k, p): if (p == 'biryani' or p == 'jambalaya'): global z s = ' the calorie content of biriyani/jambalaya is 400 to 600 ' o = 'the food is' + p z = o + s elif (p == 'rice'): global z s = ' the calorie content of fried rice is 130' o = 'the food is fried' + p z = o + s elif (p == 'roast chicken'): global z s = ' the calorie content of roast chicken is 240' o = 'the food is fried' + p z = o + s elif (p == 'boiled egg'): global z s = ' the calorie content of boiled egg is 155' o = 'the food is fried' + p z = o + s service = TextToSpeechV1( ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway-lon.watsonplatform.net/text-to-speech/api', iam_apikey='AlBMRdLEg-qoOA5lzpmP48Uhf-OM-5BuHTMkHVO935dM') with open("/home/pi/Documents/harish.wav", 'wb') as audio_file: audio_file.write( service.synthesize(z, voice='en-US_AllisonVoice', accept='audio/wav').get_result().content) song = AudioSegment.from_wav("/home/pi/Documents/harish.wav") play(song)
def get(self, lang, zabbixtext): checkUser(request) try: checkHttpEndpoint(service_url, endpoint_timeout) authenticator = IAMAuthenticator(api_key) text_to_speech = TextToSpeechV1( authenticator=authenticator ) text_to_speech.set_service_url(service_url) if lang == 'pt-br': voice = 'pt-BR_IsabelaV3Voice' else: voice = 'en-US_LisaV3Voice' with open(audio_file, 'wb') as audio_fil: audio_fil.write( text_to_speech.synthesize( zabbixtext, voice=voice, accept='audio/mp3' ).get_result().content) return talk(audio_file) except ApiException as ex: print("Method failed with status code " + str(ex.code) + ": " + str(ex.message)) talk(static_audio_file) return {'message': 'Method failed with status code ' + str(ex.code) + ': ' + str(ex.message)} except Exception as e: print("Method failed: ", str(e)) talk(static_audio_file) return {'message': 'Method failed: ' + str(e)}
def get_voice(text): filename = "" if len(text) < 31: filename = text else: filename = text[:30] observation = [ "This is gross.", "I wish I was never created.", "Sorry to be such a negative nelly.", "Oh bother. . .", "Well Bless your little heart. . ." ] authenticator = IAMAuthenticator(os.environ.get("IMB_KEY")) service = TextToSpeechV1(authenticator=authenticator) service.set_service_url(os.environ.get('IBM_URL')) with open(join(dirname(__file__), f'sounds/{filename}.mp3'), 'wb') as audio_file: response = service.synthesize(text, accept='audio/mp3', voice="en-US_KevinV3Voice").get_result() audio_file.write(response.content) payload = { "text": text, "observation": random.choice(observation), "file": audio_file.name } return payload
def getSpeechFromText(): tts_kwargs = { 'username': textToSpeechUser, 'password': textToSpeechPassword, 'iam_apikey': textToSpeechIAMKey, 'url': textToSpeechUrl } inputText = request.form.get('text') ttsService = TextToSpeechV1(**tts_kwargs) print(inputText) # global language_identify if language_identify == 'en': voice_ = 'en-US_AllisonVoice' else: voice_ = 'ja-JP_EmiVoice' def generate(): audioOut = ttsService.synthesize( inputText, voice=voice_, accept='audio/wav' # 'en-US_AllisonVoice').get_result() ).get_result() data = audioOut.content yield data return Response(response=generate(), mimetype="audio/x-wav")
def __init__(self, hmm='data/spanish/CIEMPIESS_Spanish_Models_581h/Models/modelo', lm='data/spanish/CIEMPIESS_Spanish_Models_581h/Models/leng.lm.bin', dict='data/spanish/CIEMPIESS_Spanish_Models_581h/Models/dicc.dic', grammar='data/gramatica-tp2.gram', dataPath='tmp/'): self.data_path = dataPath config = { 'hmm': hmm, 'lm': lm, 'dict': dict } #model_path = get_model_path() self.ps = Pocketsphinx(**config) # Switch to JSGF grammar jsgf = Jsgf(grammar) rule = jsgf.get_rule('tp2.grammar') fsg = jsgf.build_fsg(rule, self.ps.get_logmath(), 7.5) self.ps.set_fsg('tp2', fsg) self.ps.set_search('tp2') # Síntesis self.tts_authenticator = IAMAuthenticator('cq9_4YcCXxClw2AfgUhbokFktZ-xSRT4kcHS2akcZ05J') self.tts = TextToSpeechV1(authenticator=self.tts_authenticator) self.tts.set_service_url('https://stream.watsonplatform.net/text-to-speech/api')
def tts(question): authenticator = IAMAuthenticator(assistant_api_key) assistant = AssistantV2(version='2020-04-01', authenticator=authenticator) message_input = question message_input.encode('utf-8') assistant.set_service_url(assistant_url) session_id = assistant.create_session( assistant_id=assisstant_id).get_result() session_idj = json.dumps(session_id['session_id'])[1:-1] response = assistant.message(assistant_id=assisstant_id, session_id=session_idj, input={ 'message_type': 'text', 'text': message_input }).get_result() response_of_assistant = json.loads( json.dumps(response['output']['generic'][0]['text'])) print(response_of_assistant) authenticator = IAMAuthenticator(tts_api_key) text_to_speech = TextToSpeechV1(authenticator=authenticator) text_to_speech.set_service_url(tts_url) with open('response.wav', 'wb') as audio_file: audio_file.write( text_to_speech.synthesize(response_of_assistant, voice='ar-AR_OmarVoice', accept='audio/wav').get_result().content) class AudioFile: chunk = 1024 def __init__(self, file): """ Init audio stream """ self.wf = wave.open(file, 'rb') self.p = pyaudio.PyAudio() self.stream = self.p.open(format=self.p.get_format_from_width( self.wf.getsampwidth()), channels=self.wf.getnchannels(), rate=self.wf.getframerate(), output=True) def play(self): """ Play entire file """ data = self.wf.readframes(self.chunk) while data != '': self.stream.write(data) data = self.wf.readframes(self.chunk) def close(self): """ Graceful shutdown """ self.stream.close() self.p.terminate() # Usage example for pyaudio a = AudioFile("response.wav") a.play() a.close()
def __init__(self, api_key, api_url, voice_name=None, lang=None) -> None: if IAMAuthenticator is None or TextToSpeechV1 is None: raise ModuleNotInstalled('ibm-watson') super().__init__(voice_name=voice_name or 'en-US_LisaV3Voice', lang=lang) client = TextToSpeechV1(authenticator=IAMAuthenticator(api_key)) client.set_service_url(api_url) self.client = client
def authentication_function(): global TTS_AUTH global TTS_SERVICE global WATSON_KEY global WATSON_AUTH global WATSON_ASSISTANT global HEADERS global USERPASS global URL global TONE_AUTHENTICATOR global TONE_SERVICE # TTS TTS_AUTH = IAMAuthenticator('4CUYHU_68pReHO4xyfisGiuH7fQmXanfbgf4OR94gp2l') TTS_SERVICE = TextToSpeechV1(authenticator=TTS_AUTH) TTS_SERVICE.set_service_url( 'https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/806b8f05-e01e-4b2b-8d83-194205e7733b' ) # END TTS # STT HEADERS = {} USERPASS = "******".join(get_auth()) HEADERS["Authorization"] = "Basic " + base64.b64encode( USERPASS.encode()).decode() URL = get_url() # END STT # WATSON # put the general watson api key here WATSON_AUTH = IAMAuthenticator( 'AGesgrUJa4L4OVBHpbJgTKfOeCU6kVeVxo2qhIVFqIYS') WATSON_ASSISTANT = AssistantV2(version='2018-09-20', authenticator=WATSON_AUTH) WATSON_ASSISTANT.set_service_url( 'https://api.us-south.assistant.watson.cloud.ibm.com/instances/28f6a127-f399-482b-9b66-5502ad5af6f5' ) # WATSON_ASSISTANT.set_service_url( # 'https://api.us-south.assistant.watson.cloud.ibm.com/instances/28f6a127-f399-482b-9b66-5502ad5af6f5') # session = WATSON_ASSISTANT.create_session( # "82b5e8f6-5a1d-44a5-930e-a388332db998").get_result() # put the specific assistant api key session = WATSON_ASSISTANT.create_session( "9bf7bf36-235e-4089-bf1d-113791da5b43").get_result( ) # put the specific assistant api key WATSON_KEY = session.get("session_id", "") # END WATSON # TONE ANALYZER TONE_AUTHENTICATOR = IAMAuthenticator( 'b0DmzKxaFck7YymuFStEYpJPMmt_bbYLPu8fPO9aEend') TONE_SERVICE = ToneAnalyzerV3(version='2017-09-21', authenticator=TONE_AUTHENTICATOR) TONE_SERVICE.set_service_url( 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/4a4d15eb-5212-447b-8da9-dcad6434130a' )
def __init__(self): self.text = "" self.authenticator = IAMAuthenticator( 'vouzDVPm5xebKwXBabH_aOa6lp8ADPdIOp5crTY26XSI') self.service = TextToSpeechV1(authenticator=self.authenticator) self.service.set_service_url( 'https://api.eu-de.text-to-speech.watson.cloud.ibm.com/instances/85d78639-fd97-4b13-b45b-b7c92912ff3f' ) self.callback = MySynthesizeCallback() self.SSML_text = '"""<speak>' + self.text + '</speak>"""'
def from_text_to_speech(self, txt): text_to_speech = TextToSpeechV1( iam_apikey='Vm2QNF3Iu-HBKoxBykJqRFF-ul5OVVuKzAUaQYe4UtMk', url='https://stream.watsonplatform.net/text-to-speech/api') with open('speech.wav', 'wb') as audio_file: audio_file.write( text_to_speech.synthesize( txt, voice='pt-BR_IsabelaVoice', accept='audio/wav').get_result().content)
def audioGen(message): os.system("rm -f message.mp3") authenticator = IAMAuthenticator('<IBM WATSON TEXT TO SPEECH API KEY>') text_to_speech = TextToSpeechV1(authenticator=authenticator) text_to_speech.set_service_url('<IBM WATSON TEXT TO SPEECH URL') with open('message.mp3', 'wb') as audio_file: audio_file.write( text_to_speech.synthesize(message, accept='audio/mp3').get_result().content)
def dl_sound(i: int, string: str): speaker = TextToSpeechV1(iam_apikey="euoR7ZdLMOBd29wP1fNaZFJsqwKt45TUmwcVwpzbQBcA", url="https://gateway-wdc.watsonplatform.net/text-to-speech/api") with open("music/{i}.mp3".format(i=i), "wb") as audio_file: audio_file.write( speaker.synthesize( string, voice="en-US_AllisonVoice", accept="audio/mp3" ).get_result().content)
def __init__(self, host="watson"): self.host = host self.voice = 'en-GB_KateV3Voice' self.tts = TextToSpeechV1(authenticator=AUTHENTICATOR) self.tts.set_service_url(API_URL) self.file_selected = '' self.mail = imaplib.IMAP4_SSL(IMAP_SERVER) self.mail.login(FROM_EMAIL, FROM_PWD) self.mail.select('inbox') self.session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) self.player = SpotifyPlayer()
def __init__(self): #initialize offline tts self.pyttsxengine = pyttsx3.init() self.authenticator = IAMAuthenticator( '1-D9_Ydjmq8Hg72JkLFBZTNWtC9i6X6NEb6LffHi2LBH') self.text_to_speech = TextToSpeechV1(authenticator=self.authenticator) self.text_to_speech.set_service_url( 'https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/1915a1e6-e3b2-43a7-a600-91c6810567ac' )
def text_to_speech(text_to_speak, voice_to_use, file_name): """Use Watson Text to Speech to convert text to specified voice and save to a WAV file.""" # create Text to Speech client tts = TextToSpeechV1(iam_apikey=keys.text_to_speech_key) # open file and write the synthesized audio content into the file with open(file_name, 'wb') as audio_file: audio_file.write( tts.synthesize(text_to_speak, accept='audio/wav', voice=voice_to_use).get_result().content)
def get_engine(hass, config): """Set up IBM Watson TTS component.""" from ibm_watson import TextToSpeechV1 service = TextToSpeechV1(url=config[CONF_URL], iam_apikey=config[CONF_APIKEY]) supported_languages = list({s[:5] for s in SUPPORTED_VOICES}) default_voice = config[CONF_VOICE] output_format = config[CONF_OUTPUT_FORMAT] return WatsonTTSProvider(service, supported_languages, default_voice, output_format)
def play_sound(phrase): authenticator = IAMAuthenticator(api_key) text_to_speech = TextToSpeechV1(authenticator=authenticator) text_to_speech.set_service_url(api_url) with open('speech.mp3', 'wb+') as audio_file: audio_file.write( text_to_speech.synthesize(phrase, voice='en-US_AllisonVoice', accept='audio/mp3').get_result().content) playsound('speech.mp3')
def tts(): url = "https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/b85a7740-98a7-430b-a122-208a75c00cd7" apikey = "kkMD8MeGj8_EkNdbfrnwYCH9A6N6PtrQlT5ebEes3W3M" auth = IAMAuthenticator(apikey) tts = TextToSpeechV1(authenticator=auth) tts.set_service_url(url) with open('C:/Dev/speechV1.mp3', 'wb') as audiofile: res = tts.synthesize( 'Experience learning takes its cue from games as well as traditional education and can be non-linear and self-managed by the student. Deliver learning experiences via the cloud across all devices, from VR headsets to mobile phone apps, wherever your learners are.', accept='audio/mp3', voice='en-US_AllisonV3Voice').get_result() audiofile.write(res.content) return url
def get_engine(hass, config, discovery_info=None): """Set up IBM Watson TTS component.""" authenticator = IAMAuthenticator(config[CONF_APIKEY]) service = TextToSpeechV1(authenticator) service.set_service_url(config[CONF_URL]) supported_languages = list({s[:5] for s in SUPPORTED_VOICES}) default_voice = config[CONF_VOICE] output_format = config[CONF_OUTPUT_FORMAT] service.set_default_headers({"x-watson-learning-opt-out": "true"}) return WatsonTTSProvider(service, supported_languages, default_voice, output_format)
def text_to_speech(text): url = 'https://api.eu-de.text-to-speech.watson.cloud.ibm.com/instances/8f767ae7-66ed-4222-b423-2482e0a25c1f' apikey = 'g72_X_bSr5ksN4E2InJaiRyqBqd_smmmekD59y8iS_0q' # Setup Service authenticator = IAMAuthenticator(apikey) # New TTS Service tts = TextToSpeechV1(authenticator=authenticator) # Set Service URL tts.set_service_url(url) return tts.synthesize(text, accept='audio/mp3', voice='en-US_AllisonV3Voice').get_result().content
def texttospeechbluemix(lang, voices): authenticator1 = IAMAuthenticator( 'kpRLyx_BAPxZWgSZRkPoARPW43U8_vDzuZv87BiNfS39') text_to_speech = TextToSpeechV1(authenticator=authenticator1) text_to_speech.set_service_url( 'https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/4173c65b-56e0-4a7c-869b-1aa5d1e6750e' ) with open('result/audio/welcome.wav', 'wb') as audio_file: audio_file.write( text_to_speech.synthesize(text=lang, voice=voices, accept='audio/wav').get_result().content)
def authentication_function(): global TTS_AUTH global TTS_SERVICE global WATSON_KEY global WATSON_AUTH global WATSON_ASSISTANT global HEADERS global USERPASS global URL global TONE_SERVICE # TTS TTS_AUTH = IAMAuthenticator('msoasmplOnX24TCnYif7vaJK_bb9h2MuJG0yjp6kpPOR') TTS_SERVICE = TextToSpeechV1(authenticator=TTS_AUTH) TTS_SERVICE.set_service_url( 'https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/74be1af9-eb16-43eb-ae58-3b3f5849e112' ) # END TTS # STT HEADERS = {} USERPASS = "******".join(get_auth()) HEADERS["Authorization"] = "Basic " + base64.b64encode( USERPASS.encode()).decode() URL = get_url() # END STT # WATSON WATSON_AUTH = IAMAuthenticator( 'AGesgrUJa4L4OVBHpbJgTKfOeCU6kVeVxo2qhIVFqIYS' ) # put the general watson api key here WATSON_ASSISTANT = AssistantV2(version='2018-09-20', authenticator=WATSON_AUTH) WATSON_ASSISTANT.set_service_url( 'https://api.us-south.assistant.watson.cloud.ibm.com/instances/28f6a127-f399-482b-9b66-5502ad5af6f5' ) session = WATSON_ASSISTANT.create_session( "9bf7bf36-235e-4089-bf1d-113791da5b43").get_result( ) # put the specific assistant api key WATSON_KEY = session.get("session_id", "") # END WATSON # TONE ANALYZER TONE_AUTHENTICATOR = IAMAuthenticator( 'b0DmzKxaFck7YymuFStEYpJPMmt_bbYLPu8fPO9aEend') TONE_SERVICE = ToneAnalyzerV3(version='2017-09-21', authenticator=TONE_AUTHENTICATOR) TONE_SERVICE.set_service_url( 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/4a4d15eb-5212-447b-8da9-dcad6434130a' )
def text_to_speech(text, pt_lang=False, female=False): service = TextToSpeechV1(authenticator=IAMAuthenticator( 'J_eT6UF74E6_hxhQHp9BffGNwCFve9iNDYiRU7KmoupX')) if pt_lang: voice = 'pt-BR_IsabelaV3Voice' elif female: voice = 'en-US_AllisonV3Voice' else: voice = 'en-US_HenryV3Voice' response = service.synthesize(text, accept='audio/wav', voice=voice).get_result() return response.content
def tts(): # Compiles warning message with plate reading into .mp3 file authenticator = IAMAuthenticator( 'msSN_rmaBVE-BsIEAb-slPATzinzl2FkBmgHWuXTwqEL') service = TextToSpeechV1(authenticator=authenticator) service.set_service_url( 'https://stream.watsonplatform.net/text-to-speech/api') text_val = notif_text() with open(join(dirname(__file__), './output.mp3'), 'wb') as audio_file: response = service.synthesize(text_val, accept='audio/wav', voice="en-US_HenryV3Voice").get_result() audio_file.write(response.content)
def audioGeneration(qtext, filnm): authenticator = IAMAuthenticator( 'JUmWiBlaFBXxwGIc3rIWu_Ed3RWrKlyDL63jldvCJeGZ') text_to_speech = TextToSpeechV1(authenticator=authenticator) text_to_speech.set_service_url( 'https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/8d2ac780-cc69-4350-9f2b-3f4439e0d590' ) with open(filnm, 'wb') as audio_file: audio_file.write( text_to_speech.synthesize(qtext, voice='en-US_MichaelV2Voice', accept='audio/wav').get_result().content) audio_file.close() return (audio_file.name)
def textSpeech(): # Create session with the Text to Speech service text_to_speech = TextToSpeechV1( iam_apikey='THPYijj30qodXeAl4UnT4bIDyKSZzmrtnBXWve1tg9kX', url='https://stream.watsonplatform.net/text-to-speech/api' ) # Use Text to Speech to create mp3 file with open('glad_to_be_here.mp3', 'wb') as audio_file: audio_file.write( text_to_speech.synthesize( 'I\'m so glad you\'re here with me today.', 'audio/mp3', 'en-US_MichaelVoice' ).get_result().content)
def Watson_Text2Speech(Text_toConvert): # Authentication ################### use your API key and URL ################### t2s_authenticator = IAMAuthenticator('') text_to_speech = TextToSpeechV1(authenticator=t2s_authenticator) text_to_speech.set_service_url('') # Converting text to speech and play it # this procedure saves the audio in audio path under name "Watson_Answer_Speech.wav" with open(AudioPath + 'Watson_Answer_Speech.wav', 'wb') as audio_file: audio_file.write( text_to_speech.synthesize(Text_toConvert, voice='en-US_AllisonV3Voice', accept='audio/wav').get_result().content) audio_to_play = AudioSegment.from_wav(audio_file.name) _play_with_simpleaudio(audio_to_play)