(一)图灵机器人API2.0接口构造聊天机器人
程序员文章站
2022-06-04 09:59:41
...
参考自:
(1)构造聊天机器人
https://www.jianshu.com/p/c3ebd99d6fc4
https://zhuanlan.zhihu.com/p/86681217
(2)Chatbot的前世今生
https://zhuanlan.zhihu.com/p/55201625
基于模板匹配模方法:
图灵机器人http://www.turingapi.com/
API接口教程https://www.kancloud.cn/turing/www-tuling123-com/718227
代码1:
from flask import Flask
import requests
app = Flask(__name__)
# 装饰器里面写的是访问路径
@app.route("/")
def hello_world():
url = "http://openapi.tuling123.com/openapi/api/v2"
data_param = {
"reqType": 0,
"perception": {
"inputText": {
"text": "附近的酒店"
},
"inputImage": {
"url": "imageUrl"
},
"selfInfo": {
"location": {
"city": "北京",
"province": "北京",
"street": "信息路"
}
}
},
"userInfo": {
#在上面提供的网址中注册登录获取你的机器人apikey,userId可以随便填写
"apiKey": "xxxxxxxxxxxxxxxxxxxxxx",
"userId": "xxxxxxxxxxxxxxxxxx"
}
}
response = requests.post(url=url,json=data_param)
print(response.text)
return "贪心学院"
if __name__ == "__main__":
app.run()
运行结果:
会得到返回的信息:
{"intent":{"code":4003},"results":[{"groupType":0,"resultType":"text","values":{"text":"在外住酒店,还是得小心点好哦~"}}]}
代码2:
from flask import Flask
app = Flask(__name__)
# 装饰器里面写的是访问路径
@app.route("/greedyai/<data>")
def hello_world(data):
return data
if __name__ == "__main__":
app.run()
运行结果:
代码3:
from flask import Flask
import requests
app = Flask(__name__)
# 装饰器里面写的是访问路径
@app.route("/greedyai/<data>")
def hello_world(data):
if "帅" in data:
return "大周老师"
elif "线上" in data:
return "线上课程为主"
elif "助教" in data or "服务" in data:
return "为提高服务质量,课程配有专业的助教老师"
elif "基础" in data:
return "http://aijiaoai.greedyai.com/home"
elif "优势" in data:
return "这你都问,大周老师就是优势"
elif "有效期" in data:
return "只要你想学,我一直在你身边"
else:
return "哎哟,小主,我不懂你的意思"
if __name__ == "__main__":
app.run()
然后跟上面的示例一样,在路径之后输入一句话,如果这一句话里面包含了某个关键词,那么就会输出相应的回复
这是部分输入的回复:
实例代码4:
from flask import Flask
import requests
app = Flask(__name__)
# 装饰器里面写的是访问路径
@app.route("/chat/<data>")
def hello_world(data):
url = "http://openapi.tuling123.com/openapi/api/v2"
if "帅" in data:
return "大周老师"
elif "线上" in data:
return "线上课程为主"
elif "助教" in data or "服务" in data:
return "为提高服务质量,课程配有专业的助教老师"
elif "基础" in data:
return "http://aijiaoai.greedyai.com/home"
elif "优势" in data:
return "这你都问,大周老师就是优势"
elif "有效期" in data:
return "只要你想学,我一直在你身边"
else:
data_param = {
"reqType": 0,
"perception": {
"inputText": {
"text": "data"
},
"inputImage": {
"url": "imageUrl"
},
"selfInfo": {
"location": {
"city": "北京",
"province": "北京",
"street": "信息路"
}
}
},
"userInfo": {
"apiKey": "6cdbed64eeb14e6ea453538622bc1d74",
"userId": "582149"
}
}
response = requests.post(url=url,json=data_param)
print(response.text)
if __name__ == "__main__":
app.run()
运行结果:
基于搜索的方法
用户输入 -> 检索模型 -> 输入
如何计算相似度(文本的向量表示)
余弦相似度
课程demo
import jieba
word_vector_list = ["我们", "来", "贪心", "学院", "学习", "人工智能", "和", "python"]# 词典
s1 = "我来贪心学院学习python"
s2 = "我学习人工智能"
s3 = "Python课程的学习周期是多久"
question = "Python学习多久"
# 第一种切分模式:精确模式,比较适合做文本分析,['我来', '贪心', '学院', '学习', 'python']
s1_result_list = list(jieba.cut(s1))
print(s1_result_list)
# 全模式,['我来', '贪心', '学院', '学习', 'python']
s1_result_list = list(jieba.cut(s1, cut_all=True))
print(s1_result_list)
# 搜索引擎模式,['我来', '贪心', '学院', '学习', 'python']
s1_result_list = list(jieba.cut_for_search(s1))
print(s1_result_list)
# 向量转换
import numpy as np
def get_vector(data):
vector_list = []
for i in word_vector_list:
if i in list(jieba.cut(data)):
vector_list.append(1)
else:
vector_list.append(0)
print(data)
print(vector_list)
return np.array(vector_list).reshape(1, -1)
question_vector_list = get_vector(question)#输出:Python学习多久[0, 0, 0, 0, 1, 0, 0, 0]
s1_vector_list = get_vector(s1) #输出:我来贪心学院学习python[0, 0, 1, 1, 1, 0, 0, 1]
s2_vector_list = get_vector(s2) #输出:我学习人工智能[0, 0, 0, 0, 1, 1, 0, 0]
s3_vector_list = get_vector(s3) #输出:Python课程的学习周期是多久[0, 0, 0, 0, 1, 0, 0, 0]
# 相似度计算
from sklearn.metrics.pairwise import cosine_similarity
# print(cosine_similarity([[1, 0, 1]], [[0, 0, 1]]))
print(cosine_similarity(question_vector_list, s1_vector_list))
print(cosine_similarity(question_vector_list, s2_vector_list))
print(cosine_similarity(question_vector_list, s3_vector_list))
#输出[[0.5]],[[0.70710678]],[[1.]]
作业
完成一个完整的项目,能够根据已有的语料库,自动根据输入去计算哪个答案最符合
import jieba
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from flask import Flask
# 建立语料库
corpus = {
"Python课程是线上课程还是线下课程?": "线上课程为主",
"Python课程有助教吗?": "为提高服务效率和质量,课程都配备专业的全职助教。",
"我没有基础应该从哪个课开始学?": "大周老师的Python基础集训营非常适合你哦,"
"可以在这里学习:http://aijiaoai.greedyai.com/info/5",
"Python的学习周期是多久?": "如果你没有基础的话两个月可以搞定",
"Python课程的学习方式是什么呢?": "无需安装环境,在线直接写代码、看视频、看漫画,趣味性学习",
"Python课程的优势是什么呢?": "全网覆盖最全的Python基础知识体系练与学的深度结合,"
"每一个知识点都配有练习项目,生动有趣、授课方式多样,视频、文字、图片、在线代码编辑,"
"在聊天与娱乐中学习",
"Python课程的有效期是多久呢?": "我们把有效期确定为1年,1年内可无限次学习",
"Python课程有优惠吗?": "我们定价为开课后是599,现在是针对老学员预售199,开课后恢复原价"
}
# 建立词典,对于所有语料库中的问题进行jieba分词
all_question = ""
for question in corpus:
all_question += question
dictionaries = list(set(jieba.cut(all_question))) # 加上set是为了方便去重
# 单个词典转换为向量
def transform_vector(date):
vector_list = []
for wd in dictionaries:
if wd in list(jieba.cut(date)):
vector_list.append(1)
else:
vector_list.append(0)
return np.array(vector_list).reshape(1, -1) # .reshape(1,-1)是为了后期余弦计算
# 单个余弦相似度计算
def get_cosine(user_question, corpus_question):
similar_list = cosine_similarity(transform_vector(user_question), transform_vector(corpus_question))
similar_num = similar_list[0][0] # 相似度
return similar_num
# 计算语料库中的所有相似度
def get_corpus_consine(user_question):
ori_question_dict = {}
ori_answer_dict = {}
similar_list = [] # 保存所有余弦值
for key in corpus:
similar_num = get_cosine(user_question, key) # 获得余弦值
similar_list.append(similar_num) # 保存所有余弦值
ori_question_dict[similar_num] = key # 获取原问题并储存
ori_answer_dict[similar_num] = corpus[key] # 获取原答案并储存
return similar_list, ori_question_dict, ori_answer_dict
# 得到最佳回答
def get_best_answer(similar_list, ori_question_dict, ori_answer_dict):
max_similar = max(similar_list)
if max_similar == 0: # 没有匹配项
best_similar = 0
best_question = "未检索到相似的问题"
best_answer = "对不起,我听不懂你在说什么"
else: # 返回值
best_similar = max_similar
best_question = ori_question_dict[max_similar]
best_answer = ori_answer_dict[max_similar]
return [best_similar, best_question, best_answer]
# 使用faslk,以接口的形式完成问答
app = Flask(__name__)
@app.route("/<user_question>")
def question_for_web(user_question):
similar_list, ori_question_dict, ori_answer_dict = get_corpus_consine(user_question) # 计算所有相似度
res = get_best_answer(similar_list, ori_question_dict, ori_answer_dict) # 得到最佳答案
html_ = '<html><body>' \
'<p>' \
'<h2>问题:{}</h2>' \
'</p>' \
'<p>' \
'<li>最高相似度:{}</li>' \
'<li>最高相似度的问题:{}</li>' \
'<h2>最佳回答为:{}</h2>' \
'</p>' \
'</body></html>'.format(user_question, res[0], res[1], res[2])
return html_ # 返回html并写入网页
if __name__ == "__main__":
app.run()
运行结果: