AI人工智能-Python實現前后端人機聊天對話


【前言】

  AI

  在人工智能進展的如火如荼的今天,我們如果不嘗試去接觸新鮮事物,馬上就要被世界淘汰啦~

  本文擬使用Python開發語言實現類似於WIndows平台的“小娜”,或者是IOS下的“Siri”。最終達到人機對話的效果。

【實現功能】

  這篇文章將要介紹的主要內容如下:

  1、搭建人工智能--人機對話服務端平台

  2、實現調用服務端平台進行人機對話交互

【實現思路】

  AIML

  AIML由Richard Wallace發明。他設計了一個名為 A.L.I.C.E. (Artificial Linguistics Internet Computer Entity 人工語言網計算機實體) 的機器人,並獲得了多項人工智能大獎。有趣的是,圖靈測試的其中一項就在尋找這樣的人工智能:人與機器人通過文本界面展開數分鍾的交流,以此查看機器人是否會被當作人類。

  本文就使用了Python語言調用AIML庫進行智能機器人的開發。

  本系統的運作方式是使用Python搭建服務端后台接口,供各平台可以直接調用。然后客戶端進行對智能對話api接口的調用,服務端分析參數數據,進行語句的分析,最終返回應答結果。

  當前系統前端使用HTML進行簡單地聊天室的設計與編寫,使用異步請求的方式渲染數據。

【開發及部署環境】

開發環境:Windows 7 ×64 英文版

     JetBrains PyCharm 2017.1.3 x64

測試環境:Windows 7 ×64 英文版

【所需技術】

  1、Python語言的熟練掌握,Python版本2.7

  2、Python服務端開發框架tornado的使用

  3、aiml庫接口的簡單使用

  4、HTML+CSS+Javascript(jquery)的熟練使用

  5、Ajax技術的掌握

【實現過程】

  1、安裝Python aiml庫

pip install aiml

  2、獲取alice資源

  Python aiml安裝完成后在Python安裝目錄下的 Lib/site-packages/aiml下會有alice子目錄,將此目錄復制到工作區。
或者在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') # 將工作區目錄切換到剛才復制的alice文件夾
alice = aiml.Kernel()
alice.learn("startup.xml")
alice.respond('LOAD ALICE')

  注意加載時需要切換工作目錄到alice(剛才復制的文件夾)下。

  4、 與alice聊天

  加載之后就可以與alice聊天了,每次只需要調用respond接口:

alice.respond('hello') #這里的hello即為發給機器人的信息

  5. 用Tornado搭建聊天機器人網站

  Tornado可以很方便地搭建一個web網站的服務端,並且接口風格是Rest風格,可以很方便搭建一個通用的服務端接口。

  這里寫兩個方法:

  get:渲染界面

  post:獲取請求參數,並分析,返回聊天結果

  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. 簡單搭建一個聊天界面

  

  該界面是基於BootStrap的,我們簡單搭建這么一個聊天的界面用於展示我們的接口結果。同時進行簡單的聊天。

  6. 接口調用

  我們異步請求服務端接口,並將結果渲染到界面

復制代碼
                $.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
復制代碼

 

  這里我附上系統的完整目錄結構以及完整代碼->

  7、目錄結構

  

  8、Python服務端代碼

復制代碼
#!/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>
復制代碼

【系統測試】

  1、首先我們將我們的服務運行起來

  

  2、調用測試

   然后我們進行前台界面的調用

  

  

  這里我們可以看到,我們的項目完美運行,並且達到預期效果。

【可能遇到問題】  

  中文亂碼

【系統展望】

  經過測試,中文目前不能進行對話,只能使用英文進行對話操作,有待改善

 

 

出處:https://www.cnblogs.com/7tiny/p/7246387.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM