Project P.I.N.N. - Module : GoogleTTS.py 09-01-2014, 11:15 AM
#1
Hello, HC.
As you know I have been sharing snippets from my project P.I.N.N. and so today I will share with you this module code named GoogleTTS.py, my project uses Google Text-To-Speech Service for for converting text to voice. See the code and hear the Sample .mp3 files I have attached. You should hear HC-Hello.mp3 and japanese version file name HC-Hello-Ja.mp3
I have a facility where you can even change the voice to other languages like Japanese or French etc. by just calling the getTTS() function with an addition parameter of lang='<Your-Lang-COde>', like for english we have en and for japanese we have ja.
I have added a logger for the code just to make it more readable and better for developers.
Here's a Sample log file :-
Download Here :-
[attachment=111]
Test GoogleTTS using the code below :-
Have a nice day
Thank you,
Sincerely,
Psycho_Coder.
As you know I have been sharing snippets from my project P.I.N.N. and so today I will share with you this module code named GoogleTTS.py, my project uses Google Text-To-Speech Service for for converting text to voice. See the code and hear the Sample .mp3 files I have attached. You should hear HC-Hello.mp3 and japanese version file name HC-Hello-Ja.mp3
I have a facility where you can even change the voice to other languages like Japanese or French etc. by just calling the getTTS() function with an addition parameter of lang='<Your-Lang-COde>', like for english we have en and for japanese we have ja.
I have added a logger for the code just to make it more readable and better for developers.
Here's a Sample log file :-
Code:
2014-09-01 15:42:46,572 - __main__ - INFO - Logger Initialized
2014-09-01 15:42:46,573 - __main__ - INFO - getTTS() Function called.
2014-09-01 15:42:46,573 - __main__ - INFO - File to be saved in Default location : /home/psychocoder/PycharmProjects/P.I.N.N./pinn/web
2014-09-01 15:42:46,573 - __main__ - INFO - Query Params Encoded q=Hello%2C+How+are+you+%3F.+My+name+is+PINN.+How+can+I+assist+you+%3F&tl=en
2014-09-01 15:42:46,573 - __main__ - INFO - Request GoogleTTS service
2014-09-01 15:42:46,822 - __main__ - INFO - Response received from GoogleTTS service
2014-09-01 15:42:46,823 - __main__ - INFO - Writing the received response as Hellomp3
2014-09-01 15:42:47,042 - __main__ - INFO - File saved at location : /home/psychocoder/PycharmProjects/P.I.N.N./pinn/web/Hello.mp3
2014-09-01 15:42:47,042 - __main__ - INFO - getTTS() Function called.
2014-09-01 15:42:47,043 - __main__ - INFO - File to be saved in Default location : /home/psychocoder/PycharmProjects/P.I.N.N./pinn/web
2014-09-01 15:42:47,043 - __main__ - INFO - Query Params Encoded q=Hi%21+Hack+Community%2C+its+me+Psycho+Coder.+I+love+hentai%2C+Do+you+like+it+tou+%3F&tl=en
2014-09-01 15:42:47,043 - __main__ - INFO - Request GoogleTTS service
2014-09-01 15:42:47,377 - __main__ - INFO - Response received from GoogleTTS service
2014-09-01 15:42:47,377 - __main__ - INFO - Writing the received response as HC-Hellomp3
2014-09-01 15:42:47,672 - __main__ - INFO - File saved at location : /home/psychocoder/PycharmProjects/P.I.N.N./pinn/web/HC-Hello.mp3
2014-09-01 15:42:47,672 - __main__ - INFO - getTTS() Function called.
2014-09-01 15:42:47,672 - __main__ - INFO - File to be saved in Default location : /home/psychocoder/PycharmProjects/P.I.N.N./pinn/web
2014-09-01 15:42:47,672 - __main__ - INFO - Query Params Encoded q=Hi%21+Hack+Community%2C+its+me+Psycho+Coder.+I+love+hentai%2C+Do+you+like+it+too+%3F&tl=ja
2014-09-01 15:42:47,673 - __main__ - INFO - Request GoogleTTS service
2014-09-01 15:42:48,177 - __main__ - INFO - Response received from GoogleTTS service
2014-09-01 15:42:48,177 - __main__ - INFO - Writing the received response as HC-Hello-Jamp3
2014-09-01 15:42:48,624 - __main__ - INFO - File saved at location : /home/psychocoder/PycharmProjects/P.I.N.N./pinn/web/HC-Hello-Ja.mp3Download Here :-
[attachment=111]
Code:
"""
Copyright (C) 2014 Animesh Shaw. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Animesh Shaw ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import logging
import os
from urllib import urlencode
from urllib2 import Request, urlopen
from pinn.Constants import Constants
from pinn.exceptions.EmptyParamError import EmptyParamError
class GoogleTTS():
"""
Class to convert Text to Speech Using Google Text-To-Speech Service.
"""
def __init__(self, text=""):
"""
Initialize variables.
:param text: The text to be converted to Speech.
Can be initialized here as well.
"""
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
handler = logging.FileHandler("GoogleTTS.log")
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s "
"- %(levelname)s - %(message)s")
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.logger.info("Logger Initialized")
if not text and type(text) == str:
self.CURRDATA = text.strip()
self.BASEURL = "http://translate.google.com/translate_tts"
self.cons = Constants()
def settext(self, text):
if text.strip() != "" and type(text) == str:
self.CURRDATA = text.strip()
else:
raise TypeError("The parameter must be a string and not empty")
def getTTS(self, text="", lang="en", stype="mp3", filename="google_tts", saveloc=""):
"""
Save Voice from Google TTS as mp3 file.
:rtype : str
:param text: The text to be converted to Speech
:param lang: Language code of the converted speech.
Like en : English, ja : Japanese
:param stype: Speech data to be saved as mp3 or wav. Denotes the extension.
:param filename: File name of the sound with which it will be saved.
:param saveloc: Location where the speech is to be saved.
:return: Saved File location of the Speech.
:raise EmptyParamError: Parameters supplied are erroneous.
"""
self.logger.info("getTTS() Function called.")
if saveloc.strip() == "":
saveloc = os.path.dirname(os.path.realpath(__file__))
self.logger.info("File to be saved in Default location : %s" % saveloc)
elif not os.path.exists(saveloc):
self.logger.error("The path given is not valid or you don't have"
" write permissions")
raise OSError("Exception occur with the supplied file save path."
" See the complete log file")
elif os.path.exists(saveloc) and os.access(saveloc, os.W_OK):
self.logger.info("File to be saved in %s" % saveloc)
if text.strip() == "" and self.CURRDATA == "":
self.logger.error("Exception occured. No Parameter Given or "
"Parameter Invalid.")
raise EmptyParamError()
self.settext(text)
queryParams = {"q": self.CURRDATA, "tl": lang}
queryData = urlencode(queryParams)
self.logger.info("Query Params Encoded %s" % queryData)
self.logger.info("Request GoogleTTS service")
req = Request(self.BASEURL, queryData, headers=self.cons.DEFAULT_HEADERS)
resp = urlopen(req)
self.logger.info("Response received from GoogleTTS service")
try:
saveloc += "/" + filename + "." + stype
filemp3 = open(saveloc, "wb")
self.logger.info("Writing the received response as %s" % (filename + stype))
filemp3.write(resp.read())
filemp3.close()
self.logger.info("File saved at location : %s " % saveloc)
except (OSError, IOError):
self.logger.error("Error while writing to file.")
print("Error! See the log.")
return savelocTest GoogleTTS using the code below :-
Code:
def main():
ins = GoogleTTS()
path = ins.getTTS("Hello, How are you ?. My name is PINN. How can I assist you ?",
"en", filename="Hello")
print("\nFile Saved at location : \n %s" % path)
path = ins.getTTS("Hi! Hack Community, its me Psycho Coder. I love hentai, Do you like it tou ?",
"en", filename="HC-Hello")
print("\nFile Saved at location : \n %s " % path)
path = ins.getTTS("Hi! Hack Community, its me Psycho Coder. I love hentai, Do you like it too ?",
"ja", filename="HC-Hello-Ja")
print("\nFile Saved at location : \n %s " % path)
if __name__ == "__main__":
main()Have a nice day

Thank you,
Sincerely,
Psycho_Coder.
![[Image: OilyCostlyEwe.gif]](http://fat.gfycat.com/OilyCostlyEwe.gif)
![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)
![[Image: T4OUWZ1.png]](http://i.imgur.com/T4OUWZ1.png)