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. python-num18 - django进阶一

    一.深入django的路由系统 下面为django的请求生命周期 下面来看下整个生命周期中的路由系统: 在Django的urls中我们可以根据一个URL对应一个函数名来定义路由规则如下: " ...

  2. DNSLOG在渗透测试中的玩法儿

    首先了解一下DNS是啥??? DNS(Domain Name System,域名系统),万维网上作为域名和IP地址相互映射的一个分布式数据库,能够使用户更方便的访问互联网,而不用去记住能够被机器直接读 ...

  3. FPGA与CPLD的概念及其区别

    一.FPGA与CPLD的基本概念 1.CPLD CPLD主要是由可编程逻辑宏单元(LMC,Logic Macro Cell)围绕中心的可编程互连矩阵单元组成,其中LMC逻辑结构较复杂,并具有复杂的I/ ...

  4. MGR_ERROR 3092 (HY000): DROP DATABASE failed;

    start group_replication;时报以下错: ERROR 3092 (HY000): DROP DATABASE failed; some tables may have been d ...

  5. sqlalchemy更新和插入操作

    def save_app_info(self): try: # update app_info print(self.dicts) data = db_session.query(App_Info). ...

  6. 头像截图上传三种方式之一(一个简单易用的flash插件)(asp.net版本)

    flash中有版权声明,不适合商业开发.这是官网地址:http://www.hdfu.net/ 本文参考了http://blog.csdn.net/yafei450225664/article/det ...

  7. Integer类实现方式和注意事项

    java.lang.Integer类的源代码: //定义一个长度为256的Integer数组 static final Integer[] cache = new Integer[-(-128) + ...

  8. Java显式锁学习总结之四:ReentrantLock源码分析

    概述 ReentrantLock,即重入锁,是一个和synchronized关键字等价的,支持线程重入的互斥锁.只是在synchronized已有功能基础上添加了一些扩展功能. 除了支持可中断获取锁. ...

  9. django时差8个小时问题

    问题现象: 在用django做好的网站,上传图片后显示的发布时间比当前时间差了8小时 查找问题: 查看服务器系统时间,经查与当前时间一致,无问题 查看数据库中的时间也一样 最终原因: 在setting ...

  10. python中list的底层实现

    这里不讨论具体的实现细节,主要是转载这篇文章: 顺序表的原理与python中的list类型. 原文就不贴过来了,总结一下: 确定数据类型的意义在于确定一个数据在内存中占据的空间大小以及如何解释一段内存 ...