# -*- coding: utf-8 -*- """ 科大讯飞的语音识别API. 外网ip查询:https://ip.51240.com/ voice_name: https://www.xfyun.cn/services/online_tts """ from __future__ import division from ..__load__ import * from base import Base class Baidu(Base): url = 'http://api.xfyun.cn/v1/service/v1/' def __init__(self): super(self.__class__, self).__init__() def setting(self, appid, api_key, voice_name='vecan', **args): self.appid = appid self.api_key = api_key self.voice_name = voice_name def getHeader(self, aue, engineType): curTime = str(int(time.time())) # curTime = '1526542623' if aue = 'raw': param = "{\"aue\":\"" + aue + "\"" + ",\"engine_type\":\"" + engineType + "\"}" else: param = "{\"aue\":\""+aue+"\",\"auf\":\"audio/L16;rate=16000\",\"voice_name\":\"" + self.voice_name + "\",\"engine_type\":\"intp65\"}" Demeter.logger.debug("param:{}".format(param)) paramBase64 = str(base64.b64encode(param.encode('utf-8')), 'utf-8') Demeter.logger.debug("x_param:{}".format(paramBase64)) m2 = hashlib.md5() m2.update((self.api_key + curTime + paramBase64).encode('utf-8')) checkSum = m2.hexdigest() header = { 'X-CurTime': curTime, 'X-Param': paramBase64, 'X-Appid': self.appid, 'X-CheckSum': checkSum, 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', } return header def getBody(self, filepath): binfile = open(filepath, 'rb') data = {'audio': base64.b64encode(binfile.read())} return data def asr(self, fp): URL = self.url + "iat" r = requests.post(URL, headers=self.getHeader('raw', 'sms16k'), data=self.getBody(fp)) res = json.loads(r.content.decode('utf-8')) Demeter.logger.debug(res) if 'code' in res and res['code'] == '0': return self.log(1, res['data']) else: return self.log(2, '') def tts(self, phrase): URL = self.url + "tts" r = requests.post(URL, headers=self.getHeader('lame'), data=self.getBody(phrase)) contentType = r.headers['Content-Type'] if contentType == "audio/mpeg": tmpfile = writeTempFile(r.content, '.mp3') return self.ttsLog(1, tmpfile) else : return self.ttsLog(2, r.text)