使用百度ai接口加图灵机器人完成简单web版语音对话
app文件
from flask import Flask, request, render_template, jsonify, send_file
from uuid import uuid4
import os
import asr_test app = Flask(__name__)
app.debug = True @app.route('/')
def index():
return render_template('index.html') @app.route('/uploader', methods=['POST'])
def uploader():
file = request.files.get('reco')
file_name = os.path.join('audio', f'{uuid4()}.wav')
file.save(file_name)
ret_filename = asr_test.my_ai(file_name)
print(ret_filename)
return jsonify({'filename': ret_filename}) @app.route('/get_audio/<filename>')
def get_audio(filename):
file = os.path.join('audio', filename)
return send_file(file) if __name__ == '__main__':
app.run('0.0.0.0', 5000)
调用百度语音识别与语音合成接口,把传来的语言识别成文字,并调用下面的相似度接口,返回回答的文字,然后利用语音合成返回回答
from aip import AipSpeech
import os
from my_npl import get_score
from uuid import uuid4 """ 你的 APPID AK SK """
APP_ID = '******'
API_KEY = '******'
SECRET_KEY = '******' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) # 读取文件
def get_file_content(filePath):
any2pcm_str = f"ffmpeg -y -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm"
os.system(any2pcm_str)
with open(f"{filePath}.pcm", 'rb') as fp:
return fp.read() # 识别本地文件
def my_ai(file):
res = client.asr(get_file_content(file), 'pcm', 16000, {
'dev_pid': 1536,
}) print(res.get('result'))
print(res)
question = res.get('result')[0]
req = get_score(question) req = client.synthesis(req, 'zh', 1, {
'vol': 5,
'pit': 5,
'spd': 4,
"per": 4
}) # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(req, dict):
ret_filename = f'{uuid4()}.mp3'
new_filename = os.path.join("audio", ret_filename)
with open(new_filename, 'wb') as f:
f.write(req)
return ret_filename
调用百度ai自然语言中的短文本相似度接口,使相似的问题得到相同的答案
from aip import AipNlp
from mytuling import to_tuling """ 你的 APPID AK SK """
APP_ID = '***'
API_KEY = '***'
SECRET_KEY = '***' client = AipNlp(APP_ID, API_KEY, SECRET_KEY) def get_score(Q):
if client.simnet(Q, '你叫什么名字').get('score') > 0.7:
return '我是大名鼎鼎的小王吧'
elif client.simnet(Q, '你今年几岁呀').get('score') > 0.7:
return '我今年已经1112岁啦'
else:
return to_tuling(Q)
调用图灵接口完成未设定问答的
import requests
tuling_url = 'http://openapi.tuling123.com/openapi/api/v2'
data = {"reqType": 0,
"perception": {
"inputText": {
"text": ""
}
}
,
"userInfo": {
"apiKey": "***",
"userId": "***"
}
}
def to_tuling(Q):
data["perception"]["inputText"]['text'] = Q
a = requests.post(url=tuling_url, json=data)
res = a.json()
print(res)
return res.get("results")[0].get("values").get("text")
简单前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<audio src="" autoplay controls id="player"></audio>
<p>
<button onclick="start_reco()">开始录音</button>
</p>
<p>
<button onclick="stop_reco()">停止录音</button>
</p> </body>
<script src="/static/Recorder.js"></script>
<script src="/static/jQuery3.1.1.js"></script>
<script type="text/javascript">
var serv = "http://127.0.0.1:5000";
var audio_serv = serv + "/get_audio/";
var audio_context = new AudioContext();
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia); navigator.getUserMedia({audio: true}, create_stream, function (err) {
console.log(err)
}); function create_stream(user_media) {
var stream_input = audio_context.createMediaStreamSource(user_media);
reco = new Recorder(stream_input);
} function start_reco() {
reco.record();
} function stop_reco() {
reco.stop();
get_audio();
reco.clear();
} function get_audio() {
reco.exportWAV(function (wav_file) {
// wav_file 音频文件 Blob("wav","context")
console.log(wav_file);
var formdata = new FormData();
formdata.append("reco", wav_file);
$.ajax({
url: serv + "/uploader",
type: 'post',
processData: false,
contentType: false,
data: formdata,
dataType: 'json',
success: function (data) {
document.getElementById("player").src = audio_serv + data.filename;
}
}
);
})
}
</script>
</html>
前端页面
使用百度ai接口加图灵机器人完成简单web版语音对话的更多相关文章
- 人工智能-调百度AI接口+图灵机器人
1.登陆百度AI的官网 1.注册:没有账号注册 2.创建应用 3.创建应用 4.查看应用的ID 5.Python代码 from aip import AipSpeech APP_ID = " ...
- 基于百度ai,图灵机器人,Flask 实现的网站语音智能问答
准备以下模块中的函数 from aip import AipSpeech import time import os import requests APP_ID = '15420654' API_K ...
- [初识]使用百度AI接口,图灵机器人实现简单语音对话
一.准备 1.百度ai开放平台提供了优质的接口资源https://ai.baidu.com/ (基本免费) 2.在语音识别的接口中, 对中文来说, 讯飞的接口是很好的选择https://www.xf ...
- 百度ai 接口调用
1.百度智能云 2.右上角 管理控制台 3.左上角产品服务 选择应用 4.创建应用 5.应用详情下面的查看文档 6.选择pythonSDK 查看下面快速入门文档 和 接口说明文档. 7.按步骤写 ...
- 基于flask和百度AI接口实现前后端的语音交互
话不多说,直接怼代码,有不懂的,可以留言 简单的实现,前后端的语音交互. import os from uuid import uuid4 from aip import AipSpeech from ...
- django--调用百度AI接口实现人脸注册登录
面部识别----考勤打卡.注册登录.面部支付等等...感觉很高大上,又很方便,下面用python中的框架--django完成一个注册登录的功能,调用百度AI的接口,面部识别在网上也有好多教程,可以自己 ...
- 2019-02-15 python接口图灵机器人(简单好玩)
import requests import json def Run(text): url = "http://openapi.tuling123.com/openapi/api/v2&q ...
- WebApiClientCore简约调用百度AI接口
WebApiClientCore WebApiClient.JIT/AOT的netcore版本,集高性能高可扩展性于一体的声明式http客户端库,特别适用于微服务的restful资源请求,也适用于各种 ...
- Python人工智能-基于百度AI接口
参考百度AI官网:http://ai.baidu.com/ 准备工作: 支持Python版本:2.7.+ ,3.+ 安装使用Python SDK有如下方式 >如果已经安装了pip,执行 pip ...
随机推荐
- 【洛谷 P3690】 【模板】Link Cut Tree (动态树)
题目链接 \(RT\). FlashHu巨佬的博客 #include <cstdio> #define R register int #define I inline void #defi ...
- Lithium中关键特性更新
Lithium中关键特性更新 1. Lithium特性更新概述 Lithium相对于Helium更新特性共27项,其中原有特性提升或增强13项,新增特性14项,如下表所示 特性类型 相对于Helium ...
- jq时间日期插件的使用-datetimepicker
分三步 首先引入各种包 然后搞哥容器用id 然后加入一段js 实例: 下载:http://files.cnblogs.com/files/wordblog/datetimepicker-maste ...
- fileIO和OS操作文件和目录
1.FileIO操作文件 # 文件IO,读取文件和创建文件 # 1.读取键盘输入 x=input("please input number") print("您输入的是& ...
- 面试中关于Java虚拟机(jvm)的问题看这篇就够了
最近看书的过程中整理了一些面试题,面试题以及答案都在我的文章中有所提到,希望你能在以问题为导向的过程中掌握虚拟机的核心知识.面试毕竟是面试,核心知识我们还是要掌握的,加油~~~ 下面是按jvm虚拟机知 ...
- 【Windows使用笔记】神舟笔记本的control center
首先,神船大法好. 然后,因为我的船风扇声音有点大啊,在实验室感觉就很吵,但是它的背板温度又不是很高,所以想设置下风扇的启动. 所以需要用到神船自带的control center软件. 长这样. 应该 ...
- 002利用zabbix监控某个目录大小
近期,因为JMS的消息堆积导致ApacheMQ频率故障(消息没有被消费掉,导致其数据库达到1.2G,JMS此时直接挂掉),很是郁闷!刚好自 己在研究zabbix.既然zabbix如此强大,那么它可以监 ...
- php 7.3.3安装问题记录
1.checking for libzip... not foundconfigure: error: Please reinstall the libzip distribution 参考:http ...
- ASP .NET CORE MVC 部署Windows 系统上 IIS具体步骤---.Net Core 部署到 IIS位系统中的步骤
一.IIS 配置 启用 Web 服务器 (IIS) 角色并建立角色服务. 1.Windows Ddesktop 桌面操作系统(win7及更高版本) 导航到“控制面板” > “程序” > “ ...
- PlantUML——2.中文乱码及解决
关于中文 参见: http://plantuml.sourceforge.net/unicode.html 问题描述 第一步:创建demo03.txt描述文档: @startuml Alice - ...