新大门---人工智能---接口调用

零 百度的"tensorflow"

paddlepaddle 强烈推荐学习

补充概念

SDK(software development kit),中文可译为“软件开发工具包”。

一般都是一些被软件工程师用于为特定的软件包、软件架构、硬件平台、操作系统等建立应用软件的开发工具的集合。通俗点是指由第三方服务商提供的实现软件产品某项功能的工具包。在编辑器里敲代码的时候它会自动补全代码、自动检查错误。
开发者不需要再对产品的每个功能进行开发,选择合适稳定的SDK服务并花费很少的经历就可以在产品中集成某项功能。

API(application programming interface),中文可译为“应用程序编程接口”。提供用户编程时的接口,是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。

实际上SDK包含了API的定义,API定义一种能力,一种接口的规范,而SDK可以包含这种能力、包含这种规范。但是SDK又不完完全全只包含API以及API的实现,它是一个软件工具包,它还有很多其他辅助性的功能。

为了使用 API 函数,我们就要有跟 API 所对应的 .H 和 .LIB 文件,而 SDK 正是提供了一整套开发 Windows 应用程序所需的相关文件、范例和工具的“工具包”。

SDK 包含了使用 API 的必需资料,所以人们也常把仅使用 API 来编写 Windows 应用程序的开发方式叫做“SDK编程”。

摘自:SDK与API区别

一 语音合成

1.1 前戏

记得安装baidu-aip,两种安装途径:
一.通过pycharm安装baidu-aip;(aip是A.I. processing)
二.pip install baidu-aip

1.2 代码

from aip import AipSpeech

""" 你的 APPID AK SK """
APP_ID = '你的APP_ID'
API_KEY = '你的API_KEY '
SECRET_KEY = 'SECRET_KEY '

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

msg = '''
无题(其一)
星隐云吟雾,月嗅玉闪珠.
虚钓空野外,燕歌狂人呼.

无题(其二)
翠玉浮绿燕,碧海荡青天。
钟鼓层叠处,依稀少人烟。'''

result  = client.synthesis(msg, 'zh', 1, {
    'vol': 6,
    'per':4,
    'pit':8,
    'spd':4,
})

# 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(result, dict):
    with open('auido.mp3', 'wb') as f:
        f.write(result)

二 语音识别

2.1 前戏

FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。采用LGPL或GPL许可证。

第一步,此处我们要下载一个FFmpeg.
FFmpeg下载
链接:https://pan.baidu.com/s/1O1foEUIIxfUjShBKQOcAaQ
提取码:jlac

第二步,下载完后在bin文件夹下找到ffmpeg(相信能找到的,记得解压).然后把路径配置到path环境变量中.

第三步,最后输入命令:ffmpeg -y -i auido.mp3 -acodec pcm_s16le -f s16le -ac 1 -ar 16000 audio.pcm

理论上能转化任何音频为pcm格式.

注意,python中的os.system()很牛逼,能执行任意cmd命令.
ffmpeg命令转音乐为wav格式,wav格式与PCM数据相互转换,ffplay播放PCM数据


在安装和配置完成ffmpeg之后记得重启pycharm(pycharm会记得刚打开时候的环境变量)

否则可能会出现下面问题:
'ffmpeg' �����ڲ����ⲿ���Ҳ���ǿ����еij��� ���������ļ��� 说明没配置成功或者配置成功后没重启,或者要把进程杀死,或者是命令是空格出问题了吗?在cmd执行一下试试.

2.2 代码

import os

from aip import AipSpeech

""" 你的 APPID AK SK """
APP_ID = 'APP_ID '
API_KEY = '你的API_KEY '
SECRET_KEY = 'SECRET_KEY '

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)


# 读取文件
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


# 转换为pcm格式的不好使
os.system('ffmpeg -y -i auido.mp3 -acodec pcm_s16le -f s16le -ac 1 -ar 16000  audio.pcm')
# 识别本地文件
print(client.asr(get_file_content('audio.pcm'), 'pcm', 16000, {
    'dev_pid': 1536,
}))

三 NLP相似度分析

3.1 代码

import os

from aip import AipSpeech,AipNlp

""" 你的 APPID AK SK """
APP_ID = 'APP_ID '
API_KEY = '你的API_KEY '
SECRET_KEY = 'SECRET_KEY '

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

msg = '''你叫什么?'''

result  = client.synthesis(msg, 'zh', 1, {
    'vol': 6,
    'per':4,
    'pit':8,
    'spd':4,
})

# 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(result, dict):
    with open('auido.mp3', 'wb') as f:
        f.write(result)

# 读取文件
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


# 转换为pcm格式的不好使
os.system('ffmpeg -y -i auido.mp3 -acodec pcm_s16le -f s16le -ac 1 -ar 16000  audio.pcm')
# 识别本地文件
Q = client.asr(get_file_content('audio.pcm'), 'pcm', 16000, {
    'dev_pid': 1536,
})['result'][0]

client = AipNlp(APP_ID, API_KEY, SECRET_KEY)
A = '我不知道你在说什么?'
if  client.simnet(Q, '你的名字叫什么')['score'] >= 0.58:
    A = '我的名字是傻妞.'

""" 调用相似度分析 """

print(A)

四 图灵机器人接口

4.1 前戏

登录图灵机器人,注册.
打开帮助中心,跳转到API V2.0查看帮助,写入接口地址.(不要忘记写APIKey和ID)(ID是要写数字的).

4.2 代码

tuling.py

import requests

def tl(Q):
    data = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": Q
            },
            "inputImage": {
                "url": "imageUrl"
            },
            "selfInfo": {
                "location": {
                    "city": "北京",
                    "province": "北京",
                    "street": "信息路"
                }
            }
        },
        "userInfo": {
            "apiKey": "3f6fbc8b18384fa68ac5d2c529f52195",
            "userId": "123"
        }
    }

    res = requests.post('http://openapi.tuling123.com/openapi/api/v2',json=data)

    res_dict = res.json()

    return res_dict['results'][0]['values'].get('text')

nlp.py

import os

from aip import AipSpeech,AipNlp

from tuling import tl

""" 你的 APPID AK SK """
APP_ID = 'APP_ID '
API_KEY = '你的API_KEY '
SECRET_KEY = 'SECRET_KEY '

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

msg = '''你算老几?'''

result  = client.synthesis(msg, 'zh', 1, {
    'vol': 6,
    'per':4,
    'pit':8,
    'spd':4,
})

# 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(result, dict):
    with open('auido.mp3', 'wb') as f:
        f.write(result)

# 读取文件
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


# 转换为pcm格式的不好使
os.system('ffmpeg -y -i auido.mp3 -acodec pcm_s16le -f s16le -ac 1 -ar 16000  audio.pcm')
# 识别本地文件
Q = client.asr(get_file_content('audio.pcm'), 'pcm', 16000, {
    'dev_pid': 1536,
})['result'][0]

client = AipNlp(APP_ID, API_KEY, SECRET_KEY)
A = '我不知道你在说什么?'
if  client.simnet(Q, '你的名字叫什么')['score'] >= 0.58:
    A = '我的名字是傻妞.'
else:
    A = tl(Q)

""" 调用相似度分析 """

print(A)

五 简易聊天机器人(未测试apiKey的轮换)

5.0 提示

keyapi应该用自己的!!

多参考os模块.

5.1 项目结构图示

简易聊天机器人图示

5.2 static

含有两个文件.

5.3 storage

一个recorder,放录音文件;一个answer,放回答文件.

5.4 templates

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title id="title">smart home</title>

</head>
<body>
<audio id="player" autoplay controls></audio>
<p>
    <button onclick="start_reco()">开始录音</button>
</p>
<p>
    <button onclick="ai_reco()" style="background-color: cornflowerblue">发送语音指令</button>
</p>
</body>
<script type="application/javascript" src="/static/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="/static/Recorder.js"></script>
<script type="application/javascript">
    var reco = null;
    var serv = "http://127.0.0.1:5000";
    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 ai_reco() {
        reco.stop();

        reco.exportWAV(function (wav_file) {
            console.log(wav_file);
            var formdata = new FormData(); // form 表单 {key:value}
            formdata.append("reco", wav_file); // form input type="file"
            $.ajax({
                url: serv + "/ai_uploader",
                type: 'post',
                processData: false,
                contentType: false,
                data: formdata,
                dataType: 'json',
                success: function (data) {
                    document.getElementById('player').src = serv + '/get_chat/' + data.filename;
                }
            })
        });

        reco.clear();
    }

</script>
</html>

5.5 views

5.5.1 AI(注意不能加·)

5.5.1.1 asr.py

import os

from aip import AipSpeech

""" 你的 APPID AK SK """
APP_ID = 'APP_ID '
API_KEY = '你的API_KEY '
SECRET_KEY = 'SECRET_KEY '

asr_client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)


# 读取文件
def get_file_content(filename):
    now_path = os.getcwd() + r'\storage\recorder'
    absolute_filePath = os.path.join(now_path, filename)
    os.system(
        f'ffmpeg -y -i {absolute_filePath}.wav -acodec pcm_s16le -f s16le -ac 1 -ar 16000  {absolute_filePath}.pcm')  # 将文件由wav格式转化为pcm格式
    with open(absolute_filePath + '.pcm', 'rb') as fp:
        return fp.read()

5.5.1.2 nlp.py

from aip import AipNlp

""" 你的 APPID AK SK """
APP_ID = 'APP_ID '
API_KEY = 'API_KEY '
SECRET_KEY = 'SECRET_KEY '

nlp_client = AipNlp(APP_ID, API_KEY, SECRET_KEY)

def similarity1(Q,A):
    text1 = Q
    text2 = A

    """ 调用短文本相似度 """
    nlp_client.simnet(text1, text2)

    """ 如果有可选参数 """
    options = {}
    options["model"] = "CNN"

    """ 带参数调用短文本相似度 """
    return nlp_client.simnet(text1, text2, options)

def similarity2(Q,A):
    text1 = Q
    text2 = A

    """ 调用短文本相似度 """
    nlp_client.simnet(text1, text2)

    """ 如果有可选参数 """
    options = {}
    options["model"] = "CNN"

    """ 带参数调用短文本相似度 """
    return nlp_client.simnet(text1, text2, options)

5.5.1.3 tts.py

from aip import AipSpeech

""" 你的 APPID AK SK """
APP_ID = '你的APP_ID'
API_KEY = '你的APP_KEY'
SECRET_KEY = '你的SECRET_KEY'


def switch_text(A, now_time):
    tts_client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

    result = tts_client.synthesis(A, 'zh', 1, {
        'vol': 5,
    })
    answer_name = now_time + '_answer.mp3'
    answer_path = 'storage/answer/' + answer_name
    # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
    if not isinstance(result, dict):
        with open(answer_path, 'wb') as f:
            f.write(result)
    return answer_name

5.5.1.4 tulingRobot.py

import requests

#请使用自己的apiKEY哦
def tl(Q, count=1):
    apiKeyBak = {1: 'xxx', 2: 'xxx',
                 3: 'xxx', 4: 'xxx',
                 5: 'xxx'}

    data = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": Q
            },
            "inputImage": {
                "url": "imageUrl"
            },
            "selfInfo": {
                "location": {
                    "city": "北京",
                    "province": "北京",
                    "street": "信息路"
                }
            }
        },
        "userInfo": {
            "apiKey": "40011377e8604e669791bf87cc8394b4",
            "userId": "001"
        }
    }

    res = requests.post('http://openapi.tuling123.com/openapi/api/v2', json=data)
    res_dict = res.json()
    msg = res_dict['results'][0].get('values').get('text')
    if msg == '请求次数超过限制':
        # 切换apikey
        if count > 5:
            res = requests.get(f'http://open.drea.cc/chat/get?keyWord={Q}&userName=type%3Dbbs').text['data'].get('reply')
        else:
            count += 1
            data['userInfo']['apiKey'] = apiKeyBak[count]

    return res

5.5.2.1 app_opera.py

import time
import os

from flask import Blueprint, render_template, request

from views.AI.asr import asr_client,get_file_content
from views.AI.tulingRobot import tl
from views.AI.nlp import similarity1,similarity2
from views.AI.tts import switch_text

sqa1 = Blueprint('sqa', __name__)


@sqa1.route('/sqa', methods=["GET", "POST"])
def sqa():
    """
    返回主页面
    :return:
    """
    return render_template('smart_home.html')


sqa2 = Blueprint('ai_uploader', __name__)


@sqa2.route('/ai_uploader', methods=["POST", 'GET'])
def ai_uploader():
    """
    该蓝图得到前端发送的录音文件并且保存为wav格式的文件,文件存储位置为storage/recorder的文件夹下面,命名方法是当时的年月日时分秒.
    流程:输入语音--->转化为文本--->调用图灵机器人进行文本回答(相似度分析可以在这里做一些特定的回答)--->转化为语音--->传到前端自动播放
    :return:成功
    """
    my_reco_file = request.files.get('reco')
    now_time = time.strftime('%Y%m%d%H%M%S')
    store_files_path = os.path.join('storage/recorder', now_time)
    my_reco_file.save(store_files_path + '.wav')

    # 将生成的wav文件转化为pcm文件
    msg = get_file_content(now_time)
    # 识别本地文件并转化为文字
    question = asr_client.asr(msg, 'pcm', 16000, {
        'dev_pid': 1536,
    })

    # 插件: 可以自定义关键词语回复
    question1 = '这个妹妹太坏了'
    question2 = '这周五准备去干嘛?'
    if similarity1(question,question1).get('score',0) >= 0.58:
        # 语音合成
        answer1 = '哥哥,你怎么能这么说?我可是你的妹妹啊'
        answer_file = switch_text(question1,now_time)
    elif similarity2(question,question2).get('score',0) >= 0.58:
        # 语音合成
        answer2 = '这种问题我也不知道怎么回答啊'
        answer_file = switch_text(answer2, now_time)
    else:
        # 机器人识别文字并作出回答
        res = tl(question)
        # 语音合成
        answer_file = switch_text(res, now_time)


    return {'filename':answer_file}

5.6 manage.py

import os

from flask import Flask, send_file

from views.blueprint.app_opera import sqa1,sqa2

app = Flask(__name__)
app.config['DEBUG' ] = True

app.register_blueprint(sqa1)
app.register_blueprint(sqa2)

@app.route('/get_chat/<filename>')
def get_chat(filename):
    now_path = os.getcwd() + r'\storage\answer'
    absolute_filePath = os.path.join(now_path, filename)
    return send_file(absolute_filePath)

if __name__ == '__main__':
    app.run('0.0.0.0',5000,debug=True)

5.7 readme

该文件是一个简单的智能家居里面的小模块---简单的机器人问答.
其主要是调用图灵机器人的接口进行对话,
发现提示"请求次数超过限制"就会自动跳转到另一个apikey,轮流使用,相当于一天能用5个...
posted on 2019-07-17 23:13  流云封心  阅读(133)  评论(0)    收藏  举报