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/') 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")
简单前端页面
![](http://img.e-com-net.com/image/info8/b8d97b5613f94ed2ba791cad57d0b2ed.gif)
![](http://img.e-com-net.com/image/info8/2f88dd3f1cd145f59c0e47b51acdbd4b.gif)
"en"> "UTF-8">Title