亚马逊AWS官方博客
使用Python语言实现Transcribe Streaming的websocket协议
概述
Amazon Transcribe是自动语音识别(ASR)服务,可让开发人员轻松地为其应用程序添加语音转文本功能,Transcribe支持文件和流式Streaming的两种音频输入方式,Transcribe Streaming可以应用在会议记录,语音控制交互,语言实时翻译等场景,Streaming方式支持HTTP/2和WebSocket两种协议。本文介绍使用Python语言实现Transcribe Streaming的WebSocket协议。
Streaming transcription 接口介绍
Streaming transcription 接口可以接收音频流并且实时转换为文字,然后将结果返回客户端,同时返回数据中包含partial值,用来标示句子是否结束。
Streaming的数据是被编码的,由prelude和data组成。编码格式详见:https://docs.aws.amazon.com/transcribe/latest/dg/event-stream.html
Python语言的实现过程和示例
Python示例程序的运行环境是Python 3.7.9版本。
- 添加IAM Policy到你使用到的IAM user
- 安装Python的程序包
Python示例程序需要安装三个程序包websocket-client,boto3和amazon_transcribe;其中boto3是AWS SDK for Python,amazon_transcribe是Amazon Transcribe Streaming SDK,这两个SDK简化了和Amazon Transcribe Service的集成过程。amazon_transcribe的详细说明见:https://github.com/awslabs/amazon-transcribe-streaming-sdk
安装程序包的命令:
Python程序的import部分:
- 创建签名URL的函数
URL签名说明详见:https://docs.aws.amazon.com/transcribe/latest/dg/websocket.html#websocket-url
Python的实现示例:
下列代码中主体函数是create_pre_signed_url,它将生成访问Streaming transcription 接口的URL,其中包括必要的参数和签名,它需要传入4个参数:
- 参数region代表将要调用的Amazon Web Service Region。可查看Streaming支持的region,详见Docs链接的Amazon Transcribe Streaming部分(https://docs.aws.amazon.com/general/latest/gr/transcribe.html)
- 参数language_code, media_encoding, sample_rate是stream-transcription-websocket接口的参数,定义见https://docs.aws.amazon.com/transcribe/latest/dg/websocket.html#websocket-url
- 编写main函数
下面代码中的loop_receiving和send_data函数,作用分别是从Amazon Transcribe Service接收消息,和向Amazon Transcribe Service发送消息。
- 编写loop_receiving函数
该函数位于main函数上方。它将接收Amazon Transcribe Streaming Service的返回数据,并且打印出来。
- 编写send_data函数
该函数位于main函数上方。它将发送音频数据到Amazon Transcribe Streaming Service。其中testFile变量是测试音频文件地址,测试音频为pem格式,英语,采样率为16000。
结论
在这篇文章中,介绍了如何使用Python语言实现Transcribe Streaming的WebSocket协议,提供了Python的例子供参考,包括签名URL、数据编码、数据流的发送和接收等部分。完整代码见:https://github.com/xuemark/transcribe/blob/master/transcribe_streaming_websocket.py
参考资料
- https://docs.aws.amazon.com/transcribe/latest/dg/what-is-transcribe.html
- https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html
- https://docs.aws.amazon.com/transcribe/latest/dg/websocket.html
- https://aws.amazon.com/transcribe
- https://github.com/awslabs/amazon-transcribe-streaming-sdk