AI人工智能 Python實(shí)現(xiàn)人機(jī)對(duì)話
在人工智能進(jìn)展的如火如荼的今天,我們?nèi)绻粐L試去接觸新鮮事物,馬上就要被世界淘汰啦~
本文擬使用Python開發(fā)語言實(shí)現(xiàn)類似于WIndows平臺(tái)的“小娜”,或者是IOS下的“Siri”。最終達(dá)到人機(jī)對(duì)話的效果。
【實(shí)現(xiàn)功能】
這篇文章將要介紹的主要內(nèi)容如下:
1、搭建人工智能--人機(jī)對(duì)話服務(wù)端平臺(tái)
2、實(shí)現(xiàn)調(diào)用服務(wù)端平臺(tái)進(jìn)行人機(jī)對(duì)話交互
【實(shí)現(xiàn)思路】
AIML
AIML由Richard Wallace發(fā)明。他設(shè)計(jì)了一個(gè)名為 A.L.I.C.E. (Artificial Linguistics Internet Computer Entity 人工語言網(wǎng)計(jì)算機(jī)實(shí)體) 的機(jī)器人,并獲得了多項(xiàng)人工智能大獎(jiǎng)。有趣的是,圖靈測(cè)試的其中一項(xiàng)就在尋找這樣的人工智能:人與機(jī)器人通過文本界面展開數(shù)分鐘的交流,以此查看機(jī)器人是否會(huì)被當(dāng)作人類。
本文就使用了Python語言調(diào)用AIML庫進(jìn)行智能機(jī)器人的開發(fā)。
本系統(tǒng)的運(yùn)作方式是使用Python搭建服務(wù)端后臺(tái)接口,供各平臺(tái)可以直接調(diào)用。然后客戶端進(jìn)行對(duì)智能對(duì)話api接口的調(diào)用,服務(wù)端分析參數(shù)數(shù)據(jù),進(jìn)行語句的分析,最終返回應(yīng)答結(jié)果。
當(dāng)前系統(tǒng)前端使用HTML進(jìn)行簡(jiǎn)單地聊天室的設(shè)計(jì)與編寫,使用異步請(qǐng)求的方式渲染數(shù)據(jù)。
【開發(fā)及部署環(huán)境】
開發(fā)環(huán)境:Windows 7 ×64 英文版
JetBrains PyCharm 2017.1.3 x64
測(cè)試環(huán)境:Windows 7 ×64 英文版
【所需技術(shù)】
1、Python語言的熟練掌握,Python版本2.7
2、Python服務(wù)端開發(fā)框架tornado的使用
3、aiml庫接口的簡(jiǎn)單使用
4、HTML+CSS+Javascript(jquery)的熟練使用
5、Ajax技術(shù)的掌握
【實(shí)現(xiàn)過程】
1、安裝Python aiml庫
pip install aiml
2、獲取alice資源
Python aiml安裝完成后在Python安裝目錄下的 Lib/site-packages/aiml下會(huì)有alice子目錄,將此目錄復(fù)制到工作區(qū)。
或者在Google code上下載alice brain: aiml-en-us-foundation-alice.v1-9.zip
3、Python下加載alice
取得alice資源之后就可以直接利用Python aiml庫加載alice brain了:
import aiml os.chdir('./src/alice') # 將工作區(qū)目錄切換到剛才復(fù)制的alice文件夾 alice = aiml.Kernel() alice.learn("startup.xml") alice.respond('LOAD ALICE')
注意加載時(shí)需要切換工作目錄到alice(剛才復(fù)制的文件夾)下。
4、 與alice聊天
加載之后就可以與alice聊天了,每次只需要調(diào)用respond接口:
alice.respond('hello') #這里的hello即為發(fā)給機(jī)器人的信息
5. 用Tornado搭建聊天機(jī)器人網(wǎng)站
Tornado可以很方便地搭建一個(gè)web網(wǎng)站的服務(wù)端,并且接口風(fēng)格是Rest風(fēng)格,可以很方便搭建一個(gè)通用的服務(wù)端接口。
這里寫兩個(gè)方法:
get:渲染界面
post:獲取請(qǐng)求參數(shù),并分析,返回聊天結(jié)果
Class類的代碼如下:
class ChatHandler(tornado.web.RequestHandler): def get(self): self.render('chat.html') def post(self): try: message = self.get_argument('msg', None) print(str(message)) result = { 'is_success': True, 'message': str(alice.respond(message)) } print(str(result)) respon_json = tornado.escape.json_encode(result) self.write(respon_json) except Exception, ex: repr(ex) print(str(ex)) result = { 'is_success': False, 'message': '' } self.write(str(result))
6. 簡(jiǎn)單搭建一個(gè)聊天界面
該界面是基于BootStrap的,我們簡(jiǎn)單搭建這么一個(gè)聊天的界面用于展示我們的接口結(jié)果。同時(shí)進(jìn)行簡(jiǎn)單的聊天。
7. 接口調(diào)用
我們異步請(qǐng)求服務(wù)端接口,并將結(jié)果渲染到界面
$.ajax({ type: 'post', url: AppDomain+'chat', async: true,//異步 dataType: 'json', data: ( { "msg":request_txt }), success: function (data) { console.log(JSON.stringify(data)); if (data.is_success == true) { setView(resUser,data.message); } }, error: function (data) { console.log(JSON.stringify(data)); } });//end Ajax
這里我附上系統(tǒng)的完整目錄結(jié)構(gòu)以及完整代碼->
8、目錄結(jié)構(gòu)
9、Python服務(wù)端代碼
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path import tornado.auth import tornado.escape import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options import os import aiml os.chdir('./src/alice') alice = aiml.Kernel() alice.learn("startup.xml") alice.respond('LOAD ALICE') define('port', default=3999, help='run on the given port', type=int) class Application(tornado.web.Application): def __init__(self): handlers = [ (r'/', MainHandler), (r'/chat', ChatHandler), ] settings = dict( template_path=os.path.join(os.path.dirname(__file__), 'templates'), static_path=os.path.join(os.path.dirname(__file__), 'static'), debug=True, ) # conn = pymongo.Connection('localhost', 12345) # self.db = conn['demo'] tornado.web.Application.__init__(self, handlers, **settings) class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') def post(self): result = { 'is_success': True, 'message': '123' } respon_json = tornado.escape.json_encode(result) self.write(str(respon_json)) def put(self): respon_json = tornado.escape.json_encode("{'name':'qixiao','age':123}") self.write(respon_json) class ChatHandler(tornado.web.RequestHandler): def get(self): self.render('chat.html') def post(self): try: message = self.get_argument('msg', None) print(str(message)) result = { 'is_success': True, 'message': str(alice.respond(message)) } print(str(result)) respon_json = tornado.escape.json_encode(result) self.write(respon_json) except Exception, ex: repr(ex) print(str(ex)) result = { 'is_success': False, 'message': '' } self.write(str(result)) def main(): tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': print('HTTP server starting ...') main()
9、Html前端代碼
<!DOCTYPE html> <html> <head> <link rel="icon" href="qixiao.ico" type="image/x-icon"/> <title>qixiao tools</title> <link rel="stylesheet" type="text/css" href="../static/css/bootstrap.min.css"> <script type="text/javascript" src="../static/js/jquery-3.2.0.min.js"></script> <script type="text/javascript" src="../static/js/bootstrap.min.js"></script> <style type="text/css"> .top-margin-20{ margin-top: 20px; } #result_table,#result_table thead th{ text-align: center; } #result_table .td-width-40{ width: 40%; } </style> <script type="text/javascript"> </script> <script type="text/javascript"> var AppDomain = 'http://localhost:3999/' $(document).ready(function(){ $("#btn_sub").click(function(){ var user = 'qixiao(10011)'; var resUser = 'alice (3333)'; var request_txt = $("#txt_sub").val(); setView(user,request_txt); $.ajax({ type: 'post', url: AppDomain+'chat', async: true,//異步 dataType: 'json', data: ( { "msg":request_txt }), success: function (data) { console.log(JSON.stringify(data)); if (data.is_success == true) { setView(resUser,data.message); } }, error: function (data) { console.log(JSON.stringify(data)); } });//end Ajax }); }); function setView(user,text) { var subTxt = user + " "+new Date().toLocaleTimeString() +'\n·'+ text; $("#txt_view").val($("#txt_view").val()+'\n\n'+subTxt); var scrollTop = $("#txt_view")[0].scrollHeight; $("#txt_view").scrollTop(scrollTop); } </script> </head> <body class="container"> <header class="row"> <header class="row"> <a href="/" class="col-md-2" style="font-family: SimHei;font-size: 20px;text-align:center;margin-top: 30px;"> <span class="glyphicon glyphicon-home"></span>Home </a> <font class="col-md-4 col-md-offset-2" style="font-family: SimHei;font-size: 30px;text-align:center;margin-top: 30px;"> <a href="/tools" style="cursor: pointer;">QiXiao - Chat</a> </font> </header> <hr> <article class="row"> <section class="col-md-10 col-md-offset-1" style="border:border:solid #4B5288 1px;padding:0">Admin : QiXiao </section> <section class="col-md-10 col-md-offset-1 row" style="border:solid #4B5288 1px;padding:0"> <section class="col-md-9" style="height: 400px;"> <section class="row" style="height: 270px;"> <textarea class="form-control" style="width:100%;height: 100%;resize: none;overflow-x: none;overflow-y: scroll;" readonly="true" id="txt_view"></textarea> </section> <section class="row" style="height: 130px;border-top:solid #4B5288 1px; "> <textarea class="form-control" style="overflow-y: scroll;overflow-x: none;resize: none;width: 100%;height:70%;border: #fff" id="txt_sub"></textarea> <button class="btn btn-primary" style="float: right;margin: 0 5px 0 0" id="btn_sub">Submit</button> </section> </section> <section class="col-md-3" style="height: 400px;border-left: solid #4B5288 1px;"></section> </section> </article> </body> </html>
【系統(tǒng)測(cè)試】
1、首先我們將我們的服務(wù)運(yùn)行起來
2、調(diào)用測(cè)試
然后我們進(jìn)行前臺(tái)界面的調(diào)用
這里我們可以看到,我們的項(xiàng)目完美運(yùn)行,并且達(dá)到預(yù)期效果。
【可能遇到問題】
中文亂碼
【系統(tǒng)展望】
經(jīng)過測(cè)試,中文目前不能進(jìn)行對(duì)話,只能使用英文進(jìn)行對(duì)話操作,有待改善。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python使用Pycharm創(chuàng)建一個(gè)Django項(xiàng)目
這篇文章主要介紹了python使用Pycharm創(chuàng)建一個(gè)Django項(xiàng)目,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03Python實(shí)戰(zhàn)之markdown轉(zhuǎn)pdf(包含公式轉(zhuǎn)換)
由于我們markdown編輯器比較特殊,不是很方便瀏覽,如果轉(zhuǎn)換成pdf的話,就不需要可以的去安裝各種編輯器才可以看了。所以本文將介紹如何通過Python實(shí)現(xiàn)md轉(zhuǎn)pdf或者是docx,需要的朋友可以參考一下2021-12-12Python實(shí)現(xiàn)屏幕截圖的代碼及函數(shù)詳解
本文給大家分享一段關(guān)于python實(shí)現(xiàn)屏幕截圖及函數(shù)的代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧2016-10-10