Go to the documentation of this file.00001
00002
00003 import urllib2
00004 import json
00005 import base64
00006 import socket
00007 import traceback
00008 import logging
00009
00010
00011
00012 from rospeex_core.validators import accepts
00013 from rospeex_core.validators import check_language
00014 from rospeex_core.exceptions import ParameterException
00015 from rospeex_core.exceptions import InvalidRequestException
00016 from rospeex_core.exceptions import InvalidResponseException
00017 from rospeex_core.exceptions import SpeechSynthesisException
00018 from rospeex_core.exceptions import RequestTimeoutException
00019 from rospeex_core.ss.client_base import SpeechSynthesisClient
00020
00021
00022 logger = logging.getLogger(__name__)
00023
00024
00025 class SpeechSynthesisClient_NICT(SpeechSynthesisClient):
00026 """ SpeechSynthesisCient_NICT class """
00027 URL = 'http://rospeex.ucri.jgn-x.jp/nauth_json/jsServices/VoiceTraSS'
00028 FORMAT = 'x-wav'
00029 LANGUAGES = ['ja', 'en', 'zh', 'ko']
00030 VOICEFONT_DICT = {
00031 'ja': ['F128', 'F117', '*'],
00032 'en': ['EF007', '*'],
00033 'zh': ['CJF101', '*'],
00034 'ko': ['KF001', '*']
00035 }
00036
00037 def __init__(self):
00038 """ initialize function """
00039 pass
00040
00041 @accepts(message=basestring, language=str, voice_font=str, timeout=int)
00042 def request(self, message, language='ja', voice_font='*', timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
00043 """
00044 Send speech synthesis request to server,
00045 and get speech synthesis result.
00046 @param message: message
00047 @type message: str
00048 @param language: speech synthesis language
00049 @type language: str
00050 @param voice_font: taraget voice font
00051 @type voice_font: str
00052 @param timeout: request timeout time (second)
00053 @type timeout: float
00054 @return: voice data (wav format binary)
00055 @rtype: str
00056 @raise InvalidResponseException:
00057 @raise InvalidRequestException: send invalid request.
00058 @raise InvalidResponseException: server error.
00059 @raise RequestTimeoutException: timeout error.
00060 """
00061 check_language(language, self.LANGUAGES)
00062 self._check_voice_font(voice_font, language)
00063
00064
00065 decorded_data = self._request_tts(message, language, voice_font, timeout)
00066
00067
00068 ret_code = self._check_decorded_data(decorded_data)
00069
00070
00071 voice = None
00072 if ret_code == False:
00073 if decorded_data['error']['faultCode'] == 'Server.userException':
00074 msg = 'the format is not supported.'
00075 raise InvalidResponseException(msg)
00076 msg = 'server response error. msg:%s' % decorded_data['error']
00077 raise InvalidResponseException(msg)
00078 else:
00079 voice = base64.b64decode(decorded_data['result']['audio'])
00080 return voice
00081
00082
00083 def _check_voice_font(self, voice_font, language):
00084 """ check voice font
00085 @param voice_font:
00086 @type voice_font:
00087 @param language:
00088 @type language:
00089 @raise ParameterException
00090 """
00091 if not voice_font in self.VOICEFONT_DICT[language]:
00092 msg = 'invalid voice font [{voice_font}]. Expect: {voice_font_list}'.format(
00093 voice_font=voice_font,
00094 voice_font_list=str(self.VOICEFONT_DICT[language])
00095 )
00096 raise ParameterException(msg)
00097
00098
00099 def _check_decorded_data(self, decorded_data):
00100 """
00101 @param decorded_data:
00102 @type decorded_data:
00103 @return: True to success / False to failture
00104 @rtype: bool
00105 @raise InvalidResponseException:
00106 """
00107
00108 if not decorded_data:
00109 msg = 'invalid server response. response has no data.'
00110 raise InvalidResponseException(msg)
00111
00112 ret_code = False
00113 if decorded_data.has_key('result'):
00114 if decorded_data['result'] is not None:
00115 if decorded_data['result'].has_key('audio'):
00116 ret_code = True
00117 else:
00118 msg = 'invalid server response. response has no audio data.'
00119 raise InvalidResponseException(msg)
00120
00121
00122 if decorded_data.has_key('error'):
00123 if decorded_data['error'] is not None:
00124 if decorded_data['error'].has_key('faultCode'):
00125 ret_code = False
00126 else:
00127 msg = 'invalid server response. response has no faultcode.'
00128 raise InvalidResponseException(msg)
00129
00130 return ret_code
00131
00132
00133 def _request_tts(self, message, language, voice_font, timeout):
00134 """
00135 request tts to NICT server
00136 @param message: message
00137 @type message: str
00138 @param language: speech synthesis language
00139 @type language: str
00140 @param voice_font: taraget voice font
00141 @type voice_font: str
00142 @param timeout: request timeout time (second)
00143 @type timeout: float
00144 @return: voice data (wav format binary)
00145 @rtype: str
00146 @raise InvalidRequestException: send invalid request.
00147 @raise InvalidResponseException: server error.
00148 @raise RequestTimeoutException: timeout error.
00149 """
00150
00151 data = {
00152 'method':'speak',
00153 'params':[
00154 '1.1',
00155 {'language':language,
00156 'text':message,
00157 'voiceType':voice_font,
00158 'audioType':'audio/%s' % self.FORMAT,
00159 'applicationType':'rospeex'
00160 }
00161 ]
00162 }
00163
00164
00165 decorded_data = None
00166 request = urllib2.Request(self.URL)
00167 request.add_header('Content-Type', 'application/json')
00168
00169
00170 try:
00171 response = urllib2.urlopen(request, json.dumps(data), timeout=timeout)
00172 decorded_data = json.loads(response.read())
00173
00174 except urllib2.URLError as err:
00175 if isinstance(err.reason, socket.timeout):
00176 msg = 'request time out. Exception: %s' % str(err)
00177 raise RequestTimeoutException(msg)
00178 msg = 'request url error. Exception: %s' % str(err)
00179 raise InvalidRequestException(msg)
00180
00181 except urllib2.HTTPError as err:
00182 msg = 'http error. %s Exception:%s' % (err.code, err.msg)
00183 raise InvalidResponseException(msg)
00184
00185 except socket.timeout as err:
00186 msg = 'request time out. Exception: %s' % str(err)
00187 raise RequestTimeoutException(msg)
00188
00189 except:
00190 msg = 'unknown exception. Traceback: %s' % traceback.format_exc()
00191 raise SpeechSynthesisException(msg)
00192
00193 return decorded_data
00194