forked from SpeechColab/Leaderboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asr_api.py
executable file
·197 lines (154 loc) · 5.85 KB
/
asr_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/usr/bin/env python3
# coding=utf-8
'''
this test script is based on the official demo release:
https://github.com/Baidu-AIP/speech-demo/rest-api-asr/python/asr_raw.py
'''
import sys
import json
import time
import codecs
IS_PY3 = sys.version_info.major == 3
if IS_PY3:
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.parse import urlencode
timer = time.perf_counter
else:
import urllib2
from urllib2 import urlopen
from urllib2 import Request
from urllib2 import URLError
from urllib import urlencode
if sys.platform == "win32":
timer = time.clock
else:
# On most other platforms the best timer is time.time()
timer = time.time
# authentication
API_KEY = ''
SECRET_KEY = ''
with open('API_KEY', 'r') as f:
API_KEY = f.readline().strip()
with open('SECRET_KEY', 'r') as f:
SECRET_KEY = f.readline().strip()
CUID = '123456PYTHON';
RATE = 16000; # 采样率
## 普通版
## 1537 表示识别普通话,使用输入法模型。
## 1536表示识别普通话,使用搜索模型。
## 根据文档填写PID,选择语言及识别模型
#DEV_PID = 1537;
#ASR_URL = 'http://vop.baidu.com/server_api'
#SCOPE = 'audio_voice_assistant_get' # 有此scope表示有asr能力,没有请在网页里勾选,非常旧的应用可能没有
#测试自训练平台需要打开以下信息, 自训练平台模型上线后,您会看见 第二步:“”获取专属模型参数pid:8001,modelid:1234”,按照这个信息获取 dev_pid=8001,lm_id=1234
# DEV_PID = 8001 ;
# LM_ID = 1234 ;
# 极速版 打开注释的话请填写自己申请的appkey appSecret ,并在网页中开通极速版(开通后可能会收费)
#DEV_PID = 80001
#ASR_URL = 'http://vop.baidu.com/pro_api'
#SCOPE = 'brain_enhanced_asr' # 有此scope表示有asr能力,没有请在网页里开通极速版
DEV_PID = 80001;
ASR_URL = 'http://vop.baidu.com/pro_api'
SCOPE = 'brain_enhanced_asr' # 有此scope表示有asr能力,没有请在网页里勾选,非常旧的应用可能没有
# 忽略scope检查,非常旧的应用可能没有
# SCOPE = False
# 极速版
class DemoError(Exception):
pass
""" TOKEN start """
TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
def fetch_token():
params = {'grant_type': 'client_credentials',
'client_id': API_KEY,
'client_secret': SECRET_KEY}
post_data = urlencode(params)
if (IS_PY3):
post_data = post_data.encode('utf-8')
req = Request(TOKEN_URL, post_data)
try:
f = urlopen(req)
result_str = f.read()
except URLError as err:
print('token http response http code : ' + str(err.code))
result_str = err.read()
if (IS_PY3):
result_str = result_str.decode()
print(result_str)
result = json.loads(result_str)
print(result)
if ('access_token' in result.keys() and 'scope' in result.keys()):
if SCOPE and (not SCOPE in result['scope'].split(' ')): # SCOPE = False 忽略检查
raise DemoError('scope is not correct')
print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))
return result['access_token']
else:
raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')
""" TOKEN end """
if __name__ == '__main__':
if len(sys.argv) != 3:
print("rest_api.py <in_scp> <out_trans>")
exit(-1)
"""
httpHandler = urllib2.HTTPHandler(debuglevel=1)
opener = urllib2.build_opener(httpHandler)
urllib2.install_opener(opener)
"""
token = fetch_token()
SCP = sys.argv[1] # 只支持 pcm/wav/amr 格式,极速版额外支持m4a 格式
TRANS = sys.argv[2] # output result in Kaldi's trans format
FORMAT = 'wav' # 文件后缀只支持 pcm/wav/amr 格式,极速版额外支持m4a 格式
MAX_RETRY = 10
scp_file = codecs.open(SCP, 'r', 'utf8')
trans_file = codecs.open(TRANS, 'w+', 'utf8')
n = 0
for l in scp_file:
l = l.strip()
if l == '':
continue
key, audio = l.split('\t')
sys.stderr.write(str(n) + '\tkey:' + key + '\taudio:' + audio + '\n')
sys.stderr.flush()
speech_data = []
with open(audio, 'rb') as speech_file:
speech_data = speech_file.read()
if len(speech_data) == 0:
continue
params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}
#测试自训练平台需要打开以下信息
#params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}
params_query = urlencode(params);
headers = {
'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),
'Content-Length': len(speech_data)
}
url = ASR_URL + "?" + params_query
req = Request(ASR_URL + "?" + params_query, speech_data, headers)
time.sleep(0.55) # baidu API calling limitation: 2 qps for free
for i in range(MAX_RETRY): # retry
try:
time1 = timer()
f = urlopen(req)
resp = f.read()
time2 = timer()
sys.stderr.write("Request time cost: %f\n" % (time2 - time1))
break
except:
sys.stderr.write('Request failed, will retry.\n')
time.sleep(1)
continue
if (IS_PY3):
resp = str(resp, 'utf-8')
sys.stderr.write('Response: ' + resp + '\n')
rec_text = ''
if resp:
try:
rec_text = json.loads(resp)['result'][0].strip()
except:
pass
trans_file.write(key + '\t' + rec_text + '\n')
trans_file.flush()
n+=1
scp_file.close()
trans_file.close()