dolphinvoice 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dolphinvoice/__init__.py +5 -0
- dolphinvoice/speech_rec/__init__.py +14 -0
- dolphinvoice/speech_rec/_client.py +99 -0
- dolphinvoice/speech_rec/_log.py +28 -0
- dolphinvoice/speech_rec/_speech.py +104 -0
- dolphinvoice/speech_rec/_speech_asrfile.py +75 -0
- dolphinvoice/speech_rec/_speech_control.py +122 -0
- dolphinvoice/speech_rec/_speech_recognizer.py +215 -0
- dolphinvoice/speech_rec/_speech_transcriber.py +231 -0
- dolphinvoice/speech_rec/_token.py +63 -0
- dolphinvoice/speech_rec/_utils.py +73 -0
- dolphinvoice/speech_rec/callbacks.py +175 -0
- dolphinvoice/speech_rec/parameters.py +114 -0
- dolphinvoice/speech_syn/__init__.py +14 -0
- dolphinvoice/speech_syn/_client.py +83 -0
- dolphinvoice/speech_syn/_log.py +28 -0
- dolphinvoice/speech_syn/_speech.py +89 -0
- dolphinvoice/speech_syn/_speech_control.py +90 -0
- dolphinvoice/speech_syn/_speech_synthesizer.py +187 -0
- dolphinvoice/speech_syn/_token.py +63 -0
- dolphinvoice/speech_syn/_utils.py +54 -0
- dolphinvoice/speech_syn/callbacks.py +135 -0
- dolphinvoice/speech_syn/parameters.py +129 -0
- dolphinvoice-1.0.0.dist-info/METADATA +245 -0
- dolphinvoice-1.0.0.dist-info/RECORD +28 -0
- dolphinvoice-1.0.0.dist-info/WHEEL +5 -0
- dolphinvoice-1.0.0.dist-info/licenses/LICENSE +202 -0
- dolphinvoice-1.0.0.dist-info/top_level.txt +1 -0
dolphinvoice/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""
|
|
2
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
3
|
+
* you may not use this file except in compliance with the License.
|
|
4
|
+
* You may obtain a copy of the License at
|
|
5
|
+
*
|
|
6
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
*
|
|
8
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
10
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
* See the License for the specific language governing permissions and
|
|
12
|
+
* limitations under the License.
|
|
13
|
+
"""
|
|
14
|
+
from dolphinvoice.speech_rec._client import SpeechClient
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
"""
|
|
16
|
+
import time
|
|
17
|
+
import websocket
|
|
18
|
+
import os
|
|
19
|
+
from cryptography.fernet import Fernet
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
import thread
|
|
23
|
+
except ImportError:
|
|
24
|
+
import _thread as thread
|
|
25
|
+
from dolphinvoice.speech_rec._log import _log
|
|
26
|
+
from dolphinvoice.speech_rec._token import Token
|
|
27
|
+
from dolphinvoice.speech_rec._speech_recognizer import SpeechRecognizer
|
|
28
|
+
from dolphinvoice.speech_rec._speech_transcriber import SpeechTranscriber
|
|
29
|
+
from dolphinvoice.speech_rec._utils import utils
|
|
30
|
+
from dolphinvoice.speech_rec._speech_asrfile import SpeechASRFile
|
|
31
|
+
__all__ = ["SpeechClient"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SpeechClient(utils):
|
|
35
|
+
|
|
36
|
+
def __init__(self, app_id=None, app_secret=None, url=None, url_token=None):
|
|
37
|
+
super().__init__()
|
|
38
|
+
websocket.enableTrace(False)
|
|
39
|
+
|
|
40
|
+
self.donation = 'wss://api.voice.dolphin-ai.jp/v1/asr/ws' if not url else url
|
|
41
|
+
self.url_token = url_token
|
|
42
|
+
|
|
43
|
+
self.app_id = app_id
|
|
44
|
+
self.app_secret = app_secret
|
|
45
|
+
assert self.app_id and self.app_secret, "Please check app_id, app_secret"
|
|
46
|
+
self.token = self.update_token()
|
|
47
|
+
assert self.token, "Please check app_id, app_secret"
|
|
48
|
+
|
|
49
|
+
@staticmethod
|
|
50
|
+
def set_log_level(level):
|
|
51
|
+
_log.setLevel(level)
|
|
52
|
+
|
|
53
|
+
def update_token(self):
|
|
54
|
+
token = None
|
|
55
|
+
token_file = ".token"
|
|
56
|
+
extime = 7
|
|
57
|
+
new_time = time.time()
|
|
58
|
+
if not os.path.exists(token_file):
|
|
59
|
+
token = self.get_token(self.app_id, self.app_secret, token_file)
|
|
60
|
+
with open(token_file, "r", encoding="utf-8") as fr:
|
|
61
|
+
token_info = eval(fr.read())
|
|
62
|
+
old_time = token_info['time']
|
|
63
|
+
token = token_info['token']
|
|
64
|
+
|
|
65
|
+
if not token or new_time - old_time > 60 * 60 * 24 * (extime - 1):
|
|
66
|
+
token = self.get_token(self.app_id, self.app_secret, token_file)
|
|
67
|
+
|
|
68
|
+
return token
|
|
69
|
+
|
|
70
|
+
def get_token(self, app_id, app_secret, token_file):
|
|
71
|
+
token = Token.get_token(app_id, app_secret, self.url_token)
|
|
72
|
+
with open(token_file, "w", encoding="utf-8") as fd:
|
|
73
|
+
fd.write(str({"token": token[0], "time": time.time()}))
|
|
74
|
+
return token
|
|
75
|
+
|
|
76
|
+
def create_recognizer(self, callback, url=None):
|
|
77
|
+
if url:
|
|
78
|
+
recognizer = SpeechRecognizer(callback, url)
|
|
79
|
+
else:
|
|
80
|
+
recognizer = SpeechRecognizer(callback, self.donation)
|
|
81
|
+
self.token = self.update_token()
|
|
82
|
+
recognizer.set_app_id(self.app_id)
|
|
83
|
+
recognizer.set_token(self.token)
|
|
84
|
+
return recognizer
|
|
85
|
+
|
|
86
|
+
def create_transcriber(self, callback, url=None):
|
|
87
|
+
if url:
|
|
88
|
+
transcriber = SpeechTranscriber(callback, url)
|
|
89
|
+
else:
|
|
90
|
+
transcriber = SpeechTranscriber(callback, self.donation)
|
|
91
|
+
self.token = self.update_token()
|
|
92
|
+
transcriber.set_app_id(self.app_id)
|
|
93
|
+
transcriber.set_token(self.token)
|
|
94
|
+
return transcriber
|
|
95
|
+
|
|
96
|
+
def create_asrfile(self, asr_file_upload_url=None, asr_file_result_url=None):
|
|
97
|
+
self.token = self.update_token()
|
|
98
|
+
asrfile = SpeechASRFile(self.token, asr_file_upload_url=asr_file_upload_url, asr_file_result_url=asr_file_result_url)
|
|
99
|
+
return asrfile
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# -*- coding:utf-8 -*-
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import logging.handlers
|
|
18
|
+
|
|
19
|
+
__all__ = ['_log']
|
|
20
|
+
|
|
21
|
+
FORMAT = '%(asctime)15s %(name)s-%(levelname)s %(funcName)s:%(lineno)s %(message)s'
|
|
22
|
+
_log = logging.getLogger('speech')
|
|
23
|
+
|
|
24
|
+
handler = logging.handlers.RotatingFileHandler('speech_rec.log', maxBytes=1024 * 1024,
|
|
25
|
+
backupCount=5, encoding='utf-8')
|
|
26
|
+
handler.setLevel(logging.DEBUG)
|
|
27
|
+
handler.setFormatter(logging.Formatter(FORMAT))
|
|
28
|
+
_log.addHandler(handler)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import platform
|
|
19
|
+
from dolphinvoice.speech_rec.parameters import Parameters
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Speech:
|
|
23
|
+
def __init__(self, callback, url):
|
|
24
|
+
self._header = {}
|
|
25
|
+
self._context = {}
|
|
26
|
+
self._payload = {}
|
|
27
|
+
self._environment = {}
|
|
28
|
+
self._token = None
|
|
29
|
+
self._app_id = None
|
|
30
|
+
self._url = url
|
|
31
|
+
self._callback = callback
|
|
32
|
+
self._status = Parameters.STATUS_INIT
|
|
33
|
+
self._ws = None
|
|
34
|
+
self._thread = None
|
|
35
|
+
self._task_id = None
|
|
36
|
+
|
|
37
|
+
def set_app_id(self, app_id):
|
|
38
|
+
self._app_id = app_id
|
|
39
|
+
|
|
40
|
+
def get_app_id(self):
|
|
41
|
+
return self._app_id
|
|
42
|
+
|
|
43
|
+
def set_token(self, token):
|
|
44
|
+
self._token = token
|
|
45
|
+
|
|
46
|
+
def get_token(self):
|
|
47
|
+
return self._token
|
|
48
|
+
|
|
49
|
+
def set_format(self, format):
|
|
50
|
+
self._payload[Parameters.PAYLOAD_KEY_FORMAT] = format
|
|
51
|
+
|
|
52
|
+
def get_format(self):
|
|
53
|
+
return self._payload[Parameters.PAYLOAD_KEY_FORMAT]
|
|
54
|
+
|
|
55
|
+
def set_sample_rate(self, sample_rate):
|
|
56
|
+
self._payload[Parameters.PAYLOAD_KEY_SAMPLE_RATE] = sample_rate
|
|
57
|
+
|
|
58
|
+
def set_audio_url(self,audio_url):
|
|
59
|
+
self._payload[Parameters.PAYLOAD_KEY_AUDIO_URL] = audio_url
|
|
60
|
+
|
|
61
|
+
def get_audio_url(self):
|
|
62
|
+
return self._payload[Parameters.PAYLOAD_KEY_AUDIO_URL]
|
|
63
|
+
|
|
64
|
+
def set_audio_field(self,field):
|
|
65
|
+
self._payload[Parameters.PAYLOAD_KEY_FIELD] = field
|
|
66
|
+
|
|
67
|
+
def set_enable_save_log(self,flag=False):
|
|
68
|
+
self._payload[Parameters.PAYLOAD_KEY_ENABLE_SAVE_LOG] = flag
|
|
69
|
+
|
|
70
|
+
def get_audio_field(self):
|
|
71
|
+
return self._payload[Parameters.PAYLOAD_KEY_FIELD]
|
|
72
|
+
|
|
73
|
+
def set_lang_type(self, lang_type):
|
|
74
|
+
self._payload[Parameters.PAYLOAD_KEY_LANG_TYPE] = lang_type
|
|
75
|
+
|
|
76
|
+
def get_lang_type(self):
|
|
77
|
+
return self._payload[Parameters.PAYLOAD_KEY_LANG_TYPE]
|
|
78
|
+
|
|
79
|
+
def get_sample_rate(self):
|
|
80
|
+
return self._payload[Parameters.PAYLOAD_KEY_SAMPLE_RATE]
|
|
81
|
+
|
|
82
|
+
def get_task_id(self):
|
|
83
|
+
return self._header[Parameters.HEADER_KEY_TASK_ID]
|
|
84
|
+
|
|
85
|
+
def add_payload_param(self, key, obj):
|
|
86
|
+
self._payload[key] = obj
|
|
87
|
+
|
|
88
|
+
def get_status(self):
|
|
89
|
+
return self._status
|
|
90
|
+
|
|
91
|
+
def set_speaker_id(self, data, **kwargs):
|
|
92
|
+
if kwargs:
|
|
93
|
+
kwargs[Parameters.PAYLOAD_KEY_SPEAKER_ID] = data
|
|
94
|
+
self._payload = kwargs
|
|
95
|
+
else:
|
|
96
|
+
self._payload[Parameters.PAYLOAD_KEY_SPEAKER_ID] = data
|
|
97
|
+
|
|
98
|
+
def serialize(self):
|
|
99
|
+
root = {Parameters.HEADER: self._header}
|
|
100
|
+
|
|
101
|
+
if len(self._payload) != 0:
|
|
102
|
+
root[Parameters.PAYLOAD] = self._payload
|
|
103
|
+
|
|
104
|
+
return json.dumps(root)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
import json
|
|
5
|
+
import traceback
|
|
6
|
+
import requests
|
|
7
|
+
from dolphinvoice.speech_rec._log import _log
|
|
8
|
+
from dolphinvoice.speech_rec.parameters import Parameters
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SpeechASRFile():
|
|
12
|
+
|
|
13
|
+
def __init__(self, token, vip=False, asr_file_upload_url=None, asr_file_result_url=None):
|
|
14
|
+
|
|
15
|
+
if asr_file_upload_url:
|
|
16
|
+
self.asr_file_upload_url = asr_file_upload_url
|
|
17
|
+
else:
|
|
18
|
+
self.asr_file_upload_url = 'https://api.voice.dolphin-ai.jp/v1/asrfile/upload'
|
|
19
|
+
|
|
20
|
+
if asr_file_result_url:
|
|
21
|
+
self.asr_file_result_url = asr_file_result_url
|
|
22
|
+
else:
|
|
23
|
+
self.asr_file_result_url = 'https://api.voice.dolphin-ai.jp/v1/asrfile/result'
|
|
24
|
+
|
|
25
|
+
if vip:
|
|
26
|
+
self.asr_file_upload_url = self.asr_file_upload_url + '/vip'
|
|
27
|
+
|
|
28
|
+
self.token = token
|
|
29
|
+
|
|
30
|
+
def transcribe_file(self, audio, data):
|
|
31
|
+
try:
|
|
32
|
+
url = self.asr_file_upload_url
|
|
33
|
+
header={Parameters.HEADER_KEY_Authorization: "Bearer {}".format(self.token)}
|
|
34
|
+
|
|
35
|
+
retry_count = 1
|
|
36
|
+
while retry_count:
|
|
37
|
+
try:
|
|
38
|
+
files=[('file', (f'{audio}', open(audio,'rb'),'audio/wav'))]
|
|
39
|
+
response = requests.post(url=url, files=files, data=data, headers=header)
|
|
40
|
+
break
|
|
41
|
+
except:
|
|
42
|
+
retry_count -= 1
|
|
43
|
+
traceback.print_exc()
|
|
44
|
+
time.sleep(1)
|
|
45
|
+
_log.debug(f'response: {response.content}')
|
|
46
|
+
res = response.json()
|
|
47
|
+
_log.debug(f'res: {res}')
|
|
48
|
+
|
|
49
|
+
task_id = res['data']['task_id']
|
|
50
|
+
get_task_id_url = f"{self.asr_file_result_url}?task_id={task_id}"
|
|
51
|
+
|
|
52
|
+
while True:
|
|
53
|
+
# 获取结果
|
|
54
|
+
try:
|
|
55
|
+
res = requests.get(get_task_id_url).json()
|
|
56
|
+
except:
|
|
57
|
+
traceback.print_exc()
|
|
58
|
+
time.sleep(1)
|
|
59
|
+
continue
|
|
60
|
+
|
|
61
|
+
_log.debug(f'res: {res}')
|
|
62
|
+
|
|
63
|
+
if 'desc' in res['data'] and res['data']['desc'] == 'Failed':
|
|
64
|
+
_log.info(f'{res}')
|
|
65
|
+
return res
|
|
66
|
+
if 'statistics' in res['data'] and 'finish_time' in res['data']['statistics'] and res['data']['statistics']['finish_time']:
|
|
67
|
+
return res
|
|
68
|
+
else:
|
|
69
|
+
time.sleep(1)
|
|
70
|
+
|
|
71
|
+
return {}
|
|
72
|
+
except:
|
|
73
|
+
traceback.print_exc()
|
|
74
|
+
return {}
|
|
75
|
+
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*software
|
|
10
|
+
* Unless required by applicable law or agreed to in writing,
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import websocket
|
|
18
|
+
from dolphinvoice.speech_rec._log import _log
|
|
19
|
+
from dolphinvoice.speech_rec.parameters import Parameters
|
|
20
|
+
from dolphinvoice.speech_rec._speech import Speech
|
|
21
|
+
from dolphinvoice.speech_rec.parameters import DefaultParameters
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SpeechControl(Speech):
|
|
25
|
+
|
|
26
|
+
def __init__(self, callback, url):
|
|
27
|
+
super(SpeechControl, self).__init__(callback, url)
|
|
28
|
+
self._last_start_retry = False
|
|
29
|
+
self._connected = False
|
|
30
|
+
self._header[Parameters.HEADER_KEY_NAMESPACE] = None
|
|
31
|
+
# self._payload[Parameters.PAYLOAD_KEY_FORMAT] = DefaultParameters.MP3
|
|
32
|
+
# self._payload[Parameters.PAYLOAD_KEY_SAMPLE_RATE] = DefaultParameters.SAMPLE_RATE_16K
|
|
33
|
+
|
|
34
|
+
def set_parameter(self, data):
|
|
35
|
+
self._payload.update(data)
|
|
36
|
+
|
|
37
|
+
def set_enable_intermediate_result(self, data):
|
|
38
|
+
self._payload[Parameters.PAYLOAD_KEY_ENABLE_INTERMEDIATE_RESULT] = data
|
|
39
|
+
|
|
40
|
+
def set_enable_punctuation_prediction(self, data):
|
|
41
|
+
self._payload[Parameters.PAYLOAD_KEY_ENABLE_PUNCTUATION_PREDICTION] = data
|
|
42
|
+
|
|
43
|
+
def set_enable_inverse_text_normalization(self, data):
|
|
44
|
+
self._payload[Parameters.PAYLOAD_KEY_ENABLE_ITN] = data
|
|
45
|
+
|
|
46
|
+
def set_user_id(self,data):
|
|
47
|
+
self._payload[Parameters.PAYLOAD_KEY_USER_ID] = data
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def set_customization_id(self, data):
|
|
51
|
+
self._payload[Parameters.PAYLOAD_KEY_CUSTOMIZATION_ID] = data
|
|
52
|
+
|
|
53
|
+
def set_audio_url(self, data):
|
|
54
|
+
self._payload['audio_url'] = data
|
|
55
|
+
|
|
56
|
+
def set_vocabulary_id(self, data):
|
|
57
|
+
self._payload[Parameters.PAYLOAD_KEY_VOCABULARY_ID] = data
|
|
58
|
+
|
|
59
|
+
def set_enable_save_log(self, flag=False):
|
|
60
|
+
self._payload[Parameters.PAYLOAD_KEY_ENABLE_SAVE_LOG] = flag
|
|
61
|
+
|
|
62
|
+
def set_max_sentence_silence(self, max_sentence_silence):
|
|
63
|
+
self._payload[Parameters.PAYLOAD_KEY_MAX_SENTENCE_SILENCE] = max_sentence_silence
|
|
64
|
+
|
|
65
|
+
def set_speaker_id(self, data, **kwargs):
|
|
66
|
+
if kwargs:
|
|
67
|
+
kwargs[Parameters.PAYLOAD_KEY_SPEAKER_ID] = data
|
|
68
|
+
self._payload = kwargs
|
|
69
|
+
else:
|
|
70
|
+
self._payload[Parameters.PAYLOAD_KEY_SPEAKER_ID] = data
|
|
71
|
+
|
|
72
|
+
def get_speaker_id(self):
|
|
73
|
+
self._header[Parameters.HEADER_KEY_NAME] = Parameters.HEADER_VALUE_SPEAKER_START
|
|
74
|
+
return {Parameters.HEADER: self._header, Parameters.PAYLOAD: self._payload}
|
|
75
|
+
|
|
76
|
+
def set_mandatory_clause(self, data):
|
|
77
|
+
if data:
|
|
78
|
+
self._header[Parameters.HEADER_KEY_NAMESPACE] = Parameters.HEADER_VALUE_TRANS_NAMESPACE
|
|
79
|
+
self._header[Parameters.HEADER_KEY_NAME] = Parameters.HEADER_VALUE_TRANS_NAME_SENTENCE_END
|
|
80
|
+
else:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
def get_mandatory_clause(self, ):
|
|
84
|
+
return self._header
|
|
85
|
+
|
|
86
|
+
def start(self):
|
|
87
|
+
"""
|
|
88
|
+
Start to identify and create a new connection to the server
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def send(self, data, is_BINARY=True):
|
|
92
|
+
|
|
93
|
+
"""
|
|
94
|
+
Send voice data to the server. It is recommended to send 1000-8000 bytes each time
|
|
95
|
+
:param data: Binary audio data
|
|
96
|
+
:return: Send successfully, return 0
|
|
97
|
+
Send failed, return - 1
|
|
98
|
+
"""
|
|
99
|
+
if self._status == Parameters.STATUS_STARTED:
|
|
100
|
+
if is_BINARY:
|
|
101
|
+
self._ws.send(data, opcode=websocket.ABNF.OPCODE_BINARY)
|
|
102
|
+
else:
|
|
103
|
+
self._ws.send(data, opcode=websocket.ABNF.OPCODE_TEXT)
|
|
104
|
+
return 0
|
|
105
|
+
else:
|
|
106
|
+
_log.error('should not send data in state %d', self._status)
|
|
107
|
+
return -1
|
|
108
|
+
|
|
109
|
+
def close(self):
|
|
110
|
+
"""
|
|
111
|
+
Close websocket
|
|
112
|
+
"""
|
|
113
|
+
if self._ws:
|
|
114
|
+
if self._thread and self._thread.is_alive():
|
|
115
|
+
self._ws.keep_running = False
|
|
116
|
+
self._thread.join()
|
|
117
|
+
self._ws.close()
|
|
118
|
+
|
|
119
|
+
def stop(self):
|
|
120
|
+
"""
|
|
121
|
+
End identification and close the connection with the server
|
|
122
|
+
"""
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
"""
|
|
16
|
+
import json
|
|
17
|
+
import ssl
|
|
18
|
+
import platform
|
|
19
|
+
|
|
20
|
+
import six
|
|
21
|
+
import websocket
|
|
22
|
+
import uuid
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
from dolphinvoice.speech_rec._log import _log
|
|
26
|
+
from dolphinvoice.speech_rec.parameters import Parameters
|
|
27
|
+
from dolphinvoice.speech_rec._speech_control import SpeechControl
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SpeechRecognizer(SpeechControl):
|
|
31
|
+
|
|
32
|
+
def __init__(self, callback, url):
|
|
33
|
+
super(SpeechRecognizer, self).__init__(callback, url)
|
|
34
|
+
self._header[Parameters.HEADER_KEY_NAMESPACE] = Parameters.HEADER_VALUE_ASR_NAMESPACE
|
|
35
|
+
|
|
36
|
+
def __enter__(self):
|
|
37
|
+
return self
|
|
38
|
+
|
|
39
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
40
|
+
self.close()
|
|
41
|
+
|
|
42
|
+
def start(self, ping_interval=3, ping_timeout=2, retry_count=5):
|
|
43
|
+
"""
|
|
44
|
+
Start to identify and create a new connection to the server
|
|
45
|
+
:param retry_count: Try to connect retry_count times
|
|
46
|
+
:param ping_interval: Automatically send ping command, specify the sending interval, in seconds
|
|
47
|
+
:param ping_timeout: Timeout in seconds for waiting to receive a Pong message
|
|
48
|
+
:return: Successfully established connection with server, return 0
|
|
49
|
+
Failed to establish connection with server, return - 1
|
|
50
|
+
"""
|
|
51
|
+
if self._status == Parameters.STATUS_INIT:
|
|
52
|
+
_log.debug('starting recognizer...')
|
|
53
|
+
self._status = Parameters.STATUS_STARTING
|
|
54
|
+
else:
|
|
55
|
+
_log.error("Illegal status: %s" % self._status)
|
|
56
|
+
return -1
|
|
57
|
+
|
|
58
|
+
# Parameters required to connect to websocket
|
|
59
|
+
def _open(ws):
|
|
60
|
+
_log.debug('websocket connected')
|
|
61
|
+
self._status = Parameters.STATUS_CONNECTED
|
|
62
|
+
self._is_connected = True
|
|
63
|
+
msg_id = six.u(uuid.uuid1().hex)
|
|
64
|
+
self._task_id = six.u(uuid.uuid1().hex)
|
|
65
|
+
self._header[Parameters.HEADER_KEY_NAME] = Parameters.HEADER_VALUE_ASR_NAME_START
|
|
66
|
+
self._header[Parameters.HEADER_KEY_MESSAGE_ID] = msg_id
|
|
67
|
+
self._header[Parameters.HEADER_KEY_TASK_ID] = self._task_id
|
|
68
|
+
send_text = self.serialize()
|
|
69
|
+
_log.info('sending start cmd: ' + send_text)
|
|
70
|
+
ws.send(send_text)
|
|
71
|
+
|
|
72
|
+
def _message(ws, res):
|
|
73
|
+
_log.debug('websocket message received: ' + res)
|
|
74
|
+
res = json.loads(res)
|
|
75
|
+
data = res[Parameters.HEADER][Parameters.HEADER_KEY_NAME]
|
|
76
|
+
if data == 'Warning':
|
|
77
|
+
warning_info = \
|
|
78
|
+
f"Warning\t{Parameters.HEADER_KEY_TASK_ID}:{res[Parameters.HEADER][Parameters.HEADER_KEY_TASK_ID]}\t" \
|
|
79
|
+
f"{Parameters.HEADER_KEY_STATUS}:{res[Parameters.HEADER][Parameters.HEADER_KEY_STATUS]}\t" \
|
|
80
|
+
f"{Parameters.HEADER_KEY_STATUS_TEXT}:{res[Parameters.HEADER][Parameters.HEADER_KEY_STATUS_TEXT]}"
|
|
81
|
+
_log.warning(res)
|
|
82
|
+
warning_info = f"\033[33m{warning_info}\033[0m"
|
|
83
|
+
self._callback.warning_info(warning_info)
|
|
84
|
+
elif data == 'Error':
|
|
85
|
+
error_msg = f"Error\t{Parameters.HEADER_KEY_TASK_ID}:{res[Parameters.HEADER][Parameters.HEADER_KEY_TASK_ID]}\t" \
|
|
86
|
+
f"{Parameters.HEADER_KEY_STATUS}:{res[Parameters.HEADER][Parameters.HEADER_KEY_STATUS]}\t" \
|
|
87
|
+
f"{Parameters.HEADER_KEY_STATUS_TEXT}:{res[Parameters.HEADER][Parameters.HEADER_KEY_STATUS_TEXT]}"
|
|
88
|
+
self._callback.task_failed(f"\033[31m{error_msg}\033[0m")
|
|
89
|
+
_log.error(error_msg)
|
|
90
|
+
exit()
|
|
91
|
+
elif data == Parameters.HEADER_VALUE_ASR_NAME_STARTED:
|
|
92
|
+
self._status = Parameters.STATUS_STARTED
|
|
93
|
+
_log.debug('callback started')
|
|
94
|
+
self._callback.started(res)
|
|
95
|
+
elif data == Parameters.HEADER_VALUE_ASR_NAME_RESULT_CHANGED:
|
|
96
|
+
_log.debug('callback result_changed')
|
|
97
|
+
self._callback.result_changed(res)
|
|
98
|
+
elif data == Parameters.HEADER_VALUE_ASR_NAME_COMPLETED:
|
|
99
|
+
if self._status == Parameters.STATUS_STOPPING:
|
|
100
|
+
# The completed event returned from the client's active call to stop
|
|
101
|
+
self._status = Parameters.STATUS_STOPPED
|
|
102
|
+
else:
|
|
103
|
+
# Enable VAD and the completed event returned by the server
|
|
104
|
+
self._status = Parameters.STATUS_COMPLETED
|
|
105
|
+
_log.debug('websocket status changed to stopped')
|
|
106
|
+
_log.debug('callback completed')
|
|
107
|
+
self._callback.completed(res)
|
|
108
|
+
self._ws.close()
|
|
109
|
+
elif data == Parameters.HEADER_VALUE_NAME_TASK_FAILED:
|
|
110
|
+
self._status = Parameters.STATUS_STOPPED
|
|
111
|
+
_log.error(res)
|
|
112
|
+
_log.debug('websocket status changed to stopped')
|
|
113
|
+
_log.debug('callback task_failed')
|
|
114
|
+
self._callback.task_failed(res)
|
|
115
|
+
exit()
|
|
116
|
+
|
|
117
|
+
def _error(ws, error):
|
|
118
|
+
if self._connected or self._last_start_retry:
|
|
119
|
+
_log.error(error)
|
|
120
|
+
self._status = Parameters.STATUS_STOPPED
|
|
121
|
+
message = json.loads('{"header":{"namespace":"Default","name":"TaskFailed",'
|
|
122
|
+
'"status":400,"message_id":"0","task_id":"0",'
|
|
123
|
+
'"status_text":"%s"}}'
|
|
124
|
+
% error)
|
|
125
|
+
if eval(str(error)) is not None:
|
|
126
|
+
self._callback.task_failed(f"\033[31m{message}\033[0m")
|
|
127
|
+
exit()
|
|
128
|
+
else:
|
|
129
|
+
_log.warning('retry start: %s' % error)
|
|
130
|
+
|
|
131
|
+
def _close(ws, *args):
|
|
132
|
+
_log.debug('callback channel_closed')
|
|
133
|
+
self._callback.channel_closed()
|
|
134
|
+
|
|
135
|
+
for count in range(retry_count):
|
|
136
|
+
self._status = Parameters.STATUS_STARTING
|
|
137
|
+
if count == (retry_count - 1):
|
|
138
|
+
self._last_start_retry = True
|
|
139
|
+
|
|
140
|
+
# Init WebSocket
|
|
141
|
+
self._ws = websocket.WebSocketApp(self._url,
|
|
142
|
+
on_open=_open,
|
|
143
|
+
on_message=_message,
|
|
144
|
+
on_error=_error,
|
|
145
|
+
on_close=_close,
|
|
146
|
+
header={Parameters.HEADER_KEY_Authorization: "Bearer {}".format(self.get_token()),
|
|
147
|
+
Parameters.CONTEXT_SDK_KEY_VERSION: Parameters.CONTEXT_SDK_VALUE_VERSION,
|
|
148
|
+
Parameters.CONTEXT_SDK_KEY_OS: platform.system(),
|
|
149
|
+
Parameters.CONTEXT_SDK_KEY: Parameters.CONTEXT_SDK_VALUE_NAME_LANG,
|
|
150
|
+
})
|
|
151
|
+
# Init Thread
|
|
152
|
+
self._thread = threading.Thread(target=self._ws.run_forever,
|
|
153
|
+
# {"cert_reqs": ssl.CERT_NONE}
|
|
154
|
+
# None, None, ping_interval, ping_timeout
|
|
155
|
+
args=(None, None, None, None))
|
|
156
|
+
self._thread.daemon = True
|
|
157
|
+
self._thread.start()
|
|
158
|
+
# waite for no more than 10 seconds
|
|
159
|
+
for i in range(1000):
|
|
160
|
+
if self._status == Parameters.STATUS_STARTED or self._status == Parameters.STATUS_STOPPED:
|
|
161
|
+
break
|
|
162
|
+
else:
|
|
163
|
+
time.sleep(0.01)
|
|
164
|
+
|
|
165
|
+
if self._status == Parameters.STATUS_STARTED:
|
|
166
|
+
# Successfully established the connection with the server
|
|
167
|
+
print("Successfully established the connection with the server")
|
|
168
|
+
_log.debug('start succeed!')
|
|
169
|
+
return 0
|
|
170
|
+
else:
|
|
171
|
+
if self._connected or self._last_start_retry:
|
|
172
|
+
# If the websocket link has been established but the connection with the server fails,
|
|
173
|
+
# or the last retry, a - 1 will be returned
|
|
174
|
+
print("Websocket link established but failed to connect with server")
|
|
175
|
+
_log.error("start failed, status: %s" % self._status)
|
|
176
|
+
return -1
|
|
177
|
+
else:
|
|
178
|
+
# Try to reconnect
|
|
179
|
+
print("Try to reconnect")
|
|
180
|
+
continue
|
|
181
|
+
|
|
182
|
+
def stop(self):
|
|
183
|
+
"""
|
|
184
|
+
End identification and close the connection with the server
|
|
185
|
+
:return: Closed successfully, return 0
|
|
186
|
+
Closed failed, return - 1
|
|
187
|
+
"""
|
|
188
|
+
ret = 0
|
|
189
|
+
if self._status == Parameters.STATUS_COMPLETED:
|
|
190
|
+
ret = 0
|
|
191
|
+
elif self._status == Parameters.STATUS_STARTED:
|
|
192
|
+
self._status = Parameters.STATUS_STOPPING
|
|
193
|
+
msg_id = six.u(uuid.uuid1().hex)
|
|
194
|
+
self._header[Parameters.HEADER_KEY_NAME] = Parameters.HEADER_VALUE_ASR_NAME_STOP
|
|
195
|
+
self._header[Parameters.HEADER_KEY_MESSAGE_ID] = msg_id
|
|
196
|
+
self._payload.clear()
|
|
197
|
+
send_text = self.serialize()
|
|
198
|
+
_log.info('sending stop cmd: ' + send_text)
|
|
199
|
+
self._ws.send(send_text)
|
|
200
|
+
while True:
|
|
201
|
+
if self._status == Parameters.STATUS_STOPPED:
|
|
202
|
+
break
|
|
203
|
+
else:
|
|
204
|
+
time.sleep(0.1)
|
|
205
|
+
_log.debug('waite 100ms')
|
|
206
|
+
if self._status != Parameters.STATUS_STOPPED:
|
|
207
|
+
ret = -1
|
|
208
|
+
else:
|
|
209
|
+
ret = 0
|
|
210
|
+
else:
|
|
211
|
+
_log.error('should not stop in state %d', self._status)
|
|
212
|
+
ret = -1
|
|
213
|
+
return ret
|
|
214
|
+
|
|
215
|
+
|