google.py
Go to the documentation of this file.
00001 # -*- coding: utf-8 -*-
00002 
00003 # import python libraries
00004 import urllib
00005 import urllib2
00006 import socket
00007 import subprocess
00008 import traceback
00009 from distutils import spawn
00010 
00011 # import local library
00012 from rospeex_core import logging_util
00013 from rospeex_core import exceptions as ext
00014 from rospeex_core.validators import accepts
00015 from rospeex_core.validators import check_language
00016 from rospeex_core.ss.base import IClient
00017 from rospeex_core.ss import nict
00018 
00019 
00020 logger = logging_util.get_logger(__name__)
00021 
00022 
00023 class Client(IClient):
00024     """ SpeechSynthesisCient_Google class """
00025     LANGUAGES = ['ja', 'en', '*']
00026 
00027     def __init__(self):
00028         """ init function """
00029         self.URL = 'http://translate.google.com/translate_tts'
00030 
00031     @accepts(message=basestring, language=str, voice_font=str, timeout=int)
00032     def request(
00033         self,
00034         message,
00035         language='ja',
00036         voice_font='',
00037         timeout=socket._GLOBAL_DEFAULT_TIMEOUT
00038     ):
00039         """
00040         Send speech synthesis request to server,
00041         and get speech synthesis result.
00042         @param message: message
00043         @type  message: str
00044         @param language: speech synthesis language
00045         @type  language: str
00046         @param voice_font: taraget voice font
00047         @type  voice_font: str
00048         @param timeout: request timeout time (second)
00049         @type  timeout: float
00050         @return: voice data (wav format binary)
00051         @rtype: str
00052         @raise SpeechSynthesisException:
00053         """
00054         check_language(language, self.LANGUAGES)
00055 
00056         query = {
00057             'ie': 'UTF-8',
00058             'client': 't',
00059             'tl': language,
00060             'q': message.encode('utf-8'),
00061             'total': 1,
00062             'idx': 0,
00063             'textlen': len(message)
00064         }
00065 
00066         headers = {
00067             'User-Agent': 'stagefright/1.2 (Linux;Android 5.0)'
00068         }
00069 
00070         try:
00071             client = nict.Client()
00072             client.request(message, language, voice_font, 10)
00073         except:
00074             pass
00075 
00076         voice = None
00077         try:
00078             query_data = urllib.urlencode(query)
00079             request_url = '%s?%s' % (self.URL, query_data)
00080             request = urllib2.Request(request_url, None, headers)
00081             response = urllib2.urlopen(request)
00082             voice = response.read()
00083 
00084         except urllib2.URLError as err:
00085             if isinstance(err.reason, socket.timeout):
00086                 msg = 'request time out. Exception: %s' % str(err)
00087                 raise ext.RequestTimeoutException(msg)
00088             msg = 'request url error. Exception: %s' % str(err)
00089             raise ext.InvalidRequestException(msg)
00090 
00091         except urllib2.HTTPError as err:
00092             msg = 'http error. %s Exception:%s' % (err.code, err.msg)
00093             raise ext.InvalidResponseException(msg)
00094 
00095         except socket.timeout as err:
00096             msg = 'request time out. Exception: %s' % str(err)
00097             raise ext.RequestTimeoutException(msg)
00098 
00099         except:
00100             msg = 'unknown exception. Traceback: %s' % traceback.format_exc()
00101             raise ext.SpeechSynthesisException(msg)
00102 
00103         conv_voice = self._convert_mp3_to_wav(voice)
00104         return conv_voice
00105 
00106     def _convert_mp3_to_wav(self, data):
00107         """
00108         convert mp3 to waf file
00109         @param data: mp3 binary data
00110         @type  data: str
00111         @return: wav binary data
00112         @rtype: str
00113         @raises SpeechSynthesisException:
00114         """
00115         # convert wav to flac data
00116         convert_app = None
00117         check_ffmpeg = spawn.find_executable('ffmpeg')
00118         check_avconv = spawn.find_executable('avconv')
00119         if check_ffmpeg is not None:
00120             convert_app = 'ffmpeg'
00121 
00122         elif check_avconv is not None:
00123             convert_app = 'avconv'
00124 
00125         else:
00126             msg = 'audio converter application(ffpmeg / avconv) is not found.'
00127             raise ext.SpeechSynthesisException(msg)
00128 
00129         try:
00130             # get convert application name
00131             input_file_name = 'ss_tmp.mp3'
00132             output_file_name = 'ss_tmp.wav'
00133 
00134             fo = open(input_file_name, 'wb')
00135             fo.write(data)
00136             fo.close()
00137 
00138             subprocess.check_output(
00139                 [convert_app, '-y', '-i', input_file_name, output_file_name],
00140                 stderr=subprocess.STDOUT
00141             )
00142 
00143             fi = open(output_file_name, 'rb')
00144             data = fi.read()
00145             fi.close()
00146 
00147         except IOError as err:
00148             msg = 'file io error. Exception:%s' % str(err)
00149             raise ext.SpeechSynthesisException(msg)
00150 
00151         except subprocess.CalledProcessError as err:
00152             msg = '%s returns error value. Exception:%s' % (
00153                 convert_app,
00154                 str(err)
00155             )
00156             raise ext.SpeechSynthesisException(msg)
00157 
00158         except:
00159             msg = 'unknown exception. Traceback: %s' % traceback.format_exc()
00160             raise ext.SpeechSynthesisException(msg)
00161 
00162         return data


rospeex_core
Author(s): Komei Sugiura
autogenerated on Thu Jun 6 2019 18:53:10