import urllib2
import json
import base64
import httplib
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self)
def onLoad(self):
pass
def onUnload(self):
pass
def onInput_onStart(self, p):
accessToken = self.getAccessToken()
speech_file = str(p)
self.logger.info(p)
try:
cmd = self.baidu_asr(speech_file, accessToken)
self.logger.info(cmd)
except Exception, e:
cmd = ''
self.logger.info(cmd)
res = self.request_tuling(cmd)
self.logger.info(res)
try:
response_dic = json.loads(res, encoding='utf-8')
answer = response_dic['text'].encode('utf-8', 'ignore')
except Exception,e:
self.logger.error(e)
answer = '对不起,没能听清你的话呢'
try:
response_dic = json.loads(res, encoding='utf-8')
special_value1 = response_dic['special_value1']
except Exception,e:
self.logger.error(e)
special_value1 = '0'
try:
response_dic = json.loads(res, encoding='utf-8')
special_value2 = response_dic['special_value2'].encode('utf-8', 'ignore')
except Exception,e:
self.logger.error(e)
special_value2 = ''
self.output([answer, special_value1, special_value2])
def onInput_onStop(self):
self.onUnload()
self.onStopped()
def getAccessToken(self):
ApiKey = 'your_baidu_speech_apikey'
SecretKey = 'your_secret_key'
auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + ApiKey + "&client_secret=" + SecretKey
res = urllib2.urlopen(auth_url)
json_data = res.read()
return json.loads(json_data)['access_token']
def baidu_asr(self, speech_file, access_token):
asr_server = 'http://vop.baidu.com/server_api'
with open(speech_file, 'rb') as f:
speech_data = f.read()
speech_base64=base64.b64encode(speech_data).decode('utf-8')
speech_length=len(speech_data)
data_dict = {'format':'wav', 'rate':16000, 'channel':1, 'cuid':'005056c00008', 'token':access_token, 'lan':'zh', 'speech':speech_base64, 'len':speech_length}
json_data = json.dumps(data_dict)
json_length = len(json_data)
request = urllib2.Request(url=asr_server)
request.add_header("Content-Type", "application/json")
request.add_header("Content-Length", json_length)
fs = urllib2.urlopen(url=request, data=json_data)
result_str = fs.read()
json_resp = json.loads(result_str, encoding='utf-8')
self.logger.info('result_str ' + result_str)
return json_resp['result'][0].encode('utf-8', 'ignore')
def request_tuling(self, cmd):
if not cmd:
return ''
requrl = '/openapi/api?key=your_tuling_apikey&info=%s' % cmd
try:
conn = httplib.HTTPConnection("www.tuling123.com", timeout=5)
conn.request(method="GET", url=requrl)
response = conn.getresponse()
res = response.read()
conn.close()
except Exception,e:
self.logger.error(e)
res = ''
return res