使用百度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 ...
随机推荐
- 基于canvas的图片编辑合成器
在我们日常的前端开发中,经常会要给服务器上传图片,但是局限很大,图片只能是已有的,假设我想把多张图片合成一张上传就需要借助图片编辑器了,但是现在我们有了canvas合成就简单多了 首先我们看图片编辑器 ...
- vue--------脚手架vue-cli搭建
今天在看公司的项目的时候,用到的是Vue框架,哈哈,Vue已经火好久了,想必大家也晓得哈,这里宝宝就不瞎渣渣了~ 由于宝宝已经三个月木有看过代码了,所以对新公司的很多的架构和代码都是懵逼的,再加上宝宝 ...
- flask插件系列之flask_cors跨域请求
前后端分离在开发调试阶段本地的flask测试服务器需要允许跨域访问,简单解决办法有二: 使用flask_cors包 安装 pip install flask_cors 初始化的时候加载配置,这样就可以 ...
- SVM问题再理解与分析——我的角度
SVM问题再理解与分析--我的角度 欢迎关注我的博客:http://www.cnblogs.com/xujianqing/ 支持向量机问题 问题先按照几何间隔最大化的原则引出他的问题为 上面的约束条件 ...
- Zabbix3.0源码安装
环境:nginx1.6.3 php-5.6.22 mysql-5.5.49 请参考前面的博文自行搭建 安装依赖并创建用户 [root@test88 ~]# yum install -y libxml2 ...
- Dagger:快速的依赖注入for 安卓&Java
Dagger:快速的依赖注入for 安卓&Java 2014年5月8日 星期四 15:29 官网: http://square.github.io/dagger/ GitHub: https: ...
- python的scrapy框架
scrapy是python中数据抓取的框架.简单的逻辑如下所示 scrapy的结构如图所示,包括scrapy engine.scheduler.downloader.spider.item pipel ...
- django 解决csrf跨域问题
1.中间件代码 [root@linux-node01 mysite]# tree middlewares middlewares ├── base.py ├── base.pyc ├── cors.p ...
- linux中使用vim编译C++程序
Vi三种模式详解 命令行模式 (command mode/一般模式) 任何时候,不管用户处于何种模式,只要按一下“ESC”键,即可使Vi进入命令行模式:我们在shell环境(提示符为$)下输入启动Vi ...
- jquery datatable的详细用法
1,首先需要引用下面两个文件 <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css ...