2375浏览
查看: 2375|回复: 3

[项目] 【2020】用虚谷号打造一个智能语音助理

[复制链接]
正月初五,国内冠状病毒肺炎形式严峻,相应国家号召,继续在家学习。
在论坛里多次看到有老师发古德微的树莓派作品,咱虚谷号用户肯定也要有所表示。
今天和大家分享一个用虚谷号打造的一个智能语音助理。

一、简介
主要实现如下功能:
  • 智能语音识别,作为语音助手当然是必须项了,为了应景,这里用“抗击肺炎”作为唤醒词。
  • 基于思知AI机器人开放平台的智能语义解析
  • 实现论坛自动签到。
  • 智能获取论坛最新发帖文章。


因为虚谷号只有 micro hdmi,没有3.5mm的音频输出口,而我没有 micro hdmi的线,
所以声音的输出我用了蓝牙音箱
但是因为虚谷号系统版本的原因,对于蓝牙音箱的声音输入又不支持,手头又没有麦克风,
所以声音的输入我用了带有录音功能的摄像头
,心好累。。。
设备一览图:
【2020】用虚谷号打造一个智能语音助理图1

二、实现解析:
1.声音的获取主要是用pyaudio库录音,并用wave库保存为 wav 格式,这两个库虚谷号在最新固件里已内置。
主要用rec函数来处理:
[mw_shl_code=python,false]def rec(file_name='xuguhao.wav'):
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    print("开始录音,请说话...")
    frames = []
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
    print("录音结束!")
    stream.stop_stream()
    stream.close()
    p.terminate()
    wf = wave.open(file_name, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()
    return file_name[/mw_shl_code]

2.语音识别用了百度的在线语音识别功能:

[mw_shl_code=python,false]""" 你的 APPID AK SK """
APP_ID = ""
API_KEY = ""
SECRET_KEY = ""
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

def audio_to_text(wav_file):
    with open(wav_file, 'rb') as fp:
        file_context = fp.read()
    print("开始识别...")
    # 识别本地文件
    res = client.asr(file_context, 'wav', 16000, {
        'dev_pid': 1536,
    })
    res_str = res.get("result")[0]
    return res_str[/mw_shl_code]

其中 百度语音的 aip 库,虚谷号最新固件已内置。
app_id需要自己注册获得,基于篇幅原因这里不展开讲了。
如有需要请自行百度。

3.文字转语音(TTS)也是用的百度接口,

[mw_shl_code=python,false]def text_to_speech(text):
    global client
    result = client.synthesis(text, 'zh', 1, {'vol': 5,})
    if not isinstance(result, dict):
        with open('return.mp3', 'wb') as f:
            f.write(result)
    mplayer('return.mp3')[/mw_shl_code]

4.声音播放输出用了mplayer 播放器,如有需要请在虚谷号里自行安装:
[mw_shl_code=shell,false]sudo apt-get install mplayer[/mw_shl_code]

5.论坛的签到在这里:
[mw_shl_code=python,false]def df_sign(req_session, formhash):
    url_sign = 'https://mc.dfrobot.com.cn/plugin.php?id=dsu_paulsign%3Asign&operation=qiandao&infloat=1&sign_as=1&inajax=1'
    payload = 'formhash={}&qdxq=yl&qdmode=2&todaysay=&fastreply=0'.format(formhash)
    response = req_session.post(url_sign, payload, headers=headers)
    if '成功' in response.text:
        print('签到成功')
        return 0
    elif '已经签到' in response.text:
        print('你已经签到')
        return 1
    else:
        print('未知错误')
        return 2[/mw_shl_code]

因为论坛的cookies时间很短,所以每次签到,需要先登录,登录函数如下:
[mw_shl_code=python,false]def df_login():
    url_first = 'https://mc.dfrobot.com.cn/member.php?mod=logging&action=login'
    url_dflogin = 'https://login.dfrobot.com.cn/member/auth'
    req_session = requests.session()
    response = req_session.get(url_first)
    response = req_session.post(
        url=url_dflogin,
        data=payload,
        headers=headers,)
    formhash_text = response.text
    pre_find = 'name="formhash" value="'
    index_formhash = formhash_text.find(pre_find)
    if index_formhash > 0:
        formhash = formhash_text[index_formhash+len(pre_find):index_formhash+len(pre_find)+8]
        return req_session, formhash
    else:
        return[/mw_shl_code]

6.论坛文章的获取:
[mw_shl_code=python,false]def get_new_topic(req_session):
    global last_time
    url_new_topic = 'https://mc.dfrobot.com.cn/forum_api.php?act=ajax_forum&module=new&page=1'
    response = req_session.get(url_new_topic, headers=headers).json()
    ret_topic = []
    if not response:
        return ()
    for value in response:
        if value['publish'] > last_time:
            ret_topic.append(value['title'])
        else:
            break
        last_time = response[1]['publish']
    return tuple(ret_topic)[/mw_shl_code]

7.最后,语音助理的核心用了
思知 AI机器人开放平台,https://console.ownthink.com
本来想用tuling123的接口,可是现在不手持身份证进行认证审核不给权限。不能忍,就不用了。

[mw_shl_code=python,false]                    sess = requests.get('https://api.ownthink.com/bot?appid={}&userid=kylin&spoken={}'.format(sess_app_id, value))
                    answer = sess.json()
                    value = answer['data']['info']['text'][/mw_shl_code]
接口比较简单,直接 get一下就好了,如有需要自己看官网文档,这里不展开了。

三、完整代码

下载附件voice_assisstant.zip

四、成功视频



且歌且行  中级技师

发表于 2020-2-15 21:19:26

好听话的机器人,脾气也好。
回复

使用道具 举报

kylinpoet  初级技神
 楼主|

发表于 2020-2-18 06:18:25

多谢分享,学习了。
回复

使用道具 举报

gada888  版主

发表于 2020-2-21 16:40:02

不错的分享
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail