diff --git a/README.md b/README.md new file mode 100644 index 0000000..6b1af2e --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ +# Caps Writer + +### 简介 + +一款语音输入工具,后台运行脚本后,按下大写锁定键超过 0.3 秒后,开始语音识别,松开按键之后,自动输入识别结果。 + +### 描述 + +本工具(Caps Writer)是一个电脑端的语音输入工具,使用了阿里云的一句话识别 api + +(有兴趣的可以改成百度、腾讯、讯飞的 api 试试)。 + +使用方法很简单:用 python 运行 `run.py` 后,按下 `Caps Lock`(也就是大写锁定键)超过 0.3 秒后,就会开始用阿里云的 api 进行语音识别,松开按键后,会将识别结果自动输入。 + +对于聊天时候进行快捷输入、写代码时快速加入中文注释非常的方便。 + +### 视频演示 + +请到 HacPai 帖子中进行查看: + +### 安装使用 + +本工具是一个python脚本,依赖于以下模块: + +- keyboard +- pyaudio +- configparser +- aliyunsdkcore +- alibabacloud-nls-python-sdk + +其中: + +- pyaudio 在 windows 上不是太好安装,可以先到 [这个链接](https://www.lfd.uci.edu/~gohlke/pythonlibs) 下载 pyaudio 对应版本的 whl 文件,再用 pip 安装 +- alibabacloud-nls-python-sdk 不是通过 python 安装,而是通过 [阿里云官方文档的方法](https://help.aliyun.com/document_detail/120693.html) 进行安装。 + +另外,需要在 `run.py` 中填入阿里云拥有 **管理智能语音交互(NLS)** 权限的 **RAM访问控制** 用户的 **accessID**、**accessKey** 和智能语音交互语音识别项目的 **appkey** 。 + +做完以上步骤后,只要运行 `run.py` 就可以用了! + +本文件夹内有一个 `安装指南` 文件夹,在里面可以找到详细的安装指南,还包括了提前下载的 alibabacloud-nls-python-sdk 和 pyaudio 的 whl 文件。 + +### 后话 + +因为作者就是本着凑合能用就可以了的心态做这个工具的,所以图形界面什么的也没做,整个工具单纯就一个脚本,功能也就一个,按住大写锁定键开始语音识别,松开后输入结果。目前作者本人已经很满意。 + +欢迎有想法有能力的人将这个工具加以改进,比如加入讯飞、腾讯、百度的语音识别api,长按0.3秒后开始识别时加一个提示等等等等。 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..71cf397 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +setuptools +pyaudio +keyboard +aliyunsdkcore +configparser \ No newline at end of file diff --git a/run.py b/run.py new file mode 100644 index 0000000..3db8878 --- /dev/null +++ b/run.py @@ -0,0 +1,191 @@ +import json +import os +import pyaudio +import threading +import keyboard + +import time +import ali_speech +from ali_speech.callbacks import SpeechRecognizerCallback +from ali_speech.constant import ASRFormat +from ali_speech.constant import ASRSampleRate + +from aliyunsdkcore.client import AcsClient +from aliyunsdkcore.request import CommonRequest +import configparser + +""" 在这里填写你的 API 设置 """ +accessID = "xxxxxxxxxxxxxxxxxxxxxxxx" +accessKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +appkey = 'xxxxxxxxxxxxxxxx' + + +"""pyaudio参数""" +CHUNK = 1024 # 数据包或者数据片段 +FORMAT = pyaudio.paInt16 # pyaudio.paInt16表示我们使用量化位数 16位来进行录音 +CHANNELS = 1 # 声道,1为单声道,2为双声道 +RATE = 16000 # 采样率,每秒钟16000次 + +count = 1 # 计数 +pre = True # 是否准备开始录音 +run = False # 控制录音是否停止 + + +class MyCallback(SpeechRecognizerCallback): + """ + 构造函数的参数没有要求,可根据需要设置添加 + 示例中的name参数可作为待识别的音频文件名,用于在多线程中进行区分 + """ + def __init__(self, name='default'): + self._name = name + def on_started(self, message): + #print('MyCallback.OnRecognitionStarted: %s' % message) + pass + def on_result_changed(self, message): + print('任务信息: task_id: %s, result: %s' % ( + message['header']['task_id'], message['payload']['result'])) + def on_completed(self, message): + print('结果: %s' % ( + message['payload']['result'])) + result = message['payload']['result'] + if result[-1] == '。': # 如果最后一个符号是句号,就去掉。 + result = result[0:-1] + keyboard.write(result) # 输入识别结果 + keyboard.press_and_release('caps lock') # 再按下大写锁定键,还原大写锁定 + def on_task_failed(self, message): + print('MyCallback.OnRecognitionTaskFailed: %s' % message) + def on_channel_closed(self): + # print('MyCallback.OnRecognitionChannelClosed') + pass + +def get_token(): + if not os.path.exists('token.ini'): + init_id = """[Token] +id = 0000000000000000000 +expiretime = 0000000000""" + fp = open("token.ini",'w') + fp.write(init_id) + fp.close() + + config = configparser.ConfigParser() + config.read_file(open('token.ini')) + token = config.get("Token","Id") + expireTime = config.get("Token","ExpireTime") + # 要是 token 还有 5 秒过期,那就重新获得一个。 + if (int(expireTime) - time.time()) < 5 : + # 创建AcsClient实例 + global accessID, accessKey + client = AcsClient( + accessID, # 填写 AccessID + accessKey, # 填写 AccessKey + "cn-shanghai" + ); + # 创建request,并设置参数 + request = CommonRequest() + request.set_method('POST') + request.set_domain('nls-meta.cn-shanghai.aliyuncs.com') + request.set_version('2019-02-28') + request.set_action_name('CreateToken') + response = json.loads(client.do_action_with_exception(request)) + token = response['Token']['Id'] + expireTime = str(response['Token']['ExpireTime']) + config.set('Token', 'Id', token) + config.set('Token', 'ExpireTime', expireTime) + config.write(open("token.ini", "w")) + print + return token + +def get_recognizer(client, appkey): + token = get_token() + audio_name = 'none' + callback = MyCallback(audio_name) + recognizer = client.create_recognizer(callback) + recognizer.set_appkey(appkey) + recognizer.set_token(token) + recognizer.set_format(ASRFormat.PCM) + recognizer.set_sample_rate(ASRSampleRate.SAMPLE_RATE_16K) + recognizer.set_enable_intermediate_result(False) + recognizer.set_enable_punctuation_prediction(True) + recognizer.set_enable_inverse_text_normalization(True) + return(recognizer) + +# 因为关闭 recognizer 有点慢,就须做成一个函数,用多线程关闭它。 +def close_recognizer(): + global recognizer + recognizer.close() + +# 处理热键响应 +def on_hotkey(event): + global pre, run + if event.event_type == "down": + if pre and (not run): + pre = False + run = True + threading.Thread(target=process).start() + else: + pass + else: + pre, run = True, False + +# 处理是否开始录音 +def process(): + global run + # 等待 6 轮 0.05 秒,如果 run 还是 True,就代表还没有松开大写键,是在长按状态,那么就可以开始识别。 + for i in range(6): + if run: + time.sleep(0.05) + else: + return + global count, recognizer, p, appkey + threading.Thread(target=recoder,args=(recognizer, p)).start() # 开始录音识别 + count += 1 + recognizer = get_recognizer(client, appkey) # 为下一次监听提前准备好 recognizer + +# 录音识别处理 +def recoder(recognizer, p): + global run + try: + stream = p.open(channels=CHANNELS, + format=FORMAT, + rate=RATE, + input=True, + frames_per_buffer=CHUNK) + print('\r{}//:在听了,说完了请松开 CapsLock 键...'.format(count), end=' ') + ret = recognizer.start() + if ret < 0: + return ret + while run: + data = stream.read(CHUNK) + ret = recognizer.send(data) + if ret < 0: + break + recognizer.stop() + stream.stop_stream() + stream.close() + # p.terminate() + except Exception as e: + print(e) + finally: + threading.Thread(target=close_recognizer).start() # 关闭 recognizer + print('{}//:按住 CapsLock 键 0.3 秒后开始说话...'.format(count), end=' ') + + + +if __name__ == '__main__': + + print('开始程序') + + client = ali_speech.NlsClient() + client.set_log_level('WARNING') # 设置 client 输出日志信息的级别:DEBUG、INFO、WARNING、ERROR + + recognizer = get_recognizer(client, appkey) + p = pyaudio.PyAudio() + + keyboard.hook_key('caps lock', on_hotkey) + print('{}//:按住 CapsLock 键 0.3 秒后开始说话...'.format(count), end=' ') + keyboard.wait() + + + + + \ No newline at end of file diff --git a/安装指南/PyAudio-0.2.11-cp36-cp36m-win32.whl b/安装指南/PyAudio-0.2.11-cp36-cp36m-win32.whl new file mode 100644 index 0000000..ed3c43a Binary files /dev/null and b/安装指南/PyAudio-0.2.11-cp36-cp36m-win32.whl differ diff --git a/安装指南/PyAudio-0.2.11-cp36-cp36m-win_amd64.whl b/安装指南/PyAudio-0.2.11-cp36-cp36m-win_amd64.whl new file mode 100644 index 0000000..2a66233 Binary files /dev/null and b/安装指南/PyAudio-0.2.11-cp36-cp36m-win_amd64.whl differ diff --git a/安装指南/PyAudio-0.2.11-cp37-cp37m-win32.whl b/安装指南/PyAudio-0.2.11-cp37-cp37m-win32.whl new file mode 100644 index 0000000..4e46e87 Binary files /dev/null and b/安装指南/PyAudio-0.2.11-cp37-cp37m-win32.whl differ diff --git a/安装指南/PyAudio-0.2.11-cp37-cp37m-win_amd64.whl b/安装指南/PyAudio-0.2.11-cp37-cp37m-win_amd64.whl new file mode 100644 index 0000000..6f6588f Binary files /dev/null and b/安装指南/PyAudio-0.2.11-cp37-cp37m-win_amd64.whl differ diff --git a/安装指南/PyAudio-0.2.11-cp38-cp38-win32.whl b/安装指南/PyAudio-0.2.11-cp38-cp38-win32.whl new file mode 100644 index 0000000..3f547f2 Binary files /dev/null and b/安装指南/PyAudio-0.2.11-cp38-cp38-win32.whl differ diff --git a/安装指南/PyAudio-0.2.11-cp38-cp38-win_amd64.whl b/安装指南/PyAudio-0.2.11-cp38-cp38-win_amd64.whl new file mode 100644 index 0000000..ebdd57a Binary files /dev/null and b/安装指南/PyAudio-0.2.11-cp38-cp38-win_amd64.whl differ diff --git a/安装指南/PyAudio-0.2.11-cp39-cp39-win32.whl b/安装指南/PyAudio-0.2.11-cp39-cp39-win32.whl new file mode 100644 index 0000000..13a1695 Binary files /dev/null and b/安装指南/PyAudio-0.2.11-cp39-cp39-win32.whl differ diff --git a/安装指南/PyAudio-0.2.11-cp39-cp39-win_amd64.whl b/安装指南/PyAudio-0.2.11-cp39-cp39-win_amd64.whl new file mode 100644 index 0000000..bc32d44 Binary files /dev/null and b/安装指南/PyAudio-0.2.11-cp39-cp39-win_amd64.whl differ diff --git a/安装指南/alibabacloud-nls-python-sdk/LICENSE b/安装指南/alibabacloud-nls-python-sdk/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/安装指南/alibabacloud-nls-python-sdk/NOTICE b/安装指南/alibabacloud-nls-python-sdk/NOTICE new file mode 100644 index 0000000..0927292 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/NOTICE @@ -0,0 +1,38 @@ +The following notices pertain to this software license. + + +==================================================================== +==================================================================== +websocket-client + +Copyright 2018 Hiroki Ohtani. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +==================================================================== +==================================================================== +requests + +Copyright 2018 Kenneth Reitz + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/安装指南/alibabacloud-nls-python-sdk/README.rst b/安装指南/alibabacloud-nls-python-sdk/README.rst new file mode 100644 index 0000000..1e5b546 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/README.rst @@ -0,0 +1,51 @@ +============================ +alibabacloud-nls-java-sdk +============================ + +概述 +----- + +这是阿里巴巴智能语音交互2.0服务的Python SDK。 +支持的服务:获取Token、一句话识别、实时语音识别、语音合成。 + +运行环境 +-------- + +Python3.4及以上 + +.. note:: + + 暂不支持Python2 + + +安全方法 +-------- + +请确认已安装Python包管理工具setuptools,如果没有安装,请安装: + +.. code-block:: bash + + $ pip install setuptools + + +请在SDK目录执行以下命令: + +.. code-block:: bash + + # 打包 + $ python setup.py bdist_egg + # 安装 + $ python setup.py install + + +.. note:: + + 以上的pip、python命令是对应的Python3。 + + +接口说明 +-------- + +- `一句话识别Python SDK说明 `_ +- `实时语音识别Python SDK说明 `_ +- `语音合成Python SDK说明 `_ \ No newline at end of file diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/__init__.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/__init__.py new file mode 100644 index 0000000..4d2d663 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/__init__.py @@ -0,0 +1,19 @@ +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +from ali_speech._client import NlsClient + +__version__ = "0.1.0" diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/_client.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_client.py new file mode 100644 index 0000000..45b02bb --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_client.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import websocket + +try: + import thread +except ImportError: + import _thread as thread + +from ali_speech._logging import _log +from ali_speech._create_token import AccessToken +from ali_speech._speech_recognizer import SpeechRecognizer +from ali_speech._speech_transcriber import SpeechTranscriber +from ali_speech._speech_synthesizer import SpeechSynthesizer + +__all__ = ["NlsClient"] + + +class NlsClient: + URL_GATEWAY = 'wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1' + + def __init__(self): + websocket.enableTrace(False) + + @staticmethod + def set_log_level(level): + _log.setLevel(level) + + @staticmethod + def create_token(access_key_id, access_key_secret): + return AccessToken.create_token(access_key_id, access_key_secret) + + def create_recognizer(self, callback, gateway_url=URL_GATEWAY): + request = SpeechRecognizer(callback, gateway_url) + return request + + def create_transcriber(self, callback, gateway_url=URL_GATEWAY): + transcriber = SpeechTranscriber(callback, gateway_url) + return transcriber + + def create_synthesizer(self, callback, gateway_url=URL_GATEWAY): + synthesizer = SpeechSynthesizer(callback, gateway_url) + return synthesizer diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/_constant.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_constant.py new file mode 100644 index 0000000..ca8387a --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_constant.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + + +class Status: + # 初始状态 + STATUS_INIT = 1 + # websocker 网络连接建立成功,on_open + STATUS_WS_CONNECTED = 2 + # 与gateway服务建立连接中 + STATUS_STARTING = 3 + # 与服务建立连接成功,on_message RecognitionStarted + STATUS_STARTED = 4 + # 客户端正主动断开连接 + STATUS_STOPPING = 5 + # 与服务已断开连接 + STATUS_STOPPED = 6 + # 开启VAD,服务主动返回completed事件 + STATUS_COMPLETED_WITH_OUT_STOP = 7 + + +class Constant: + CONTEXT = 'context' + CONTEXT_SDK_KEY = 'sdk' + CONTEXT_SDK_KEY_NAME = 'name' + CONTEXT_SDK_VALUE_NAME = 'nls-sdk-python' + CONTEXT_SDK_KEY_VERSION = 'version' + CONTEXT_SDK_VALUE_VERSION = '2.0.1' + + HEADER_TOKEN = 'X-NLS-Token' + + HEADER = 'header' + HEADER_KEY_NAMESPACE = 'namespace' + HEADER_KEY_NAME = 'name' + HEADER_KEY_MESSAGE_ID = 'message_id' + HEADER_KEY_APPKEY = 'appkey' + HEADER_KEY_TASK_ID = 'task_id' + HEADER_KEY_STATUS = 'status' + HEADER_KEY_STATUS_TEXT = 'status_text' + + PAYLOAD = 'payload' + PAYLOAD_KEY_SAMPLE_RATE = 'sample_rate' + PAYLOAD_KEY_FORMAT = 'format' + PAYLOAD_KEY_ENABLE_ITN = 'enable_inverse_text_normalization' + PAYLOAD_KEY_ENABLE_INTERMEDIATE_RESULT = 'enable_intermediate_result' + PAYLOAD_KEY_ENABLE_PUNCTUATION_PREDICTION = 'enable_punctuation_prediction' + + PAYLOAD_KEY_VOICE = 'voice' + PAYLOAD_KEY_TEXT = 'text' + PAYLOAD_KEY_VOLUME = 'volume' + PAYLOAD_KEY_SPEECH_RATE = 'speech_rate' + PAYLOAD_KEY_PITCH_RATE = 'pitch_rate' + + HEADER_VALUE_ASR_NAMESPACE = 'SpeechRecognizer' + HEADER_VALUE_ASR_NAME_START = 'StartRecognition' + HEADER_VALUE_ASR_NAME_STOP = 'StopRecognition' + HEADER_VALUE_ASR_NAME_STARTED = 'RecognitionStarted' + HEADER_VALUE_ASR_NAME_RESULT_CHANGED = 'RecognitionResultChanged' + HEADER_VALUE_ASR_NAME_COMPLETED = 'RecognitionCompleted' + + HEADER_VALUE_NAME_TASK_FAILED = 'TaskFailed' + + HEADER_VALUE_TRANS_NAMESPACE = 'SpeechTranscriber' + HEADER_VALUE_TRANS_NAME_START = 'StartTranscription' + HEADER_VALUE_TRANS_NAME_STOP = 'StopTranscription' + HEADER_VALUE_TRANS_NAME_STARTED = 'TranscriptionStarted' + HEADER_VALUE_TRANS_NAME_SENTENCE_BEGIN = 'SentenceBegin' + HEADER_VALUE_TRANS_NAME_SENTENCE_END = 'SentenceEnd' + HEADER_VALUE_TRANS_NAME_RESULT_CHANGE = 'TranscriptionResultChanged' + HEADER_VALUE_TRANS_NAME_COMPLETED = 'TranscriptionCompleted' + + HEADER_VALUE_TTS_NAMESPACE = 'SpeechSynthesizer' + HEADER_VALUE_TTS_NAME_START = 'StartSynthesis' + HEADER_VALUE_TTS_NAME_COMPLETED = 'SynthesisCompleted' + diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/_create_token.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_create_token.py new file mode 100644 index 0000000..d7c9a79 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_create_token.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import base64 +import hashlib +import hmac +import requests +import time +import uuid + +from urllib import parse +from ali_speech._logging import _log + + +class AccessToken: + @staticmethod + def _encode_text(text): + encoded_text = parse.quote_plus(text) + return encoded_text.replace('+', '%20').replace('*', '%2A').replace('%7E', '~') + + @staticmethod + def _encode_dict(dic): + keys = dic.keys() + dic_sorted = [(key, dic[key]) for key in sorted(keys)] + encoded_text = parse.urlencode(dic_sorted) + return encoded_text.replace('+', '%20').replace('*', '%2A').replace('%7E', '~') + + @staticmethod + def create_token(access_key_id, access_key_secret): + parameters = {'AccessKeyId': access_key_id, + 'Action': 'CreateToken', + 'Format': 'JSON', + 'RegionId': 'cn-shanghai', + 'SignatureMethod': 'HMAC-SHA1', + 'SignatureNonce': str(uuid.uuid1()), + 'SignatureVersion': '1.0', + 'Timestamp': time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + 'Version': '2019-02-28'} + # 构造规范化的请求字符串 + query_string = AccessToken._encode_dict(parameters) + _log.debug('规范化的请求字符串: %s' % query_string) + # 构造待签名字符串 + string_to_sign = 'GET' + '&' + AccessToken._encode_text('/') + '&' + AccessToken._encode_text(query_string) + _log.debug('待签名的字符串: %s' % string_to_sign) + # 计算签名 + secreted_string = hmac.new(bytes(access_key_secret + '&', encoding='utf-8'), + bytes(string_to_sign, encoding='utf-8'), + hashlib.sha1).digest() + signature = base64.b64encode(secreted_string) + _log.debug('签名: %s' % signature) + # 进行URL编码 + signature = AccessToken._encode_text(signature) + _log.debug('URL编码后的签名: %s' % signature) + # 调用服务 + full_url = 'http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s' % (signature, query_string) + _log.debug('url: %s' % full_url) + # 提交HTTP GET请求 + response = requests.get(full_url) + if response.ok: + root_obj = response.json() + key = 'Token' + if key in root_obj: + token = root_obj[key]['Id'] + expire_time = root_obj[key]['ExpireTime'] + return token, expire_time + + _log.error(response.text) + return None, None + + diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/_logging.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_logging.py new file mode 100644 index 0000000..a16d9cb --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_logging.py @@ -0,0 +1,31 @@ +# -*- coding:utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import logging.handlers + +__all__ = ['_log'] + +FORMAT = '%(asctime)15s %(name)s-%(levelname)s %(funcName)s:%(lineno)s %(message)s' +logging.basicConfig(level=logging.DEBUG, format=FORMAT) +_log = logging.getLogger('alispeech') + +handler = logging.handlers.RotatingFileHandler('alispeech.log', maxBytes=1024 * 1024, + backupCount=5, encoding='utf-8') +handler.setLevel(logging.DEBUG) +handler.setFormatter(logging.Formatter(FORMAT)) +_log.addHandler(handler) diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_recognizer.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_recognizer.py new file mode 100644 index 0000000..08889a3 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_recognizer.py @@ -0,0 +1,227 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import json +import six +import websocket +import uuid +import threading +import time + +from ali_speech._logging import _log +from ali_speech._constant import Status +from ali_speech._constant import Constant +from ali_speech._speech_reqprotocol import SpeechReqProtocol + + +class SpeechRecognizer(SpeechReqProtocol): + + def __init__(self, callback, url): + super(SpeechRecognizer, self).__init__(callback, url) + self._last_start_retry = False + self._is_connected = False + + self._header[Constant.HEADER_KEY_NAMESPACE] = Constant.HEADER_VALUE_ASR_NAMESPACE + self._payload[Constant.PAYLOAD_KEY_FORMAT] = "pcm" + self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] = 16000 + + def set_enable_intermediate_result(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_INTERMEDIATE_RESULT] = flag + + def set_enable_punctuation_prediction(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_PUNCTUATION_PREDICTION] = flag + + def set_enable_inverse_text_normalization(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_ITN] = flag + + def start(self, ping_interval=5, ping_timeout=3): + """ + 开始识别,新建到服务端的连接 + :param ping_interval: 自动发送ping命令,指定发送间隔,单位为秒 + :param ping_timeout: 等待接收pong消息的超时时间,单位为秒 + :return: 与服务端建立连接成功,返回0 + 与服务端建立连接失败,返回-1 + """ + if self._status == Status.STATUS_INIT: + _log.debug('starting recognizer...') + self._status = Status.STATUS_STARTING + else: + _log.error("Illegal status: %s" % self._status) + return -1 + + def _on_open(ws): + _log.debug('websocket connected') + self._status = Status.STATUS_WS_CONNECTED + self._is_connected = True + msg_id = six.u(uuid.uuid1().hex) + self._task_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_ASR_NAME_START + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._header[Constant.HEADER_KEY_TASK_ID] = self._task_id + + text = self.serialize() + _log.info('sending start cmd: ' + text) + ws.send(text) + + def _on_message(ws, raw): + _log.debug('websocket message received: ' + raw) + msg = json.loads(raw) + name = msg[Constant.HEADER][Constant.HEADER_KEY_NAME] + if name == Constant.HEADER_VALUE_ASR_NAME_STARTED: + self._status = Status.STATUS_STARTED + _log.debug('callback on_started') + self._callback.on_started(msg) + elif name == Constant.HEADER_VALUE_ASR_NAME_RESULT_CHANGED: + _log.debug('callback on_result_changed') + self._callback.on_result_changed(msg) + elif name == Constant.HEADER_VALUE_ASR_NAME_COMPLETED: + if self._status == Status.STATUS_STOPPING: + # 客户端主动调用stop返回的completed事件 + self._status = Status.STATUS_STOPPED + else: + # 开启VAD,服务端主动返回的completed事件 + self._status = Status.STATUS_COMPLETED_WITH_OUT_STOP + + _log.debug('websocket status changed to stopped') + _log.debug('callback on_completed') + self._callback.on_completed(msg) + elif name == Constant.HEADER_VALUE_NAME_TASK_FAILED: + self._status = Status.STATUS_STOPPED + _log.error(msg) + _log.debug('websocket status changed to stopped') + _log.debug('callback on_task_failed') + self._callback.on_task_failed(msg) + + def _on_close(ws): + _log.debug('callback on_channel_closed') + self._callback.on_channel_closed() + + def _on_error(ws, error): + if self._is_connected or self._last_start_retry: + _log.error(error) + self._status = Status.STATUS_STOPPED + message = json.loads('{"header":{"namespace":"Default","name":"TaskFailed",' + '"status":400,"message_id":"0","task_id":"0",' + '"status_text":"%s"}}' + % error) + self._callback.on_task_failed(message) + else: + _log.warning('retry start: %s' % error) + + retry_count = 3 + for count in range(retry_count): + self._status = Status.STATUS_STARTING + if count == (retry_count - 1): + self._last_start_retry = True + + # Init WebSocket + self._ws = websocket.WebSocketApp(self._gateway_url, + on_open=_on_open, + on_message=_on_message, + on_error=_on_error, + on_close=_on_close, + header={Constant.HEADER_TOKEN: self._token}) + + self._thread = threading.Thread(target=self._ws.run_forever, + args=(None, None, ping_interval, ping_timeout)) + self._thread.daemon = True + self._thread.start() + # waite for no more than 10 seconds + for i in range(1000): + if self._status == Status.STATUS_STARTED or self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.01) + + if self._status == Status.STATUS_STARTED: + # 与服务端连接建立成功 + _log.debug('start succeed!') + return 0 + else: + if self._is_connected or self._last_start_retry: + # 已建立了WebSocket链接但是与服务端的连接失败, 或者是最后一次重试,则返回-1 + _log.error("start failed, status: %s" % self._status) + return -1 + else: + # 尝试重连 + continue + + def send(self, audio_data): + """ + 发送语音数据到服务端,建议每次发送 1000 ~ 8000 字节 + :param audio_data: 二进制音频数据 + :return: 发送成功,返回0 + 发送失败,返回-1 + """ + if self._status == Status.STATUS_STARTED: + self._ws.send(audio_data, opcode=websocket.ABNF.OPCODE_BINARY) + return 0 + elif self._status == Status.STATUS_COMPLETED_WITH_OUT_STOP: + _log.info('the recognizer finished with VAD, no need to send data anymore!') + return -1 + else: + _log.error('should not send data in state %d', self._status) + return -1 + + def stop(self): + """ + 结束识别并关闭与服务端的连接 + :return: 关闭成功,返回0 + 关闭失败,返回-1 + """ + ret = 0 + if self._status == Status.STATUS_COMPLETED_WITH_OUT_STOP: + _log.info('the recognizer finished with VAD') + ret = 0 + elif self._status == Status.STATUS_STARTED: + self._status = Status.STATUS_STOPPING + msg_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_ASR_NAME_STOP + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._payload.clear() + text = self.serialize() + _log.info('sending stop cmd: ' + text) + self._ws.send(text) + + for i in range(100): + if self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.1) + _log.debug('waite 100ms') + + if self._status != Status.STATUS_STOPPED: + ret = -1 + else: + ret = 0 + else: + _log.error('should not stop in state %d', self._status) + ret = -1 + + return ret + + def close(self): + """ + 关闭WebSocket链接 + """ + if self._ws: + if self._thread and self._thread.is_alive(): + self._ws.keep_running = False + self._thread.join() + self._ws.close() + diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_reqprotocol.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_reqprotocol.py new file mode 100644 index 0000000..1f8ffb3 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_reqprotocol.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import json + +from ali_speech._constant import Status +from ali_speech._constant import Constant + + +class SpeechReqProtocol: + def __init__(self, callback, url): + self._header = {} + self._context = {} + self._payload = {} + self._token = None + self._gateway_url = url + self._callback = callback + self._status = Status.STATUS_INIT + self._ws = None + self._thread = None + self._task_id = None + + sdk_info = {Constant.CONTEXT_SDK_KEY_NAME: Constant.CONTEXT_SDK_VALUE_NAME, + Constant.CONTEXT_SDK_KEY_VERSION: Constant.CONTEXT_SDK_VALUE_VERSION} + self._context[Constant.CONTEXT_SDK_KEY] = sdk_info + + def set_appkey(self, appkey): + self._header[Constant.HEADER_KEY_APPKEY] = appkey + + def get_appkey(self): + return self._header[Constant.HEADER_KEY_APPKEY] + + def set_token(self, token): + self._token = token + + def get_token(self): + return self._token + + def set_format(self, format): + self._payload[Constant.PAYLOAD_KEY_FORMAT] = format + + def get_format(self): + return self._payload[Constant.PAYLOAD_KEY_FORMAT] + + def set_sample_rate(self, sample_rate): + self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] = sample_rate + + def get_sample_rate(self): + return self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] + + def get_task_id(self): + return self._header[Constant.HEADER_KEY_TASK_ID] + + def put_context(self, key, obj): + self._context[key] = obj + + def add_payload_param(self, key, obj): + self._payload[key] = obj + + def get_status(self): + return self._status + + def serialize(self): + root = {Constant.HEADER: self._header} + + if len(self._payload) != 0: + root[Constant.CONTEXT] = self._context + root[Constant.PAYLOAD] = self._payload + + return json.dumps(root) diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_synthesizer.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_synthesizer.py new file mode 100644 index 0000000..97894fc --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_synthesizer.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import json +import six +import websocket +import uuid +import threading +import time + +from ali_speech._logging import _log +from ali_speech._constant import Status +from ali_speech._constant import Constant +from ali_speech._speech_reqprotocol import SpeechReqProtocol + + +class SpeechSynthesizer(SpeechReqProtocol): + + def __init__(self, callback, url): + super(SpeechSynthesizer, self).__init__(callback, url) + self._last_start_retry = False + self._is_connected = False + + self._header[Constant.HEADER_KEY_NAMESPACE] = Constant.HEADER_VALUE_TTS_NAMESPACE + self._payload[Constant.PAYLOAD_KEY_VOICE] = 'xiaoyun' + self._payload[Constant.PAYLOAD_KEY_FORMAT] = 'pcm' + self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] = 16000 + + def set_text(self, text): + self._payload[Constant.PAYLOAD_KEY_TEXT] = text + + def set_voice(self, voice): + self._payload[Constant.PAYLOAD_KEY_VOICE] = voice + + def set_volume(self, volume): + self._payload[Constant.PAYLOAD_KEY_VOLUME] = volume + + def set_speech_rate(self, speech_rate): + self._payload[Constant.PAYLOAD_KEY_SPEECH_RATE] = speech_rate + + def set_pitch_rate(self, pitch_rate): + self._payload[Constant.PAYLOAD_KEY_PITCH_RATE] = pitch_rate + + def start(self, ping_interval=5, ping_timeout=3): + """ + 开始合成,新建到服务端的连接 + :param ping_interval: 自动发送ping命令,指定发送间隔,单位为秒 + :param ping_timeout: 等待接收pong消息的超时时间,单位为秒 + :return: 与服务端建立连接成功,返回0 + 与服务端建立连接失败,返回-1 + """ + if self._status == Status.STATUS_INIT: + _log.debug('starting synthesizer...') + self._status = Status.STATUS_STARTING + else: + _log.error("Illegal status: %s" % self._status) + return -1 + + def _on_open(ws): + _log.debug('websocket connected') + self._status = Status.STATUS_STARTED + self._is_connected = True + time.sleep(0.01) + msg_id = six.u(uuid.uuid1().hex) + self._task_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_TTS_NAME_START + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._header[Constant.HEADER_KEY_TASK_ID] = self._task_id + + text = self.serialize() + _log.info('sending start cmd: ' + text) + ws.send(text) + + def _on_data(ws, raw, opcode, flag): + if opcode == websocket.ABNF.OPCODE_BINARY: + _log.debug("received binary data, size: %s" % len(raw)) + self._callback.on_binary_data_received(raw) + elif opcode == websocket.ABNF.OPCODE_TEXT: + _log.debug("websocket message received: %s" % raw) + msg = json.loads(raw) + name = msg[Constant.HEADER][Constant.HEADER_KEY_NAME] + if name == Constant.HEADER_VALUE_TTS_NAME_COMPLETED: + self._status = Status.STATUS_STOPPED + _log.debug('websocket status changed to stopped') + _log.debug('callback on_completed') + self._callback.on_completed(msg) + elif name == Constant.HEADER_VALUE_NAME_TASK_FAILED: + self._status = Status.STATUS_STOPPED + _log.error(msg) + _log.debug('websocket status changed to stopped') + _log.debug('callback on_task_failed') + self._callback.on_task_failed(msg) + + def _on_close(ws): + _log.debug('callback on_channel_closed') + self._callback.on_channel_closed() + + def _on_error(ws, error): + if self._is_connected or self._last_start_retry: + _log.error(error) + self._status = Status.STATUS_STOPPED + message = json.loads('{"header":{"namespace":"Default","name":"TaskFailed",' + '"status":400,"message_id":"0","task_id":"0",' + '"status_text":"%s"}}' + % error) + self._callback.on_task_failed(message) + else: + _log.warning('retry start: %s' % error) + + retry_count = 3 + for count in range(retry_count): + self._status = Status.STATUS_STARTING + if count == (retry_count - 1): + self._last_start_retry = True + + # Init WebSocket + self._ws = websocket.WebSocketApp(self._gateway_url, + on_open=_on_open, + on_data=_on_data, + on_error=_on_error, + on_close=_on_close, + header={Constant.HEADER_TOKEN: self._token}) + + self._thread = threading.Thread(target=self._ws.run_forever, args=(None, None, ping_interval, ping_timeout)) + self._thread.daemon = True + self._thread.start() + # waite for no more than 10 seconds + for i in range(1000): + if self._status == Status.STATUS_STARTED or self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.01) + + if self._status == Status.STATUS_STARTED: + # 与服务端连接建立成功 + _log.debug('start succeed!') + return 0 + else: + if self._is_connected or self._last_start_retry: + # 已建立了WebSocket链接但是与服务端的连接失败, 或者是最后一次重试,则返回-1 + _log.error("start failed, status: %s" % self._status) + return -1 + else: + # 尝试重连 + continue + + def wait_completed(self): + """ + 等待合成结束 + :return: 合成结束,返回0 + 合成超时,返回-1 + """ + ret = 0 + if self._status == Status.STATUS_STARTED: + for i in range(100): + if self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.1) + _log.debug('waite 100ms') + + if self._status != Status.STATUS_STOPPED: + ret = -1 + else: + ret = 0 + else: + _log.error('should not wait completed in state %d', self._status) + ret = -1 + + return ret + + def close(self): + """ + 关闭WebSocket连接 + :return: + """ + if self._ws: + if self._thread and self._thread.is_alive(): + self._ws.keep_running = False + self._thread.join() + self._ws.close() + diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_transcriber.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_transcriber.py new file mode 100644 index 0000000..e63c6fa --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/_speech_transcriber.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import json +import six +import websocket +import uuid +import threading +import time + +from ali_speech._logging import _log +from ali_speech._constant import Status +from ali_speech._constant import Constant +from ali_speech._speech_reqprotocol import SpeechReqProtocol + + +class SpeechTranscriber(SpeechReqProtocol): + def __init__(self, callback, url): + super(SpeechTranscriber, self).__init__(callback, url) + self._last_start_retry = False + self._is_connected = False + + self._header[Constant.HEADER_KEY_NAMESPACE] = Constant.HEADER_VALUE_TRANS_NAMESPACE + self._payload[Constant.PAYLOAD_KEY_FORMAT] = 'pcm' + self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] = 16000 + + def set_enable_intermediate_result(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_INTERMEDIATE_RESULT] = flag + + def set_enable_punctuation_prediction(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_PUNCTUATION_PREDICTION] = flag + + def set_enable_inverse_text_normalization(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_ITN] = flag + + def start(self, ping_interval=5, ping_timeout=3): + """ + 开始识别,新建到服务端的连接 + :param ping_interval: 自动发送ping命令,指定发送间隔,单位为秒 + :param ping_timeout: 等待接收pong消息的超时时间,单位为秒 + :return: 与服务端建立连接成功,返回0 + 与服务端建立连接失败,返回-1 + """ + if self._status == Status.STATUS_INIT: + _log.debug('starting transcriber...') + self._status = Status.STATUS_STARTING + else: + _log.error("Illegal status: %s" % self._status) + return -1 + + def _on_open(ws): + _log.debug('websocket connected') + self._status = Status.STATUS_WS_CONNECTED + self._is_connected = True + msg_id = six.u(uuid.uuid1().hex) + self._task_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_TRANS_NAME_START + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._header[Constant.HEADER_KEY_TASK_ID] = self._task_id + + text = self.serialize() + _log.info('sending start cmd: ' + text) + ws.send(text) + + def _on_message(ws, raw): + _log.debug('websocket message received: ' + raw) + msg = json.loads(raw) + name = msg[Constant.HEADER][Constant.HEADER_KEY_NAME] + if name == Constant.HEADER_VALUE_TRANS_NAME_STARTED: + self._status = Status.STATUS_STARTED + _log.debug('callback on_started') + self._callback.on_started(msg) + elif name == Constant.HEADER_VALUE_TRANS_NAME_RESULT_CHANGE: + _log.debug('callback on_result_changed') + self._callback.on_result_changed(msg) + elif name == Constant.HEADER_VALUE_TRANS_NAME_SENTENCE_BEGIN: + _log.debug('callback on_sentence_begin') + self._callback.on_sentence_begin(msg) + elif name == Constant.HEADER_VALUE_TRANS_NAME_SENTENCE_END: + _log.debug('callback on_sentence_end') + self._callback.on_sentence_end(msg) + elif name == Constant.HEADER_VALUE_TRANS_NAME_COMPLETED: + self._status = Status.STATUS_STOPPED + _log.debug('websocket status changed to stopped') + _log.debug('callback on_completed') + self._callback.on_completed(msg) + elif name == Constant.HEADER_VALUE_NAME_TASK_FAILED: + self._status = Status.STATUS_STOPPED + _log.error(msg) + _log.debug('websocket status changed to stopped') + _log.debug('callback on_task_failed') + self._callback.on_task_failed(msg) + + def _on_close(ws): + _log.debug('callback on_channel_closed') + self._callback.on_channel_closed() + + def _on_error(ws, error): + if self._is_connected or self._last_start_retry: + _log.error(error) + self._status = Status.STATUS_STOPPED + message = json.loads('{"header":{"namespace":"Default","name":"TaskFailed",' + '"status":400,"message_id":"0","task_id":"0",' + '"status_text":"%s"}}' + % error) + self._callback.on_task_failed(message) + else: + _log.warning('retry start: %s' % error) + + retry_count = 3 + for count in range(retry_count): + self._status = Status.STATUS_STARTING + if count == (retry_count - 1): + self._last_start_retry = True + + # Init WebSocket + self._ws = websocket.WebSocketApp(self._gateway_url, + on_open=_on_open, + on_message=_on_message, + on_error=_on_error, + on_close=_on_close, + header={Constant.HEADER_TOKEN: self._token}) + + self._thread = threading.Thread(target=self._ws.run_forever, args=(None, None, ping_interval, ping_timeout)) + self._thread.daemon = True + self._thread.start() + # waite for no more than 3 seconds + for i in range(1000): + if self._status == Status.STATUS_STARTED or self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.01) + + if self._status == Status.STATUS_STARTED: + _log.debug('start succeed!') + return 0 + else: + if self._is_connected or self._last_start_retry: + _log.error("start failed, status: %s" % self._status) + return -1 + else: + continue + + def send(self, audio_data): + """ + 发送语音数据到服务端,建议每次发送 1000 ~ 8000 字节 + :param audio_data: 二进制音频数据 + :return: 发送成功,返回0 + 发送失败,返回-1 + """ + if self._status == Status.STATUS_STARTED: + self._ws.send(audio_data, opcode=websocket.ABNF.OPCODE_BINARY) + return 0 + else: + _log.error('should not send data in state %d', self._status) + return -1 + + def stop(self): + """ + 结束识别并关闭与服务端的连接 + :return: 关闭成功,返回0 + 关闭失败,返回-1 + """ + ret = 0 + if self._status == Status.STATUS_STARTED: + self._status = Status.STATUS_STOPPING + msg_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_TRANS_NAME_STOP + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._payload.clear() + text = self.serialize() + _log.info('sending stop cmd: ' + text) + self._ws.send(text) + + for i in range(100): + if self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.1) + _log.debug('waite 100ms') + + if self._status != Status.STATUS_STOPPED: + ret = -1 + else: + ret = 0 + else: + _log.error('should not stop in state %d', self._status) + ret = -1 + + return ret + + def close(self): + """ + 关闭WebSocket链接 + :return: + """ + if self._ws: + if self._thread and self._thread.is_alive(): + self._ws.keep_running = False + self._thread.join() + self._ws.close() diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/callbacks.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/callbacks.py new file mode 100644 index 0000000..fca77c2 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/callbacks.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + + +class SpeechRecognizerCallback: + """ + * @brief 调用start(), 成功与服务建立连接, sdk内部线程上报started事件 + * @note 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_started(self, message): + raise Exception('Not implemented!') + + """ + * @brief 设置允许返回中间结果参数, sdk在接收到服务返回到中间结果时, sdk内部线程上报ResultChanged事件 + * @note 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_result_changed(self, message): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回识别结束消息时, sdk内部线程上报Completed事件 + * @note 上报Completed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_completed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别过程(包含start(), send(), stop())发生异常时, sdk内部线程上报TaskFailed事件 + * @note 上报TaskFailed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_task_failed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别结束或发生异常时,会关闭websocket连接通道 + * @note 请勿在回调函数内部调用stop()操作 + * @return + """ + def on_channel_closed(self): + raise Exception('Not implemented!') + + +class SpeechTranscriberCallback: + """ + * @brief 调用start(), 成功与服务建立连接, sdk内部线程上报started事件 + * @note 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_started(self, message): + raise Exception('Not implemented!') + + """ + * @brief 设置允许返回中间结果参数, sdk在接收到服务返回到中间结果时, sdk内部线程上报ResultChanged事件 + * @note 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_result_changed(self, message): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回的识别到一句话的开始, sdk内部线程上报SentenceBegin事件 + * @note 该事件作为检测到一句话的开始,请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_sentence_begin(self, message): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回的识别到一句话的开始, sdk内部线程上报SentenceBegin事件 + * @note 该事件作为检测到一句话的开始,请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_sentence_end(self, message): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回识别结束消息时, sdk内部线程上报Completed事件 + * @note 上报Completed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_completed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别过程(包含start(), send(), stop())发生异常时, sdk内部线程上报TaskFailed事件 + * @note 上报TaskFailed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_task_failed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别结束或发生异常时,会关闭websocket连接通道 + * @note 请勿在回调函数内部调用stop()操作 + * @return + """ + def on_channel_closed(self): + raise Exception('Not implemented!') + + +class SpeechSynthesizerCallback: + + def on_binary_data_received(self, raw): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回识别结束消息时, sdk内部线程上报Completed事件 + * @note 上报Completed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_completed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别过程(包含start(), send(), stop())发生异常时, sdk内部线程上报TaskFailed事件 + * @note 上报TaskFailed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_task_failed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别结束或发生异常时,会关闭websocket连接通道 + * @note 请勿在回调函数内部调用stop()操作 + * @return + """ + def on_channel_closed(self): + raise Exception('Not implemented!') diff --git a/安装指南/alibabacloud-nls-python-sdk/ali_speech/constant.py b/安装指南/alibabacloud-nls-python-sdk/ali_speech/constant.py new file mode 100644 index 0000000..2b13410 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/ali_speech/constant.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + + +class ASRFormat: + PCM = 'pcm' + OPUS = 'opus' + + +class TTSFormat: + PCM = 'pcm' + WAV = 'wav' + MP3 = 'mp3' + + +class ASRSampleRate: + SAMPLE_RATE_8K = 8000 + SAMPLE_RATE_16K = 16000 + + +class TTSSampleRate: + SAMPLE_RATE_8K = 8000 + SAMPLE_RATE_16K = 16000 + SAMPLE_RATE_24K = 24000 + diff --git a/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/PKG-INFO b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/PKG-INFO new file mode 100644 index 0000000..f0794bf --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/PKG-INFO @@ -0,0 +1,19 @@ +Metadata-Version: 1.1 +Name: alibabacloud-nls-java-sdk +Version: 2.0.0 +Summary: ali_speech python sdk +Home-page: https://github.com/aliyun/alibabacloud-nls-python-sdk.git +Author: Alibaba Cloud NLS Team +Author-email: nls-system-client@list.alibaba-inc.com +License: Apache License 2.0 +Description: UNKNOWN +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Topic :: Software Development diff --git a/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/SOURCES.txt b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/SOURCES.txt new file mode 100644 index 0000000..cb03b97 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/SOURCES.txt @@ -0,0 +1,18 @@ +README.rst +setup.py +ali_speech/__init__.py +ali_speech/_client.py +ali_speech/_constant.py +ali_speech/_create_token.py +ali_speech/_logging.py +ali_speech/_speech_recognizer.py +ali_speech/_speech_reqprotocol.py +ali_speech/_speech_synthesizer.py +ali_speech/_speech_transcriber.py +ali_speech/callbacks.py +ali_speech/constant.py +alibabacloud_nls_java_sdk.egg-info/PKG-INFO +alibabacloud_nls_java_sdk.egg-info/SOURCES.txt +alibabacloud_nls_java_sdk.egg-info/dependency_links.txt +alibabacloud_nls_java_sdk.egg-info/requires.txt +alibabacloud_nls_java_sdk.egg-info/top_level.txt \ No newline at end of file diff --git a/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/dependency_links.txt b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/requires.txt b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/requires.txt new file mode 100644 index 0000000..bdbbd00 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/requires.txt @@ -0,0 +1,2 @@ +websocket-client +requests diff --git a/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/top_level.txt b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/top_level.txt new file mode 100644 index 0000000..fd3a58f --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/alibabacloud_nls_java_sdk.egg-info/top_level.txt @@ -0,0 +1 @@ +ali_speech diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/__init__.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/__init__.py new file mode 100644 index 0000000..4d2d663 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/__init__.py @@ -0,0 +1,19 @@ +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +from ali_speech._client import NlsClient + +__version__ = "0.1.0" diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_client.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_client.py new file mode 100644 index 0000000..45b02bb --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_client.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import websocket + +try: + import thread +except ImportError: + import _thread as thread + +from ali_speech._logging import _log +from ali_speech._create_token import AccessToken +from ali_speech._speech_recognizer import SpeechRecognizer +from ali_speech._speech_transcriber import SpeechTranscriber +from ali_speech._speech_synthesizer import SpeechSynthesizer + +__all__ = ["NlsClient"] + + +class NlsClient: + URL_GATEWAY = 'wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1' + + def __init__(self): + websocket.enableTrace(False) + + @staticmethod + def set_log_level(level): + _log.setLevel(level) + + @staticmethod + def create_token(access_key_id, access_key_secret): + return AccessToken.create_token(access_key_id, access_key_secret) + + def create_recognizer(self, callback, gateway_url=URL_GATEWAY): + request = SpeechRecognizer(callback, gateway_url) + return request + + def create_transcriber(self, callback, gateway_url=URL_GATEWAY): + transcriber = SpeechTranscriber(callback, gateway_url) + return transcriber + + def create_synthesizer(self, callback, gateway_url=URL_GATEWAY): + synthesizer = SpeechSynthesizer(callback, gateway_url) + return synthesizer diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_constant.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_constant.py new file mode 100644 index 0000000..ca8387a --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_constant.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + + +class Status: + # 初始状态 + STATUS_INIT = 1 + # websocker 网络连接建立成功,on_open + STATUS_WS_CONNECTED = 2 + # 与gateway服务建立连接中 + STATUS_STARTING = 3 + # 与服务建立连接成功,on_message RecognitionStarted + STATUS_STARTED = 4 + # 客户端正主动断开连接 + STATUS_STOPPING = 5 + # 与服务已断开连接 + STATUS_STOPPED = 6 + # 开启VAD,服务主动返回completed事件 + STATUS_COMPLETED_WITH_OUT_STOP = 7 + + +class Constant: + CONTEXT = 'context' + CONTEXT_SDK_KEY = 'sdk' + CONTEXT_SDK_KEY_NAME = 'name' + CONTEXT_SDK_VALUE_NAME = 'nls-sdk-python' + CONTEXT_SDK_KEY_VERSION = 'version' + CONTEXT_SDK_VALUE_VERSION = '2.0.1' + + HEADER_TOKEN = 'X-NLS-Token' + + HEADER = 'header' + HEADER_KEY_NAMESPACE = 'namespace' + HEADER_KEY_NAME = 'name' + HEADER_KEY_MESSAGE_ID = 'message_id' + HEADER_KEY_APPKEY = 'appkey' + HEADER_KEY_TASK_ID = 'task_id' + HEADER_KEY_STATUS = 'status' + HEADER_KEY_STATUS_TEXT = 'status_text' + + PAYLOAD = 'payload' + PAYLOAD_KEY_SAMPLE_RATE = 'sample_rate' + PAYLOAD_KEY_FORMAT = 'format' + PAYLOAD_KEY_ENABLE_ITN = 'enable_inverse_text_normalization' + PAYLOAD_KEY_ENABLE_INTERMEDIATE_RESULT = 'enable_intermediate_result' + PAYLOAD_KEY_ENABLE_PUNCTUATION_PREDICTION = 'enable_punctuation_prediction' + + PAYLOAD_KEY_VOICE = 'voice' + PAYLOAD_KEY_TEXT = 'text' + PAYLOAD_KEY_VOLUME = 'volume' + PAYLOAD_KEY_SPEECH_RATE = 'speech_rate' + PAYLOAD_KEY_PITCH_RATE = 'pitch_rate' + + HEADER_VALUE_ASR_NAMESPACE = 'SpeechRecognizer' + HEADER_VALUE_ASR_NAME_START = 'StartRecognition' + HEADER_VALUE_ASR_NAME_STOP = 'StopRecognition' + HEADER_VALUE_ASR_NAME_STARTED = 'RecognitionStarted' + HEADER_VALUE_ASR_NAME_RESULT_CHANGED = 'RecognitionResultChanged' + HEADER_VALUE_ASR_NAME_COMPLETED = 'RecognitionCompleted' + + HEADER_VALUE_NAME_TASK_FAILED = 'TaskFailed' + + HEADER_VALUE_TRANS_NAMESPACE = 'SpeechTranscriber' + HEADER_VALUE_TRANS_NAME_START = 'StartTranscription' + HEADER_VALUE_TRANS_NAME_STOP = 'StopTranscription' + HEADER_VALUE_TRANS_NAME_STARTED = 'TranscriptionStarted' + HEADER_VALUE_TRANS_NAME_SENTENCE_BEGIN = 'SentenceBegin' + HEADER_VALUE_TRANS_NAME_SENTENCE_END = 'SentenceEnd' + HEADER_VALUE_TRANS_NAME_RESULT_CHANGE = 'TranscriptionResultChanged' + HEADER_VALUE_TRANS_NAME_COMPLETED = 'TranscriptionCompleted' + + HEADER_VALUE_TTS_NAMESPACE = 'SpeechSynthesizer' + HEADER_VALUE_TTS_NAME_START = 'StartSynthesis' + HEADER_VALUE_TTS_NAME_COMPLETED = 'SynthesisCompleted' + diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_create_token.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_create_token.py new file mode 100644 index 0000000..d7c9a79 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_create_token.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import base64 +import hashlib +import hmac +import requests +import time +import uuid + +from urllib import parse +from ali_speech._logging import _log + + +class AccessToken: + @staticmethod + def _encode_text(text): + encoded_text = parse.quote_plus(text) + return encoded_text.replace('+', '%20').replace('*', '%2A').replace('%7E', '~') + + @staticmethod + def _encode_dict(dic): + keys = dic.keys() + dic_sorted = [(key, dic[key]) for key in sorted(keys)] + encoded_text = parse.urlencode(dic_sorted) + return encoded_text.replace('+', '%20').replace('*', '%2A').replace('%7E', '~') + + @staticmethod + def create_token(access_key_id, access_key_secret): + parameters = {'AccessKeyId': access_key_id, + 'Action': 'CreateToken', + 'Format': 'JSON', + 'RegionId': 'cn-shanghai', + 'SignatureMethod': 'HMAC-SHA1', + 'SignatureNonce': str(uuid.uuid1()), + 'SignatureVersion': '1.0', + 'Timestamp': time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + 'Version': '2019-02-28'} + # 构造规范化的请求字符串 + query_string = AccessToken._encode_dict(parameters) + _log.debug('规范化的请求字符串: %s' % query_string) + # 构造待签名字符串 + string_to_sign = 'GET' + '&' + AccessToken._encode_text('/') + '&' + AccessToken._encode_text(query_string) + _log.debug('待签名的字符串: %s' % string_to_sign) + # 计算签名 + secreted_string = hmac.new(bytes(access_key_secret + '&', encoding='utf-8'), + bytes(string_to_sign, encoding='utf-8'), + hashlib.sha1).digest() + signature = base64.b64encode(secreted_string) + _log.debug('签名: %s' % signature) + # 进行URL编码 + signature = AccessToken._encode_text(signature) + _log.debug('URL编码后的签名: %s' % signature) + # 调用服务 + full_url = 'http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s' % (signature, query_string) + _log.debug('url: %s' % full_url) + # 提交HTTP GET请求 + response = requests.get(full_url) + if response.ok: + root_obj = response.json() + key = 'Token' + if key in root_obj: + token = root_obj[key]['Id'] + expire_time = root_obj[key]['ExpireTime'] + return token, expire_time + + _log.error(response.text) + return None, None + + diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_logging.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_logging.py new file mode 100644 index 0000000..a16d9cb --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_logging.py @@ -0,0 +1,31 @@ +# -*- coding:utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import logging.handlers + +__all__ = ['_log'] + +FORMAT = '%(asctime)15s %(name)s-%(levelname)s %(funcName)s:%(lineno)s %(message)s' +logging.basicConfig(level=logging.DEBUG, format=FORMAT) +_log = logging.getLogger('alispeech') + +handler = logging.handlers.RotatingFileHandler('alispeech.log', maxBytes=1024 * 1024, + backupCount=5, encoding='utf-8') +handler.setLevel(logging.DEBUG) +handler.setFormatter(logging.Formatter(FORMAT)) +_log.addHandler(handler) diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_recognizer.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_recognizer.py new file mode 100644 index 0000000..08889a3 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_recognizer.py @@ -0,0 +1,227 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import json +import six +import websocket +import uuid +import threading +import time + +from ali_speech._logging import _log +from ali_speech._constant import Status +from ali_speech._constant import Constant +from ali_speech._speech_reqprotocol import SpeechReqProtocol + + +class SpeechRecognizer(SpeechReqProtocol): + + def __init__(self, callback, url): + super(SpeechRecognizer, self).__init__(callback, url) + self._last_start_retry = False + self._is_connected = False + + self._header[Constant.HEADER_KEY_NAMESPACE] = Constant.HEADER_VALUE_ASR_NAMESPACE + self._payload[Constant.PAYLOAD_KEY_FORMAT] = "pcm" + self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] = 16000 + + def set_enable_intermediate_result(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_INTERMEDIATE_RESULT] = flag + + def set_enable_punctuation_prediction(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_PUNCTUATION_PREDICTION] = flag + + def set_enable_inverse_text_normalization(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_ITN] = flag + + def start(self, ping_interval=5, ping_timeout=3): + """ + 开始识别,新建到服务端的连接 + :param ping_interval: 自动发送ping命令,指定发送间隔,单位为秒 + :param ping_timeout: 等待接收pong消息的超时时间,单位为秒 + :return: 与服务端建立连接成功,返回0 + 与服务端建立连接失败,返回-1 + """ + if self._status == Status.STATUS_INIT: + _log.debug('starting recognizer...') + self._status = Status.STATUS_STARTING + else: + _log.error("Illegal status: %s" % self._status) + return -1 + + def _on_open(ws): + _log.debug('websocket connected') + self._status = Status.STATUS_WS_CONNECTED + self._is_connected = True + msg_id = six.u(uuid.uuid1().hex) + self._task_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_ASR_NAME_START + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._header[Constant.HEADER_KEY_TASK_ID] = self._task_id + + text = self.serialize() + _log.info('sending start cmd: ' + text) + ws.send(text) + + def _on_message(ws, raw): + _log.debug('websocket message received: ' + raw) + msg = json.loads(raw) + name = msg[Constant.HEADER][Constant.HEADER_KEY_NAME] + if name == Constant.HEADER_VALUE_ASR_NAME_STARTED: + self._status = Status.STATUS_STARTED + _log.debug('callback on_started') + self._callback.on_started(msg) + elif name == Constant.HEADER_VALUE_ASR_NAME_RESULT_CHANGED: + _log.debug('callback on_result_changed') + self._callback.on_result_changed(msg) + elif name == Constant.HEADER_VALUE_ASR_NAME_COMPLETED: + if self._status == Status.STATUS_STOPPING: + # 客户端主动调用stop返回的completed事件 + self._status = Status.STATUS_STOPPED + else: + # 开启VAD,服务端主动返回的completed事件 + self._status = Status.STATUS_COMPLETED_WITH_OUT_STOP + + _log.debug('websocket status changed to stopped') + _log.debug('callback on_completed') + self._callback.on_completed(msg) + elif name == Constant.HEADER_VALUE_NAME_TASK_FAILED: + self._status = Status.STATUS_STOPPED + _log.error(msg) + _log.debug('websocket status changed to stopped') + _log.debug('callback on_task_failed') + self._callback.on_task_failed(msg) + + def _on_close(ws): + _log.debug('callback on_channel_closed') + self._callback.on_channel_closed() + + def _on_error(ws, error): + if self._is_connected or self._last_start_retry: + _log.error(error) + self._status = Status.STATUS_STOPPED + message = json.loads('{"header":{"namespace":"Default","name":"TaskFailed",' + '"status":400,"message_id":"0","task_id":"0",' + '"status_text":"%s"}}' + % error) + self._callback.on_task_failed(message) + else: + _log.warning('retry start: %s' % error) + + retry_count = 3 + for count in range(retry_count): + self._status = Status.STATUS_STARTING + if count == (retry_count - 1): + self._last_start_retry = True + + # Init WebSocket + self._ws = websocket.WebSocketApp(self._gateway_url, + on_open=_on_open, + on_message=_on_message, + on_error=_on_error, + on_close=_on_close, + header={Constant.HEADER_TOKEN: self._token}) + + self._thread = threading.Thread(target=self._ws.run_forever, + args=(None, None, ping_interval, ping_timeout)) + self._thread.daemon = True + self._thread.start() + # waite for no more than 10 seconds + for i in range(1000): + if self._status == Status.STATUS_STARTED or self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.01) + + if self._status == Status.STATUS_STARTED: + # 与服务端连接建立成功 + _log.debug('start succeed!') + return 0 + else: + if self._is_connected or self._last_start_retry: + # 已建立了WebSocket链接但是与服务端的连接失败, 或者是最后一次重试,则返回-1 + _log.error("start failed, status: %s" % self._status) + return -1 + else: + # 尝试重连 + continue + + def send(self, audio_data): + """ + 发送语音数据到服务端,建议每次发送 1000 ~ 8000 字节 + :param audio_data: 二进制音频数据 + :return: 发送成功,返回0 + 发送失败,返回-1 + """ + if self._status == Status.STATUS_STARTED: + self._ws.send(audio_data, opcode=websocket.ABNF.OPCODE_BINARY) + return 0 + elif self._status == Status.STATUS_COMPLETED_WITH_OUT_STOP: + _log.info('the recognizer finished with VAD, no need to send data anymore!') + return -1 + else: + _log.error('should not send data in state %d', self._status) + return -1 + + def stop(self): + """ + 结束识别并关闭与服务端的连接 + :return: 关闭成功,返回0 + 关闭失败,返回-1 + """ + ret = 0 + if self._status == Status.STATUS_COMPLETED_WITH_OUT_STOP: + _log.info('the recognizer finished with VAD') + ret = 0 + elif self._status == Status.STATUS_STARTED: + self._status = Status.STATUS_STOPPING + msg_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_ASR_NAME_STOP + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._payload.clear() + text = self.serialize() + _log.info('sending stop cmd: ' + text) + self._ws.send(text) + + for i in range(100): + if self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.1) + _log.debug('waite 100ms') + + if self._status != Status.STATUS_STOPPED: + ret = -1 + else: + ret = 0 + else: + _log.error('should not stop in state %d', self._status) + ret = -1 + + return ret + + def close(self): + """ + 关闭WebSocket链接 + """ + if self._ws: + if self._thread and self._thread.is_alive(): + self._ws.keep_running = False + self._thread.join() + self._ws.close() + diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_reqprotocol.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_reqprotocol.py new file mode 100644 index 0000000..1f8ffb3 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_reqprotocol.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import json + +from ali_speech._constant import Status +from ali_speech._constant import Constant + + +class SpeechReqProtocol: + def __init__(self, callback, url): + self._header = {} + self._context = {} + self._payload = {} + self._token = None + self._gateway_url = url + self._callback = callback + self._status = Status.STATUS_INIT + self._ws = None + self._thread = None + self._task_id = None + + sdk_info = {Constant.CONTEXT_SDK_KEY_NAME: Constant.CONTEXT_SDK_VALUE_NAME, + Constant.CONTEXT_SDK_KEY_VERSION: Constant.CONTEXT_SDK_VALUE_VERSION} + self._context[Constant.CONTEXT_SDK_KEY] = sdk_info + + def set_appkey(self, appkey): + self._header[Constant.HEADER_KEY_APPKEY] = appkey + + def get_appkey(self): + return self._header[Constant.HEADER_KEY_APPKEY] + + def set_token(self, token): + self._token = token + + def get_token(self): + return self._token + + def set_format(self, format): + self._payload[Constant.PAYLOAD_KEY_FORMAT] = format + + def get_format(self): + return self._payload[Constant.PAYLOAD_KEY_FORMAT] + + def set_sample_rate(self, sample_rate): + self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] = sample_rate + + def get_sample_rate(self): + return self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] + + def get_task_id(self): + return self._header[Constant.HEADER_KEY_TASK_ID] + + def put_context(self, key, obj): + self._context[key] = obj + + def add_payload_param(self, key, obj): + self._payload[key] = obj + + def get_status(self): + return self._status + + def serialize(self): + root = {Constant.HEADER: self._header} + + if len(self._payload) != 0: + root[Constant.CONTEXT] = self._context + root[Constant.PAYLOAD] = self._payload + + return json.dumps(root) diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_synthesizer.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_synthesizer.py new file mode 100644 index 0000000..97894fc --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_synthesizer.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import json +import six +import websocket +import uuid +import threading +import time + +from ali_speech._logging import _log +from ali_speech._constant import Status +from ali_speech._constant import Constant +from ali_speech._speech_reqprotocol import SpeechReqProtocol + + +class SpeechSynthesizer(SpeechReqProtocol): + + def __init__(self, callback, url): + super(SpeechSynthesizer, self).__init__(callback, url) + self._last_start_retry = False + self._is_connected = False + + self._header[Constant.HEADER_KEY_NAMESPACE] = Constant.HEADER_VALUE_TTS_NAMESPACE + self._payload[Constant.PAYLOAD_KEY_VOICE] = 'xiaoyun' + self._payload[Constant.PAYLOAD_KEY_FORMAT] = 'pcm' + self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] = 16000 + + def set_text(self, text): + self._payload[Constant.PAYLOAD_KEY_TEXT] = text + + def set_voice(self, voice): + self._payload[Constant.PAYLOAD_KEY_VOICE] = voice + + def set_volume(self, volume): + self._payload[Constant.PAYLOAD_KEY_VOLUME] = volume + + def set_speech_rate(self, speech_rate): + self._payload[Constant.PAYLOAD_KEY_SPEECH_RATE] = speech_rate + + def set_pitch_rate(self, pitch_rate): + self._payload[Constant.PAYLOAD_KEY_PITCH_RATE] = pitch_rate + + def start(self, ping_interval=5, ping_timeout=3): + """ + 开始合成,新建到服务端的连接 + :param ping_interval: 自动发送ping命令,指定发送间隔,单位为秒 + :param ping_timeout: 等待接收pong消息的超时时间,单位为秒 + :return: 与服务端建立连接成功,返回0 + 与服务端建立连接失败,返回-1 + """ + if self._status == Status.STATUS_INIT: + _log.debug('starting synthesizer...') + self._status = Status.STATUS_STARTING + else: + _log.error("Illegal status: %s" % self._status) + return -1 + + def _on_open(ws): + _log.debug('websocket connected') + self._status = Status.STATUS_STARTED + self._is_connected = True + time.sleep(0.01) + msg_id = six.u(uuid.uuid1().hex) + self._task_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_TTS_NAME_START + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._header[Constant.HEADER_KEY_TASK_ID] = self._task_id + + text = self.serialize() + _log.info('sending start cmd: ' + text) + ws.send(text) + + def _on_data(ws, raw, opcode, flag): + if opcode == websocket.ABNF.OPCODE_BINARY: + _log.debug("received binary data, size: %s" % len(raw)) + self._callback.on_binary_data_received(raw) + elif opcode == websocket.ABNF.OPCODE_TEXT: + _log.debug("websocket message received: %s" % raw) + msg = json.loads(raw) + name = msg[Constant.HEADER][Constant.HEADER_KEY_NAME] + if name == Constant.HEADER_VALUE_TTS_NAME_COMPLETED: + self._status = Status.STATUS_STOPPED + _log.debug('websocket status changed to stopped') + _log.debug('callback on_completed') + self._callback.on_completed(msg) + elif name == Constant.HEADER_VALUE_NAME_TASK_FAILED: + self._status = Status.STATUS_STOPPED + _log.error(msg) + _log.debug('websocket status changed to stopped') + _log.debug('callback on_task_failed') + self._callback.on_task_failed(msg) + + def _on_close(ws): + _log.debug('callback on_channel_closed') + self._callback.on_channel_closed() + + def _on_error(ws, error): + if self._is_connected or self._last_start_retry: + _log.error(error) + self._status = Status.STATUS_STOPPED + message = json.loads('{"header":{"namespace":"Default","name":"TaskFailed",' + '"status":400,"message_id":"0","task_id":"0",' + '"status_text":"%s"}}' + % error) + self._callback.on_task_failed(message) + else: + _log.warning('retry start: %s' % error) + + retry_count = 3 + for count in range(retry_count): + self._status = Status.STATUS_STARTING + if count == (retry_count - 1): + self._last_start_retry = True + + # Init WebSocket + self._ws = websocket.WebSocketApp(self._gateway_url, + on_open=_on_open, + on_data=_on_data, + on_error=_on_error, + on_close=_on_close, + header={Constant.HEADER_TOKEN: self._token}) + + self._thread = threading.Thread(target=self._ws.run_forever, args=(None, None, ping_interval, ping_timeout)) + self._thread.daemon = True + self._thread.start() + # waite for no more than 10 seconds + for i in range(1000): + if self._status == Status.STATUS_STARTED or self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.01) + + if self._status == Status.STATUS_STARTED: + # 与服务端连接建立成功 + _log.debug('start succeed!') + return 0 + else: + if self._is_connected or self._last_start_retry: + # 已建立了WebSocket链接但是与服务端的连接失败, 或者是最后一次重试,则返回-1 + _log.error("start failed, status: %s" % self._status) + return -1 + else: + # 尝试重连 + continue + + def wait_completed(self): + """ + 等待合成结束 + :return: 合成结束,返回0 + 合成超时,返回-1 + """ + ret = 0 + if self._status == Status.STATUS_STARTED: + for i in range(100): + if self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.1) + _log.debug('waite 100ms') + + if self._status != Status.STATUS_STOPPED: + ret = -1 + else: + ret = 0 + else: + _log.error('should not wait completed in state %d', self._status) + ret = -1 + + return ret + + def close(self): + """ + 关闭WebSocket连接 + :return: + """ + if self._ws: + if self._thread and self._thread.is_alive(): + self._ws.keep_running = False + self._thread.join() + self._ws.close() + diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_transcriber.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_transcriber.py new file mode 100644 index 0000000..e63c6fa --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/_speech_transcriber.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import json +import six +import websocket +import uuid +import threading +import time + +from ali_speech._logging import _log +from ali_speech._constant import Status +from ali_speech._constant import Constant +from ali_speech._speech_reqprotocol import SpeechReqProtocol + + +class SpeechTranscriber(SpeechReqProtocol): + def __init__(self, callback, url): + super(SpeechTranscriber, self).__init__(callback, url) + self._last_start_retry = False + self._is_connected = False + + self._header[Constant.HEADER_KEY_NAMESPACE] = Constant.HEADER_VALUE_TRANS_NAMESPACE + self._payload[Constant.PAYLOAD_KEY_FORMAT] = 'pcm' + self._payload[Constant.PAYLOAD_KEY_SAMPLE_RATE] = 16000 + + def set_enable_intermediate_result(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_INTERMEDIATE_RESULT] = flag + + def set_enable_punctuation_prediction(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_PUNCTUATION_PREDICTION] = flag + + def set_enable_inverse_text_normalization(self, flag): + self._payload[Constant.PAYLOAD_KEY_ENABLE_ITN] = flag + + def start(self, ping_interval=5, ping_timeout=3): + """ + 开始识别,新建到服务端的连接 + :param ping_interval: 自动发送ping命令,指定发送间隔,单位为秒 + :param ping_timeout: 等待接收pong消息的超时时间,单位为秒 + :return: 与服务端建立连接成功,返回0 + 与服务端建立连接失败,返回-1 + """ + if self._status == Status.STATUS_INIT: + _log.debug('starting transcriber...') + self._status = Status.STATUS_STARTING + else: + _log.error("Illegal status: %s" % self._status) + return -1 + + def _on_open(ws): + _log.debug('websocket connected') + self._status = Status.STATUS_WS_CONNECTED + self._is_connected = True + msg_id = six.u(uuid.uuid1().hex) + self._task_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_TRANS_NAME_START + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._header[Constant.HEADER_KEY_TASK_ID] = self._task_id + + text = self.serialize() + _log.info('sending start cmd: ' + text) + ws.send(text) + + def _on_message(ws, raw): + _log.debug('websocket message received: ' + raw) + msg = json.loads(raw) + name = msg[Constant.HEADER][Constant.HEADER_KEY_NAME] + if name == Constant.HEADER_VALUE_TRANS_NAME_STARTED: + self._status = Status.STATUS_STARTED + _log.debug('callback on_started') + self._callback.on_started(msg) + elif name == Constant.HEADER_VALUE_TRANS_NAME_RESULT_CHANGE: + _log.debug('callback on_result_changed') + self._callback.on_result_changed(msg) + elif name == Constant.HEADER_VALUE_TRANS_NAME_SENTENCE_BEGIN: + _log.debug('callback on_sentence_begin') + self._callback.on_sentence_begin(msg) + elif name == Constant.HEADER_VALUE_TRANS_NAME_SENTENCE_END: + _log.debug('callback on_sentence_end') + self._callback.on_sentence_end(msg) + elif name == Constant.HEADER_VALUE_TRANS_NAME_COMPLETED: + self._status = Status.STATUS_STOPPED + _log.debug('websocket status changed to stopped') + _log.debug('callback on_completed') + self._callback.on_completed(msg) + elif name == Constant.HEADER_VALUE_NAME_TASK_FAILED: + self._status = Status.STATUS_STOPPED + _log.error(msg) + _log.debug('websocket status changed to stopped') + _log.debug('callback on_task_failed') + self._callback.on_task_failed(msg) + + def _on_close(ws): + _log.debug('callback on_channel_closed') + self._callback.on_channel_closed() + + def _on_error(ws, error): + if self._is_connected or self._last_start_retry: + _log.error(error) + self._status = Status.STATUS_STOPPED + message = json.loads('{"header":{"namespace":"Default","name":"TaskFailed",' + '"status":400,"message_id":"0","task_id":"0",' + '"status_text":"%s"}}' + % error) + self._callback.on_task_failed(message) + else: + _log.warning('retry start: %s' % error) + + retry_count = 3 + for count in range(retry_count): + self._status = Status.STATUS_STARTING + if count == (retry_count - 1): + self._last_start_retry = True + + # Init WebSocket + self._ws = websocket.WebSocketApp(self._gateway_url, + on_open=_on_open, + on_message=_on_message, + on_error=_on_error, + on_close=_on_close, + header={Constant.HEADER_TOKEN: self._token}) + + self._thread = threading.Thread(target=self._ws.run_forever, args=(None, None, ping_interval, ping_timeout)) + self._thread.daemon = True + self._thread.start() + # waite for no more than 3 seconds + for i in range(1000): + if self._status == Status.STATUS_STARTED or self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.01) + + if self._status == Status.STATUS_STARTED: + _log.debug('start succeed!') + return 0 + else: + if self._is_connected or self._last_start_retry: + _log.error("start failed, status: %s" % self._status) + return -1 + else: + continue + + def send(self, audio_data): + """ + 发送语音数据到服务端,建议每次发送 1000 ~ 8000 字节 + :param audio_data: 二进制音频数据 + :return: 发送成功,返回0 + 发送失败,返回-1 + """ + if self._status == Status.STATUS_STARTED: + self._ws.send(audio_data, opcode=websocket.ABNF.OPCODE_BINARY) + return 0 + else: + _log.error('should not send data in state %d', self._status) + return -1 + + def stop(self): + """ + 结束识别并关闭与服务端的连接 + :return: 关闭成功,返回0 + 关闭失败,返回-1 + """ + ret = 0 + if self._status == Status.STATUS_STARTED: + self._status = Status.STATUS_STOPPING + msg_id = six.u(uuid.uuid1().hex) + self._header[Constant.HEADER_KEY_NAME] = Constant.HEADER_VALUE_TRANS_NAME_STOP + self._header[Constant.HEADER_KEY_MESSAGE_ID] = msg_id + self._payload.clear() + text = self.serialize() + _log.info('sending stop cmd: ' + text) + self._ws.send(text) + + for i in range(100): + if self._status == Status.STATUS_STOPPED: + break + else: + time.sleep(0.1) + _log.debug('waite 100ms') + + if self._status != Status.STATUS_STOPPED: + ret = -1 + else: + ret = 0 + else: + _log.error('should not stop in state %d', self._status) + ret = -1 + + return ret + + def close(self): + """ + 关闭WebSocket链接 + :return: + """ + if self._ws: + if self._thread and self._thread.is_alive(): + self._ws.keep_running = False + self._thread.join() + self._ws.close() diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/callbacks.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/callbacks.py new file mode 100644 index 0000000..fca77c2 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/callbacks.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + + +class SpeechRecognizerCallback: + """ + * @brief 调用start(), 成功与服务建立连接, sdk内部线程上报started事件 + * @note 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_started(self, message): + raise Exception('Not implemented!') + + """ + * @brief 设置允许返回中间结果参数, sdk在接收到服务返回到中间结果时, sdk内部线程上报ResultChanged事件 + * @note 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_result_changed(self, message): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回识别结束消息时, sdk内部线程上报Completed事件 + * @note 上报Completed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_completed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别过程(包含start(), send(), stop())发生异常时, sdk内部线程上报TaskFailed事件 + * @note 上报TaskFailed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_task_failed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别结束或发生异常时,会关闭websocket连接通道 + * @note 请勿在回调函数内部调用stop()操作 + * @return + """ + def on_channel_closed(self): + raise Exception('Not implemented!') + + +class SpeechTranscriberCallback: + """ + * @brief 调用start(), 成功与服务建立连接, sdk内部线程上报started事件 + * @note 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_started(self, message): + raise Exception('Not implemented!') + + """ + * @brief 设置允许返回中间结果参数, sdk在接收到服务返回到中间结果时, sdk内部线程上报ResultChanged事件 + * @note 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_result_changed(self, message): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回的识别到一句话的开始, sdk内部线程上报SentenceBegin事件 + * @note 该事件作为检测到一句话的开始,请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_sentence_begin(self, message): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回的识别到一句话的开始, sdk内部线程上报SentenceBegin事件 + * @note 该事件作为检测到一句话的开始,请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_sentence_end(self, message): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回识别结束消息时, sdk内部线程上报Completed事件 + * @note 上报Completed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_completed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别过程(包含start(), send(), stop())发生异常时, sdk内部线程上报TaskFailed事件 + * @note 上报TaskFailed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_task_failed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别结束或发生异常时,会关闭websocket连接通道 + * @note 请勿在回调函数内部调用stop()操作 + * @return + """ + def on_channel_closed(self): + raise Exception('Not implemented!') + + +class SpeechSynthesizerCallback: + + def on_binary_data_received(self, raw): + raise Exception('Not implemented!') + + """ + * @brief sdk在接收到服务返回识别结束消息时, sdk内部线程上报Completed事件 + * @note 上报Completed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_completed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别过程(包含start(), send(), stop())发生异常时, sdk内部线程上报TaskFailed事件 + * @note 上报TaskFailed事件之后, SDK内部会关闭识别连接通道. 此时调用send()会返回-1, 请停止发送. + * 请勿在回调函数内部调用stop()操作 + * @param message 服务返回的响应 + * @return + """ + def on_task_failed(self, message): + raise Exception('Not implemented!') + + """ + * @brief 识别结束或发生异常时,会关闭websocket连接通道 + * @note 请勿在回调函数内部调用stop()操作 + * @return + """ + def on_channel_closed(self): + raise Exception('Not implemented!') diff --git a/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/constant.py b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/constant.py new file mode 100644 index 0000000..2b13410 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/build/lib/ali_speech/constant.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + + +class ASRFormat: + PCM = 'pcm' + OPUS = 'opus' + + +class TTSFormat: + PCM = 'pcm' + WAV = 'wav' + MP3 = 'mp3' + + +class ASRSampleRate: + SAMPLE_RATE_8K = 8000 + SAMPLE_RATE_16K = 16000 + + +class TTSSampleRate: + SAMPLE_RATE_8K = 8000 + SAMPLE_RATE_16K = 16000 + SAMPLE_RATE_24K = 24000 + diff --git a/安装指南/alibabacloud-nls-python-sdk/create_token_demo.py b/安装指南/alibabacloud-nls-python-sdk/create_token_demo.py new file mode 100644 index 0000000..1dd61e7 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/create_token_demo.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import time +import ali_speech + +if __name__ == "__main__": + ali_speech.NlsClient.set_log_level('INFO') + # 用户信息 + access_key_id = '您的AccessKeyId' + access_key_secret = '您的AccessKeySecret' + token, expire_time = ali_speech.NlsClient.create_token(access_key_id, access_key_secret) + print('token: %s, expire time(s): %s' % (token, expire_time)) + if expire_time: + print('token有效期的北京时间:%s' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(expire_time)))) diff --git a/安装指南/alibabacloud-nls-python-sdk/dist/alibabacloud_nls_java_sdk-2.0.0-py3.7.egg b/安装指南/alibabacloud-nls-python-sdk/dist/alibabacloud_nls_java_sdk-2.0.0-py3.7.egg new file mode 100644 index 0000000..8e203ec Binary files /dev/null and b/安装指南/alibabacloud-nls-python-sdk/dist/alibabacloud_nls_java_sdk-2.0.0-py3.7.egg differ diff --git a/安装指南/alibabacloud-nls-python-sdk/nls-sample-16k.wav b/安装指南/alibabacloud-nls-python-sdk/nls-sample-16k.wav new file mode 100644 index 0000000..33de02f Binary files /dev/null and b/安装指南/alibabacloud-nls-python-sdk/nls-sample-16k.wav differ diff --git a/安装指南/alibabacloud-nls-python-sdk/setup.py b/安装指南/alibabacloud-nls-python-sdk/setup.py new file mode 100644 index 0000000..0665018 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/setup.py @@ -0,0 +1,46 @@ +#!/usr/bin/python +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +config = { + 'name': 'alibabacloud-nls-java-sdk', + 'version': '2.0.0', + 'description': 'ali_speech python sdk', + 'author': 'Alibaba Cloud NLS Team', + 'author_email': 'nls-system-client@list.alibaba-inc.com', + 'license': 'Apache License 2.0', + 'url': 'https://github.com/aliyun/alibabacloud-nls-python-sdk.git', + 'install_requires': ['websocket-client', 'requests'], + 'packages': ['ali_speech'], + 'classifiers': ( + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Topic :: Software Development', + ) +} + +setup(**config) diff --git a/安装指南/alibabacloud-nls-python-sdk/speech_recognizer_demo.py b/安装指南/alibabacloud-nls-python-sdk/speech_recognizer_demo.py new file mode 100644 index 0000000..7161bdc --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/speech_recognizer_demo.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import os +import time +import threading +import ali_speech +from ali_speech.callbacks import SpeechRecognizerCallback +from ali_speech.constant import ASRFormat +from ali_speech.constant import ASRSampleRate + + +class MyCallback(SpeechRecognizerCallback): + """ + 构造函数的参数没有要求,可根据需要设置添加 + 示例中的name参数可作为待识别的音频文件名,用于在多线程中进行区分 + """ + def __init__(self, name='default'): + self._name = name + + def on_started(self, message): + print('MyCallback.OnRecognitionStarted: %s' % message) + + def on_result_changed(self, message): + print('MyCallback.OnRecognitionResultChanged: file: %s, task_id: %s, result: %s' % ( + self._name, message['header']['task_id'], message['payload']['result'])) + + def on_completed(self, message): + print('MyCallback.OnRecognitionCompleted: file: %s, task_id:%s, result:%s' % ( + self._name, message['header']['task_id'], message['payload']['result'])) + + def on_task_failed(self, message): + print('MyCallback.OnRecognitionTaskFailed: %s' % message) + + def on_channel_closed(self): + print('MyCallback.OnRecognitionChannelClosed') + + +def process(client, appkey, token): + audio_name = 'nls-sample-16k.wav' + callback = MyCallback(audio_name) + recognizer = client.create_recognizer(callback) + recognizer.set_appkey(appkey) + recognizer.set_token(token) + recognizer.set_format(ASRFormat.PCM) + recognizer.set_sample_rate(ASRSampleRate.SAMPLE_RATE_16K) + recognizer.set_enable_intermediate_result(False) + recognizer.set_enable_punctuation_prediction(True) + recognizer.set_enable_inverse_text_normalization(True) + + try: + ret = recognizer.start() + if ret < 0: + return ret + + print('sending audio...') + with open(audio_name, 'rb') as f: + audio = f.read(3200) + while audio: + ret = recognizer.send(audio) + if ret < 0: + break + time.sleep(0.1) + audio = f.read(3200) + + recognizer.stop() + except Exception as e: + print(e) + finally: + recognizer.close() + + +def process_multithread(client, appkey, token, number): + thread_list = [] + for i in range(0, number): + thread = threading.Thread(target=process, args=(client, appkey, token)) + thread_list.append(thread) + thread.start() + + for thread in thread_list: + thread.join() + + +if __name__ == "__main__": + client = ali_speech.NlsClient() + # 设置输出日志信息的级别:DEBUG、INFO、WARNING、ERROR + client.set_log_level('INFO') + + appkey = '您的appkey' + token = '您的Token' + + process(client, appkey, token) + + # 多线程示例 + # process_multithread(client, appkey, token, 10) + + + + diff --git a/安装指南/alibabacloud-nls-python-sdk/speech_synthesizer_demo.py b/安装指南/alibabacloud-nls-python-sdk/speech_synthesizer_demo.py new file mode 100644 index 0000000..bd56f40 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/speech_synthesizer_demo.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import threading +import ali_speech +from ali_speech.callbacks import SpeechSynthesizerCallback +from ali_speech.constant import TTSFormat +from ali_speech.constant import TTSSampleRate + + +class MyCallback(SpeechSynthesizerCallback): + # 参数name用于指定保存音频的文件 + def __init__(self, name): + self._name = name + self._fout = open(name, 'wb') + + def on_binary_data_received(self, raw): + print('MyCallback.on_binary_data_received: %s' % len(raw)) + self._fout.write(raw) + + def on_completed(self, message): + print('MyCallback.OnRecognitionCompleted: %s' % message) + self._fout.close() + + def on_task_failed(self, message): + print('MyCallback.OnRecognitionTaskFailed-task_id:%s, status_text:%s' % ( + message['header']['task_id'], message['header']['status_text'])) + self._fout.close() + + def on_channel_closed(self): + print('MyCallback.OnRecognitionChannelClosed') + + +def process(client, appkey, token, text, audio_name): + callback = MyCallback(audio_name) + synthesizer = client.create_synthesizer(callback) + synthesizer.set_appkey(appkey) + synthesizer.set_token(token) + synthesizer.set_voice('xiaoyun') + synthesizer.set_text(text) + synthesizer.set_format(TTSFormat.WAV) + synthesizer.set_sample_rate(TTSSampleRate.SAMPLE_RATE_16K) + synthesizer.set_volume(50) + synthesizer.set_speech_rate(0) + synthesizer.set_pitch_rate(0) + + try: + ret = synthesizer.start() + if ret < 0: + return ret + + synthesizer.wait_completed() + except Exception as e: + print(e) + finally: + synthesizer.close() + + +def process_multithread(client, appkey, token, number): + thread_list = [] + for i in range(0, number): + text = "这是线程" + str(i) + "的合成。" + audio_name = "sy_audio_" + str(i) + ".wav" + thread = threading.Thread(target=process, args=(client, appkey, token, text, audio_name)) + thread_list.append(thread) + thread.start() + + for thread in thread_list: + thread.join() + + +if __name__ == "__main__": + client = ali_speech.NlsClient() + # 设置输出日志信息的级别:DEBUG、INFO、WARNING、ERROR + client.set_log_level('INFO') + + appkey = '您的appkey' + token = '您的token' + + text = "今天是周一,天气挺好的。" + audio_name = 'sy_audio.wav' + process(client, appkey, token, text, audio_name) + + # 多线程示例 + # process_multithread(client, appkey, token, 10) + + + + + diff --git a/安装指南/alibabacloud-nls-python-sdk/speech_transcriber_demo.py b/安装指南/alibabacloud-nls-python-sdk/speech_transcriber_demo.py new file mode 100644 index 0000000..7142ce2 --- /dev/null +++ b/安装指南/alibabacloud-nls-python-sdk/speech_transcriber_demo.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- + +""" + * Copyright 2015 Alibaba Group Holding Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +""" + +import os +import time +import threading +import ali_speech +from ali_speech.callbacks import SpeechTranscriberCallback +from ali_speech.constant import ASRFormat +from ali_speech.constant import ASRSampleRate + + +class MyCallback(SpeechTranscriberCallback): + """ + 构造函数的参数没有要求,可根据需要设置添加 + 示例中的name参数可作为待识别的音频文件名,用于在多线程中进行区分 + """ + def __init__(self, name='default'): + self._name = name + + def on_started(self, message): + print('MyCallback.OnRecognitionStarted: %s' % message) + + def on_result_changed(self, message): + print('MyCallback.OnRecognitionResultChanged: file: %s, task_id: %s, result: %s' % ( + self._name, message['header']['task_id'], message['payload']['result'])) + + def on_sentence_begin(self, message): + print('MyCallback.on_sentence_begin: file: %s, task_id: %s, sentence_id: %s, time: %s' % ( + self._name, message['header']['task_id'], message['payload']['index'], message['payload']['time'])) + + def on_sentence_end(self, message): + print('MyCallback.on_sentence_end: file: %s, task_id: %s, sentence_id: %s, time: %s, result: %s' % ( + self._name, + message['header']['task_id'], message['payload']['index'], + message['payload']['time'], message['payload']['result'])) + + def on_completed(self, message): + print('MyCallback.OnRecognitionCompleted: %s' % message) + + def on_task_failed(self, message): + print('MyCallback.OnRecognitionTaskFailed-task_id:%s, status_text:%s' % ( + message['header']['task_id'], message['header']['status_text'])) + + def on_channel_closed(self): + print('MyCallback.OnRecognitionChannelClosed') + + +def process(client, appkey, token): + audio_name = 'nls-sample-16k.wav' + callback = MyCallback(audio_name) + transcriber = client.create_transcriber(callback) + transcriber.set_appkey(appkey) + transcriber.set_token(token) + transcriber.set_format(ASRFormat.PCM) + transcriber.set_sample_rate(ASRSampleRate.SAMPLE_RATE_16K) + transcriber.set_enable_intermediate_result(False) + transcriber.set_enable_punctuation_prediction(True) + transcriber.set_enable_inverse_text_normalization(True) + + try: + ret = transcriber.start() + if ret < 0: + return ret + + print('sending audio...') + with open(audio_name, 'rb') as f: + audio = f.read(3200) + while audio: + ret = transcriber.send(audio) + if ret < 0: + break + time.sleep(0.1) + audio = f.read(3200) + + transcriber.stop() + except Exception as e: + print(e) + finally: + transcriber.close() + + +def process_multithread(client, appkey, token, number): + thread_list = [] + for i in range(0, number): + thread = threading.Thread(target=process, args=(client, appkey, token)) + thread_list.append(thread) + thread.start() + + for thread in thread_list: + thread.join() + + +if __name__ == "__main__": + client = ali_speech.NlsClient() + # 设置输出日志信息的级别:DEBUG、INFO、WARNING、ERROR + client.set_log_level('INFO') + + appkey = '您的appkey' + token = '您的Token' + + process(client, appkey, token) + + # 多线程示例 + # process_multithread(client, appkey, token, 10) + + diff --git a/安装指南/requirements.txt b/安装指南/requirements.txt new file mode 100644 index 0000000..71cf397 --- /dev/null +++ b/安装指南/requirements.txt @@ -0,0 +1,5 @@ +setuptools +pyaudio +keyboard +aliyunsdkcore +configparser \ No newline at end of file diff --git a/安装指南/安装指南.md b/安装指南/安装指南.md new file mode 100644 index 0000000..3ca4b61 --- /dev/null +++ b/安装指南/安装指南.md @@ -0,0 +1,48 @@ +## 安装依赖 + +先确保安装了 python + +然后打开命令行窗口,切换到本文件夹,用以下命令安装依赖: + +``` +pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple +pip install setuptools keyboard aliyunsdkcore configparser +cd alibabacloud-nls-python-sdk +python setup.py bdist_egg +python setup.py install +``` + +此外,还有一个依赖 `pyaudio` 不是太好安装,需要先到 [这个链接](https://www.lfd.uci.edu/~gohlke/pythonlibs) 下载 pyaudio 对应版本的 whl 文件。例如,我安装的是 python3.7 64位版本,就下载 `PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl` ,放到本文件夹,用 + +``` +pip install PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl +``` + +安装好 pyaudio。(为了方便,作者已经将 python3.6 到 3.9 的 whl 文件下载到本文件夹,根据版本选择安装即可) + +## API 配置 + +### 开通服务 + +你需要先到阿云开发者控制台开通 **RAM访问控制** ,进入 **RAM访问控制** 的控制台,新建一个用户,记下它的 **accessID**、**accessKey**,然后再为它添加 **管理智能语音交互(NLS)** 的权限。 + +接下来开通 **智能语音交互** 服务,新建一个项目: + +- 类别:非电话 +- 分类:通用 +- 场景:中文普通话 或 其它语言(想识别哪个语言就用哪个) + +发布上线,再记下这个项目的 **appkey** + +### 填写 API + +用文本编辑器打开项目主目录的 `run.py` 编辑,可以看到: + +```python +""" 在这里填写你的 API 设置 """ +accessID = "xxxxxxxxxxxxxxxxxxxxxxxx" +accessKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +appkey = 'xxxxxxxxxxxxxxxx' +``` + +将你在阿里云的 **accessID**、**accessKey**、**appkey** 分别填入,保存。 \ No newline at end of file