4.AI实时语音转录——Flask从制作到起飞,零件级颗粒度制造

1. 包管理

重新生成项目依赖文件

$ pip install pipreqs
$ pipreqs <app_path> --force

更新 virtualenv 的 packages

$ virtualenv --clear venv
$ pip install -r requirements.txt

目前还没有特别好的自动包管理工具,pipreqs 会遗漏一些 package,pip freeze 不能很好的区分 package 和 package dependency,比较推荐手动管理 requirements.txt。
本项目当前的 requirements.txt 的手动管理版本是:

flask==1.0.2
baidu-aip==2.2.11.0
pytest==4.1.1
coverage==4.5.2
pytest-cov==2.6.1

2.实时语音录入

为了实现实时语音转文本的功能,需要一个工具启动本地的录音功能,并将音频数据流上传到百度。
本文使用开源 package sounddevice,首先安装 package,因为依赖 numpy 的 array 功能,所以同时要安装 numpy。

$ pip install soundedevice
$ pip install numpy

此时 requirements.txt 为:

flask==1.0.2
baidu-aip==2.2.11.0
pytest==4.1.1
coverage==4.5.2
pytest-cov==2.6.1
sounddevice==0.3.12
numpy==1.16.0

3.View

新开一个路由给实时语音转文本功能,在 server/AI/view.py 中加入一个 view 函数

@blueprint.route('/online_asr')
def online_asr():
    # online_asr 方法还未创建,返回的是语音转文本的结果 list,所以用了 pop() 方法简单获得转录结果
    rsp = controller.online_asr().pop()

    return rsp

4.Controller

新开一个 controller 方法实现实时语音转文本功能,为了简化功能,这里先实现固定时长的录音,未来会由前端页面传入录音时长增加交互性。在 server/AI/controller.py 中写相应方法。
随着功能的增多,代码需要模块化,这里第一个遇到的问题就是获得百度语音转文本的 client,因为上一篇文章的录音文件语音转文本和这里的实时语音转文本都需要这个功能。依照 write once, use eveywhere的原则,抽象出一个方法

def get_baidu_client():
    """
    set up baidu asr client
    :return:
    """
    # Baidu Cloud AI
    # 从项目 config 中获得百度语音转文本相应的控制参数
    app_id = current_app.config['APP_ID']
    api_key = current_app.config['API_KEY']
    secret_key = current_app.config['SECRET_KEY']

    # 创建交互的 client
    client = AipSpeech(app_id, api_key, secret_key)

    return client

接着实现实时语音转文本功能

def online_asr():
    """
    online automatic speech recognition
    :return:
    """
    client = get_baidu_client()

    duration = 10  # set record time as 10s, will be transferred from frontend in the future
    fs = 44100  # sampling frequency, in most cases this will be 44100 or 48000 frames per second
    ndarray_data = sd.rec(int(duration * fs), samplerate=fs, channels=2)
    bytes_data = ndarray_data.tobytes()

    rsp = client.asr(bytes_data)

    return rsp['result']

5.结果

实现 demo 如下图


4078144-620d15191edf2ac3.png
image

相关链接
源码
3.AI语音转文本——Flask从制作到起飞,零件级颗粒度制造
2.CI(Continuous Integration)——Flask从制作到起飞,零件级颗粒度制造
1.初始化——Flask从制作到起飞,零件级颗粒度制造

猜你喜欢

转载自blog.csdn.net/weixin_34014555/article/details/87140015