import json
import tkinter as tk
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.parse import quote_plus
from tkinter import ttk
from playsound import playsound
from EP import *

API_KEY = '百度应用的API_KEY'# 替换你的 API_KEY
SECRET_KEY = '百度应用的SECRET_KEY'# 替换你的 SECRET_KEY

TTS_URL = 'http://tsn.baidu.com/text2audio'
TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
角色表={'度小宇':1, '度小美': 0, '度逍遥': 3, '度丫丫': 4, '度博文': 106, '度小童':110 , '度小萌':111 , '度米朵':103 , '度小娇':5}

class PyWinDesign:
    def __init__(self, 启动窗口):
        self.启动窗口 = 启动窗口
        self.启动窗口.title('【小强】私人翻译官')
        self.启动窗口.resizable(width=False, height=False)
        screenwidth = self.启动窗口.winfo_screenwidth()
        screenheight = self.启动窗口.winfo_screenheight()
        size = '%dx%d+%d+%d' % (305, 137, (screenwidth - 305) / 2, (screenheight - 137) / 2)
        self.启动窗口.geometry(size)

        self.标签1_标题 = tk.StringVar()
        self.标签1_标题.set('内容')
        self.标签1 = tk.Label(self.启动窗口, textvariable=self.标签1_标题, anchor=tk.E)
        self.标签1.place(x=12, y=10, width=35, height=24)

        self.标签2_标题 = tk.StringVar()
        self.标签2_标题.set('语速')
        self.标签2 = tk.Label(self.启动窗口, textvariable=self.标签2_标题, anchor=tk.E)
        self.标签2.place(x=14, y=70, width=35, height=24)

        self.标签3_标题 = tk.StringVar()
        self.标签3_标题.set('音调')
        self.标签3 = tk.Label(self.启动窗口, textvariable=self.标签3_标题, anchor=tk.E)
        self.标签3.place(x=102, y=70, width=35, height=24)

        self.标签4_标题 = tk.StringVar()
        self.标签4_标题.set('音量')
        self.标签4 = tk.Label(self.启动窗口, textvariable=self.标签4_标题, anchor=tk.E)
        self.标签4.place(x=192, y=70, width=35, height=24)

        self.编辑框1_内容 = tk.StringVar()
        self.编辑框1_内容.set('3')
        self.编辑框1 = ttk.Entry(self.启动窗口, textvariable=self.编辑框1_内容, justify=tk.LEFT)
        self.编辑框1.place(x=51, y=71, width=51, height=22)

        self.编辑框2_内容 = tk.StringVar()
        self.编辑框2_内容.set('5')
        self.编辑框2 = ttk.Entry(self.启动窗口, textvariable=self.编辑框2_内容, justify=tk.LEFT)
        self.编辑框2.place(x=139, y=71, width=51, height=22)

        self.编辑框3_内容 = tk.StringVar()
        self.编辑框3_内容.set('5')
        self.编辑框3 = ttk.Entry(self.启动窗口, textvariable=self.编辑框3_内容, justify=tk.LEFT)
        self.编辑框3.place(x=231, y=71, width=51, height=22)

        self.编辑框4 = tk.Text(self.启动窗口, wrap=tk.NONE)
        self.编辑框4.insert(tk.END, '')
        self.编辑框4.place(x=51, y=15, width=233, height=43)

        self.按钮1_标题 = tk.StringVar()
        self.按钮1_标题.set('开始朗读')
        self.按钮1 = ttk.Button(self.启动窗口, textvariable=self.按钮1_标题, command=self.按钮1_被鼠标左键单击)
        self.按钮1.place(x=175, y=101, width=109, height=25)

        self.标签5_标题 = tk.StringVar()
        self.标签5_标题.set('角色')
        self.标签5 = tk.Label(self.启动窗口, textvariable=self.标签5_标题, anchor=tk.E)
        self.标签5.place(x=14, y=101, width=35, height=24)

        self.组合框1 = ttk.Combobox(self.启动窗口, values=('度小宇', '度小美', '度逍遥', '度丫丫', '度博文', '度小童', '度小萌', '度米朵', '度小娇'),
                                 state='readonly')
        self.组合框1.current(0)
        self.组合框1.place(x=51, y=103, width=100, height=20)

    def 按钮1_被鼠标左键单击(self):
        str = self.编辑框4.get(1.0, tk.END)
        列表 = 文件_遍历指定路径文件('./rec/')
        if 加密_MD5(str)+'.mp3' in 列表:
            playsound('./rec/{}.mp3'.format(加密_MD5(str)))  # 播放
            return
        token = self.fetch_token()
        tex = quote_plus(str)  # 此处TEXT需要两次urlencode
        params = {'tok': token, 'tex': tex, 'cuid': "quickstart",
                  'lan': 'zh', 'ctp': 1, 'spd': int(self.编辑框1_内容.get()), 'pit': int(self.编辑框2_内容.get()), 'vol': int(self.编辑框3_内容.get()),'per':角色表[self.组合框1.get()]}  # lan ctp 固定参数 spd是语速0-15 pit音调 vol音量

        data = urlencode(params)
        req = Request(TTS_URL, data.encode('utf-8'))
        has_error = False
        try:
            f = urlopen(req)
            result_str = f.read()

            headers = dict((name.lower(), value) for name, value in f.headers.items())

            has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)
        except  URLError as err:
            print('http response http code : ' + str(err.code))
            result_str = err.read()
            has_error = True

        save_file = "error.txt" if has_error else './rec/{}.mp3'.format(加密_MD5(str))
        目录, 文件 = 文件_目录文件名分割(save_file)
        if 目录 != '' and os.path.exists(目录) is False:
            os.makedirs(目录)

        with open(save_file, 'wb') as of:
            of.write(result_str)
        if has_error:
            result_str = str(result_str, 'utf-8')
            print("tts api  error:" + result_str)
        print("file saved as : " + save_file)
        playsound('./rec/{}.mp3'.format(加密_MD5(str)))#播放



    def fetch_token(self):
        params = {'grant_type': 'client_credentials',
                  'client_id': API_KEY,
                  'client_secret': SECRET_KEY}
        post_data = urlencode(params)
        post_data = post_data.encode('utf-8')
        req = Request(TOKEN_URL, post_data)
        try:
            f = urlopen(req, timeout=5)
            result_str = f.read()
        except URLError as err:
            print('token http response http code : ' + str(err.code))
            result_str = err.read()

        result_str = result_str.decode()

        result = json.loads(result_str)

        if ('access_token' in result.keys() and 'scope' in result.keys()):
            if not 'audio_tts_post' in result['scope'].split(' '):
                print('please ensure has check the tts ability')
                exit()
            return result['access_token']
        else:
            print('please overwrite the correct API_KEY and SECRET_KEY')
            exit()


if __name__ == '__main__':
    root = tk.Tk()
    app = PyWinDesign(root)
    root.mainloop()
