使用百度大脑构建一个闲聊机器人

  • 使用的库
  • 录下你所说的内容
  • 调用百度语音识别系统将录音文件转化为文字
  • 调用百度UINIT进行回答
  • 在主函数中检测键盘输入

代码上传到了Github
主要参考了这篇博客

使用的库

from aip import AipSpeech
import json
import win32com.client
import urllib.request
import pyaudio
import threading
import wave
from pynput import keyboard
import time

录下你所说的内容

class Recorder():def __init__(self, chunk=1024, channels=1, rate=16000):self.CHUNK = chunkself.FORMAT = pyaudio.paInt16self.CHANNELS = channelsself.RATE = rateself._running = Trueself._frames = []def start(self):threading._start_new_thread(self.__recording, ())def __recording(self):self._running = True# self._frames = []p = pyaudio.PyAudio()stream = p.open(format=self.FORMAT,channels=self.CHANNELS,rate=self.RATE,input=True,frames_per_buffer=self.CHUNK)while (self._running):data = stream.read(self.CHUNK)self._frames.append(data)stream.stop_stream()stream.close()p.terminate()def stop(self):self._running = Falsetime.sleep(0.1)# sleep是为了保证def stop结束前录音线程也结束def save(self, filename):p = pyaudio.PyAudio()if not filename.endswith('.wav'):filename = filename + '.wav'wf = wave.open(filename, 'wb')wf.setnchannels(self.CHANNELS)wf.setsampwidth(p.get_sample_size(self.FORMAT))wf.setframerate(self.RATE)wf.writeframes(b''.join(self._frames))wf.close()self._frames.clear()

采样频率rate过高或者过低都会产生KeyError(无法识别所说的内容),在这里我们设置为16000。

调用百度语音识别系统将录音文件转化为文字

# 音频文件转文字:采用百度的语音识别python-SDK。网址:https://ai.baidu.com/tech/speech
# 百度语音识别API配置参数
APP_ID = 'your AppId'
API_KEY = 'your ApiKey'
SECRET_KEY = 'your SecretKey'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
path = 'voices/myvoices.wav# 将语音转文本
def listen():# 读取录音文件with open(path, 'rb') as fp:voices = fp.read()try:# 参数dev_pid表示识别的语种result = client.asr(voices, 'wav', 16000, {'dev_pid': 1537, })result_text = result['result'][0]global numnum = num + 1print('Round {}:'.format(num))print('you said:', result_text)return result_textexcept KeyError:print('KeyError')speaker.Speak('我没有听清楚,请再说一遍...')return False

App Key、Secret Key等数据的获取参考这篇博客

调用百度UINIT进行回答

# 调用百度UNIT智能对话系统,网址:https://ai.baidu.com/unit/
# API配置参数
headers = {'Content-Type': 'application/json'}
access_token = 'your token'
url = 'https://aip.baidubce.com/rpc/2.0/unit/bot/chat?access_token=' + access_tokendef baidu_unit(text_words):post_data = "{\"bot_session\":\"\",\"log_id\":\"7758521\",\"request\":{\"bernard_level\":1, " \"\"client_session\":\"{\\\"client_results\\\":\\\"\\\", \\\"candidate_options\\\":[]}\"," \"\"query\":\"" + text_words + "\",\"query_info\":{\"asr_candidates\":[],\"source\":\"KEYBOARD\"," \"\"type\":\"TEXT\"},\"updates\":\"\",\"user_id\":\"UNIT_DEV_你的百度账号昵称\"}," \"\"bot_id\":\"71625\",\"version\":\"2.0\"}"request = urllib.request.Request(url, data=post_data.encode('utf-8'), headers=headers)response = urllib.request.urlopen(request)content = response.read().decode("utf-8")content = json.loads(content)resp = content['result']['response']['action_list'][0]['say']print('robot said:', resp)return resp

上述代码的post_data中需要更改的就是user_id,这里采用“UNIT_DEV_”+“你的百度账号昵称”的形式,除此之外便是bot_id,是你所要使用的技能ID,71625代表了闲聊技能,其他技能的编号可以通过访问百度UNIT——新建机器人——添加技能的方式来查询。

access_token则需要专门获取:

import urllib.request
import json# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=your AK&client_secret=your SK'
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
content = response.read()
content = json.loads(content)
if (content):print(content['access_token'])

注意这里的SK和AK与上面的不同,需要点击你刚才新建的机器人,选择“发布上线”——“获取Api Key/Secret Key”——创建应用,这里的AK和SK才是我们获取token所需要的。

在主函数中检测键盘输入

if __name__ == '__main__':num = 0rec = Recorder()print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')print('Press \'t\' to start the record, and press \'p\' to stop.\n''After that you only need to wait for the robot\'s response\n''You can quit at any time by pressing esc.')print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')with keyboard.Listener(on_press=on_press) as listener:listener.join()

函数on_press:

# 按下按键后的响应
def on_press(key):try:if key.char == 't':if not len(rec._frames) == 0:print('\nThe record has been going on, please check your command!')else:rec.start()print('\nRecording......')elif key.char == 'p':if len(rec._frames) == 0:print('\nThere is no data,please check your command!')else:rec.stop()rec.save('voices/myvoices.wav')print('\nWaiting for response......')rep_text = listen()if (rep_text):res_text = baidu_unit(rep_text)speaker.Speak(res_text)else:print('There is something wrong with the server, you can wait for a moment and try again.')except AttributeError:if key == keyboard.Key.esc:return False# return false 则with ... as ... 结构结束

运行效果:

D:\PycharmProjects\voiceDetect\venv\Scripts\python.exe D:/PycharmProjects/voiceDetect/main.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Press 't' to start the record, and press 'p' to stop.
After that you only need to wait for the robot's response
You can quit at any time by pressing esc.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~t
Recording......
t
The record has been going on, please check your command!
p
Waiting for response......
Round 2:
you said: 嗨,你好。
robot said: 你好啵啵啵
p
There is no data,please check your command!
t
Recording......
p
Waiting for response......
Round 3:
you said: 你叫什么名字?
robot said: 我怎么能说名字呢?There is no data,please check your command!
pt
Recording......
p
Waiting for response......
Round 4:
you said: 那你能说什么?
robot said: 不知道
t
Recording......
p
Waiting for response......
Round 5:
you said: 你是男是女?
robot said: 男。我的id让人错觉女
t
Recording......
p
Waiting for response......
Round 6:
you said: 你的ID是啥?
robot said: 啥意思
t
Recording......
p
Waiting for response......
Round 7:
you said: 我问你,你的ID是什么?
robot said: 我不知道。
t
Recording......
p
Waiting for response......
Round 8:
you said: 你是不是有病?
robot said: 绝对不是病
t
Recording......
p
Waiting for response......
Round 9:
you said: 那你就是知道。
robot said: 知道知道
t
Recording......
p
Waiting for response......
Round 10:
you said: 我说那你就是智障。
robot said: 打错了智商
t
Recording......
p
Waiting for response......
Round 11:
you said: 不是智商,是智障。
robot said: 不关智商问题
t
Recording......
p
Waiting for response......
Round 12:
you said: 你就是有病。
robot said: 请注意文明用语
t
Recording......
p
Waiting for response......
Round 13:
you said: 你有病,你有病,你有病。
robot said: 我又不是没病!Recording......
tp
Waiting for response......
Round 14:
you said: 你有什么病?
robot said: 没病啊
t
Recording......
p
Waiting for response......
Round 15:
you said: 说话前后矛盾,我看你就是知道。
robot said: 矛盾?
t
Recording......
p
Waiting for response......
Round 16:
you said: 你绝对是个真。
robot said: 必须真
t
Recording......
p
Waiting for response......
Round 17:
you said: 垃圾百度。
robot said: 百度尽全力变得更完美,希望你多多指教
t
Recording......
p
Waiting for response......
Round 18:
you said: 李彦宏去死吧!
robot said: 喂,你别乱说哦,小心警察蜀黍请你喝茶
t
Recording......
p
Waiting for response......
Round 19:
you said: 你绝对是百度的亲儿子。
robot said: 是亲儿子阿Process finished with exit code 0

使用百度大脑构建一个闲聊机器人相关推荐

  1. 如何用 Slack 和 Kubernetes 构建一个聊天机器人?| 附代码

    作者 | Alexander Kainz 译者 | 天道酬勤,责编 | Carol 出品 | AI科技大本营(ID:rgznai100) ChatOps可以让你使用基于聊天的接口来管理DevOps任务 ...

  2. php百度大脑,百度大脑和图灵机器人制作一个简单的自动聊天机器人【PHP代码】...

    可以和机器人聊天 文字发送消息 网页进行语音回复 这里主要用到了两个接口 一个是百度大脑  用来实现语音合成 一个是图灵机器人用来实现自动聊天 以下是代码分两个版本 版本一是没有语音合成 版本二是加上 ...

  3. 直播实录|如何使用百度大脑EasyDL构建互联网内容安全方案?

    如何使用EasyDL构建互联网内容安全方案 时间:2020年6月2日 讲师:百度AI技术生态部高级产品经理 Nathan [直播回放] 如何使用EasyDL构建互联网内容安全方案:https://ww ...

  4. 使用Arduino Uno构建一个巡线机器人

    使用Arduino Uno构建一个巡线机器人 原文 MX 巡线机器人(**LFR)**是一种简单的自主引导机器人,它遵循在地面上绘制的线来检测白色表面上的暗线或黑暗表面上的白线.在本教程中,使用 Ar ...

  5. 从城市大脑到世界数字大脑 构建人类协同发展的超级智能平台

    作者:远望智库数字大脑研究院院长,中国科学院虚拟经济与数据科学研究中心研究组成员,南京财经大学教授  刘锋 (本文2021年12月发表于中国建设信息化) 一.世界数字大脑产生的背景 世界数字大脑与城市 ...

  6. 五大服务顺序_百度大脑5.0技术干货:详解飞桨五大优势,鸿鹄芯片架构细节

    智东西 文 | 心缘 智东西7月8日消息,近日,2019百度AI开发者大会在北京国家会议中心举行.在上午的主论坛中,百度CTO王海峰带来了软硬一体的AI大生产平台--百度大脑5.0,宣布百度飞桨与华为 ...

  7. 快速构建一个简单的对话+问答AI (上)

    文章目录 前言 part0 资源准备 基本功能 语料 停用词 问答 闲聊语料 获取 part01句的表达 表达 one-hot编码 词嵌入 大致原理 实现 简单版 复杂版 如何训练 转换后的形状 pa ...

  8. 百度大脑的燎原之势:强大成标配,更深得企业拥抱AI之心

    作者|震霆   出品|遇见人工智能        公众号|GOwithAI 是时候让那个刚刷屏的波士顿机器人成为过去式了. 之所以有这样的想法,只是因为今天发现一个AI应用. 不多说,先来先见识下. ...

  9. PaddleNLP通用信息抽取技术UIE【一】产业应用实例:信息抽取{实体关系抽取、中文分词、精准实体标。情感分析等}、文本纠错、问答系统、闲聊机器人、定制训练

    相关文章: 1.快递单中抽取关键信息[一]----基于BiGRU+CR+预训练的词向量优化 2.快递单信息抽取[二]基于ERNIE1.0至ErnieGram + CRF预训练模型 3.快递单信息抽取[ ...

最新文章

  1. [精]Odoo 8.0深入浅出开发教程-模块开发基础
  2. 使用python处理没有被Web用到的图片
  3. 在ASP.NET MVC中使用IIS级别的URL Rewrite
  4. 《深入C++对象模型》笔记
  5. 团队软件开发第一次冲刺(六)
  6. [算法总结] 二分查找
  7. java mousepress_Java线程原语弃用
  8. CodePlex关闭,建议迁移至GitHub
  9. cmake make
  10. pytorch 训练人脸精度不达标
  11. ul1977标准_UL1977标准连接器UL认证测试内容
  12. bbsmax mysql_mysql 语句case when
  13. QTableWidget设置Item不可编辑状态
  14. 希腊呼吁欧委会增加欧洲网络与信息安全管理局预算
  15. 光谱分辨率单位_【ENVI入门系列】16.基本光谱分析
  16. Intent详解及其用法
  17. viewModel生命周期
  18. iOS APP启动函数调用顺序~详解
  19. “{:02d}”.format(i)什么意思
  20. PCB上电源走线注意

热门文章

  1. FRP 内网穿透下载配置
  2. 西电机器学习简答题核心考点汇总(期末真题,教材西瓜书)
  3. 20210729-Codeforces Round #735 (Div. 2)
  4. Java面试自我介绍篇
  5. 手机打开html没有图片,网页看不到图片怎么办?图片打不开的解决办法
  6. Docker Engine 安装时遇到的坑
  7. stm32h7能跑linux,STM32H7榨干了Cortex-M7的最后一滴血
  8. VB.NET学习笔记:使用Random类生成随机数(不重复、数字、字母)
  9. tailwindcss使用教程
  10. man手册中文版设置