1#!/usr/bin/env python
2# -*- encoding: utf-8 -*-
3'''
4@File       :    speech_utils.py
5@Description:    file description
6@Date       :    2021/05/17 11:43:06
7@Author     :    guoliang.wgl
8@version    :    1.0
9'''
10
11import math
12import http
13import json
14import time
15from audio import Player,Snd
16import uos
17
18toneDir = "/sdcard/resource/"
19tonenameSuffix = [".wav", ".mp3"]
20tonenameNumb = ["SYS_TONE_0", "SYS_TONE_1", "SYS_TONE_2", "SYS_TONE_3", "SYS_TONE_4", "SYS_TONE_5", "SYS_TONE_6", "SYS_TONE_7", "SYS_TONE_8", "SYS_TONE_9"]
21tonenameNumb1 = "SYS_TONE_yao"
22tonenameDot = "SYS_TONE_dian"
23tonenameUnit = ["SYS_TONE_MEASURE_WORD_ge", "SYS_TONE_MEASURE_WORD_shi", "SYS_TONE_MEASURE_WORD_bai", "SYS_TONE_MEASURE_WORD_qian"]
24tonenameHunit = ["SYS_TONE_MEASURE_WORD_wan", "SYS_TONE_MEASURE_WORD_yi", "SYS_TONE_MEASURE_WORD_sw", "SYS_TONE_MEASURE_WORD_bw", "SYS_TONE_MEASURE_WORD_qw"]
25
26on_callback = False
27on_download = False
28cb_data = None
29
30
31player = None
32def init_audio():
33    global player
34    Snd.install_codec_driver()
35    Snd.init()
36    player = Player()
37    player.create()
38    player.set_volume(8)
39
40def play(path):
41    global player
42    player.set_source(path)
43    player.start()
44    player.wait_complete()
45
46def playlist(pathlist):
47    for path in pathlist:
48        play('fs:'+path)
49
50    print('********end playlist*******')
51
52def play_voice(data,dir):
53    global toneDir, tonenameSuffix, playlist
54    toneDir = dir
55    format =  data['format']
56    audioResFormat = 0
57    if (format == 'mp3'):
58        audioResFormat = 1
59    speechs =  data['speechs']
60    toneList = []
61
62    for speech in speechs:
63        print(speech)
64        # length = len(speech)
65        if speech.endswith('}') and speech.startswith('{') and (speech[1] == '$'):
66            speech_num = speech.strip('{').strip('$').strip('}')
67            toneList = add_amount(speech_num,toneList,audioResFormat)
68        else:
69            toneList.append(toneDir + speech + tonenameSuffix[audioResFormat])
70        print(toneList)
71    playlist(toneList)
72
73
74
75def add_amount(num_str, toneList, formatFlag):
76    global toneDir,tonenameSuffix,tonenameNumb,tonenameNumb1,tonenameDot,tonenameUnit,tonenameHunit
77    num_f = float(num_str)
78    numb = int(num_f)
79    deci = num_f - numb
80    target = numb
81    subTarget = 0
82    subNumber = None
83    slot = 0
84    factor = 0
85    count = 0
86    prevSlotZero = False
87    hundredMillionExist = False
88    tenThousandExist = False
89
90    if (numb < 0 or numb >= 1000000000000):
91        print('amount overrange')
92        return toneIndex
93
94    if (deci < 0.0001 and deci > 0.0):
95        deci = 0.0001
96
97    i = 2
98    while(i >= 0):
99
100        factor = math.pow(10000,i)
101        if target < factor:
102            i = i -1
103            continue
104        subTarget = int(target / factor)
105        target %= factor
106        if (subTarget == 0):
107            i = i -1
108            continue
109
110
111
112        if (i == 2):
113            hundredMillionExist = True
114        elif (i == 1):
115            tenThousandExist = True
116        subNumber = subTarget
117        prevSlotZero = False
118
119        depth = 3
120        while(depth >= 0):
121            if(subNumber == 0):
122                break
123            factor = math.pow(10, depth)
124            if ((hundredMillionExist == True or tenThousandExist == True) and i == 0):
125                pass
126            elif (hundredMillionExist == True and tenThousandExist == True and depth > 0 and subTarget < factor):
127                pass
128            elif (subTarget < factor):
129                depth = depth - 1
130                continue
131
132            slot = int(subNumber / factor)
133            subNumber %= factor
134            if (slot == 0 and depth == 0):
135                depth = depth - 1
136                continue
137
138            if ((subTarget < 20 and depth == 1) or (slot == 0 and prevSlotZero) or (slot == 0 and depth == 0)):
139                pass
140            else:
141                toneList.append(toneDir + tonenameNumb[slot] + tonenameSuffix[formatFlag])
142                count += 1
143                if (slot == 0 and prevSlotZero == False):
144                    prevSlotZero = True
145                elif (prevSlotZero == True and slot != 0):
146                    prevSlotZero = False
147
148            if (slot > 0 and depth > 0) :
149                toneList.append(toneDir + tonenameUnit[depth] + tonenameSuffix[formatFlag])
150                count += 1
151            depth = depth - 1
152        if (i > 0):
153            toneList.append(toneDir + tonenameHunit[i - 1] + tonenameSuffix[formatFlag])
154            count += 1
155        i = i - 1
156
157    if (count == 0 and numb == 0):
158        toneList.append(toneDir + tonenameNumb[0] + tonenameSuffix[formatFlag])
159    if (deci >= 0.0001) :
160        toneList.append(toneDir + tonenameDot + tonenameSuffix[formatFlag])
161
162        deci ="{:.4f}".format(deci)
163        deci_tmp = str(deci).strip().rstrip('0')
164        deci_str = ''
165        got_dot = False
166        for j in range(len(deci_tmp)):
167            if(got_dot):
168                deci_str = deci_str + deci_tmp[j]
169            elif deci_tmp[j] == '.':
170                got_dot = True
171        deciArray = deci_str
172        for item in deciArray:
173            if (item >= '0' and item <= '9'):
174                toneList.append(toneDir + tonenameNumb[int(item)] + tonenameSuffix[formatFlag])
175    return toneList
176
177
178def download_resource_file(on_request,resDir):
179    global toneDir,on_callback,on_download,cb_data
180    toneDir = resDir
181
182    data = {
183        'url':on_request['url'],
184        'method': 'GET',
185        'headers': {
186            'Accept':'*/*'
187        },
188        'timeout': 30000,
189        'params' : ''
190    }
191    def cb(data):
192        global on_callback,cb_data
193        on_callback = True
194        cb_data = data
195
196    http.request(data,cb)
197
198    while True:
199        if  on_callback:
200            on_callback = False
201            break
202        else:
203            time.sleep(1)
204
205    response = json.loads(cb_data)
206    format = response['format']
207    size = response['size']
208    audio = response['audios'][0]
209    id = audio['id']
210    format = audio['format']
211    path = toneDir +id+'.'+format
212    print('************ begin to download: ' + path)
213    d_data = {
214        'url': audio['url'],
215        'filepath': path
216    }
217
218    def d_cb(data):
219        global on_download
220        on_download = True
221
222    http.download(d_data,d_cb)
223
224    while True:
225        if on_download:
226            on_download = False
227            break
228        else:
229            time.sleep(1)
230    print('download succeed :' + path)
231
232
233