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版语音对话的更多相关文章

  1. 人工智能-调百度AI接口+图灵机器人

    1.登陆百度AI的官网 1.注册:没有账号注册 2.创建应用 3.创建应用 4.查看应用的ID 5.Python代码 from aip import AipSpeech APP_ID = " ...

  2. 基于百度ai,图灵机器人,Flask 实现的网站语音智能问答

    准备以下模块中的函数 from aip import AipSpeech import time import os import requests APP_ID = '15420654' API_K ...

  3. [初识]使用百度AI接口,图灵机器人实现简单语音对话

    一.准备 1.百度ai开放平台提供了优质的接口资源https://ai.baidu.com/  (基本免费) 2.在语音识别的接口中, 对中文来说, 讯飞的接口是很好的选择https://www.xf ...

  4. 百度ai 接口调用

    1.百度智能云 2.右上角 管理控制台 3.左上角产品服务 选择应用 4.创建应用 5.应用详情下面的查看文档 6.选择pythonSDK  查看下面快速入门文档  和  接口说明文档. 7.按步骤写 ...

  5. 基于flask和百度AI接口实现前后端的语音交互

    话不多说,直接怼代码,有不懂的,可以留言 简单的实现,前后端的语音交互. import os from uuid import uuid4 from aip import AipSpeech from ...

  6. django--调用百度AI接口实现人脸注册登录

    面部识别----考勤打卡.注册登录.面部支付等等...感觉很高大上,又很方便,下面用python中的框架--django完成一个注册登录的功能,调用百度AI的接口,面部识别在网上也有好多教程,可以自己 ...

  7. 2019-02-15 python接口图灵机器人(简单好玩)

    import requests import json def Run(text): url = "http://openapi.tuling123.com/openapi/api/v2&q ...

  8. WebApiClientCore简约调用百度AI接口

    WebApiClientCore WebApiClient.JIT/AOT的netcore版本,集高性能高可扩展性于一体的声明式http客户端库,特别适用于微服务的restful资源请求,也适用于各种 ...

  9. Python人工智能-基于百度AI接口

    参考百度AI官网:http://ai.baidu.com/ 准备工作: 支持Python版本:2.7.+ ,3.+ 安装使用Python SDK有如下方式 >如果已经安装了pip,执行 pip ...

随机推荐

  1. Vue的keep-alive

    Vue的keep-alive: 简答的做下理解 缓存!页面从某一个页面跳转到另一个页面的时候,需要进行一定的缓存,然后这个时候调用的钩子函数是actived,而在第一次加载的时候,created.ac ...

  2. 二. Jmeter--关联

    1. 首先建立一个线程组(Thread Group),为什么所有的请求都要加入线程组这个组件呢?不加不行吗?答案当然是不行的.因为jmeter的所有任务都必须由线程处理,所有任务都必须在线程组下面创建 ...

  3. 大端小端转换,le32_to_cpu 和cpu_to_le32

    字节序 http://oss.org.cn/kernel-book/ldd3/ch11s04.html 小心不要假设字节序. PC 存储多字节值是低字节为先(小端为先, 因此是小端), 一些高级的平台 ...

  4. HOJ 1108

    题目链接:HOJ-1108 题意为给定N和M,找出最小的K,使得K个N组成的数能被M整除.比如对于n=2,m=11,则k=2. 思路是抽屉原理,K个N组成的数modM的值最多只有M个. 具体看代码: ...

  5. puppet practice

    目标 试验环境有两台主机(VM)构成,一台是master,一台是agent,完成以下工作: 新建用户newuser; 安装 ubuntu-cloud-keyring package,更改文件/etc/ ...

  6. SP 页面缓存以及清除缓存

    JSP 页面缓存以及清除缓存 一.概述 缓存的思想可以应用在软件分层的各个层面.它是一种内部机制,对外界而言,是不可感知的. 数据库本身有缓存,持久层也可以缓存.(比如:hibernate,还分1级和 ...

  7. NTP算法

    网络时间协议 由特拉华大学的David L. Mills热心提供.http://www.eecis.udel.edu/~mills mills@udel.edu 由Reinhard v. Hanxle ...

  8. mini_httpd在RedHat 5下安装

    1.安装mini_httpdcd /usr/src/redhat/SOURCES wget http://www.acme.com/software/mini_httpd/mini_httpd-1.1 ...

  9. 次短路经(dijsktra)

    #include <cstdio>#include <cstring>#include <queue>#include <algorithm>#defi ...

  10. interesting Integers(数学暴力||数论扩展欧几里得)

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAwwAAAHwCAIAAACE0n9nAAAgAElEQVR4nOydfUBT1f/Hbw9202m0r8