# -*- coding: utf-8 -*-
"""
腾讯API
"""
from __future__ import division
from ..__load__ import *
from .base import Base

class Tencent(Base):

	def __init__(self):
		super(self.__class__, self).__init__(True)

	def setting(self, appid, secret_id, secret_key, region='ap-guangzhou', voiceType=0, language=1, **args):
		self.engine = self.sdk.init(secret_id, secret_key)
		self.region = region
		self.voiceType = voiceType
		self.language = language

	def asr(self, fp):
		file = convertMp3ToWav(fp)
		r = self.engine.ASR(file, 'mp3', '1', self.region)
		File.remove(file)
		res = json.loads(r)
		print(file)
		print(res)
		if 'Response' in res and 'Result' in res['Response']:
			return self.asrLog(1, res['Response']['Result'])
		else:
			return self.asrLog(2, '')

	"""
	腾讯的语音合成
	region: 服务地域，挑个离自己最近的区域有助于提升速度。
		有效值：https://cloud.tencent.com/document/api/441/17365#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
	voiceType:
		- 0：女声1，亲和风格(默认)
		- 1：男声1，成熟风格
		- 2：男声2，成熟风格
	language:
		- 1: 中文，最大100个汉字（标点符号算一个汉子）
		- 2: 英文，最大支持400个字母（标点符号算一个字母）
	"""
	def tts(self, phrase):
		result = self.engine.TTS(phrase, self.voiceType, self.language, self.region)
		if 'Response' in result and 'Audio' in result['Response']:
			audio = result['Response']['Audio']
			data = base64.b64decode(audio)
			tmpfile = writeTempFile(data, '.mp3')
			return self.ttsLog(1, tmpfile)
		else:
			return self.ttsLog(2, '')