AI, artificial intelligence, Python, man-machine interaction, aipython
Today, with the development of artificial intelligence, if we don't try to get in touch with new things, we will soon be eliminated by the world ~
This article is intended to use the Python development language to implement "Dana", similar to the WIndows platform, or "Siri" under IOS ". In the end, man-machine interaction is achieved.
[Implementation function]
The main content of this article is as follows:
1. Building Ai-man-machine interaction Server Platform
2. Implement man-machine interaction by calling the server platform
[Implementation]
AIML
AIML was invented by Richard Wallace. He designed A robot named A. L. I .C.E. (Artificial Linguistics Internet Computer Entity Artificial language Network Computer Entity) and won several Artificial intelligence awards. Interestingly, one of the items in the Turing test is looking for such artificial intelligence: People and robots can communicate with each other for several minutes through the text interface to see if robots will be treated as humans.
This article uses the Python language to call the AIML library for intelligent robot development.
The system uses Python to set up the server-side backend interface, which can be directly called by various platforms. Then the client calls the intelligent conversation api interface, the server analyzes the parameter data, analyzes the statement, and finally returns the response result.
At present, the system front-end uses HTML to design and write simple chat rooms, and uses asynchronous requests to render data.
[Development and deployment environment]
Development Environment: Windows 7 × 64 English version
JetBrains PyCharm 2017.1.3 x64
Test environment: Windows 7 × 64 English version
[Required technology]
1. Familiar with Python, Python version 2.7
2. Use of the Python server development framework tornado
3. Simple use of the aiml library interface
4. Skillful Use of HTML + CSS + Javascript (jquery)
5. Ajax technology mastery
[Implementation process]
1. Install the Python aiml Library
pip install aiml
2. Get alice Resources
After installing Python aiml, there will be a alice subdirectory under Lib/site-packages/aiml under the Python installation directory. Copy this directory to the workspace.
Or download alice brain: aiml-en-us-foundation-alice.v1-9.zip on Google code
3. Load alice in Python
After obtaining alice resources, you can directly use the Python aiml library to load alice brain:
Import aimlos. chdir ('. /src/alice ') # Switch the workspace directory to the copied alice folder alice = aiml. kernel () alice. learn ("startup. xml ") alice. respond ('Load ALICE ')
Note: During loading, you need to switch the working directory to alice (the copied folder.
4. Chat with alice
After loading, you can chat with alice. Each time you only need to call the respond interface:
Alice. respond ('hello') # Here "hello" is the information sent to the robot.
5. Use Tornado to build a chatbot website
Tornado can easily build a web site's server, and the interface style is Rest style, it is easy to build a common server interface.
Here we will write two methods:
Get: rendering Interface
Post: GET request parameters, analyze them, and return chat results.
The code of the Class is as follows:
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. Build a chat interface
This interface is based on BootStrap. We have simply set up such a chat interface to display our interface results. Chat at the same time.
7. Interface call
We asynchronously request the server interface and render the result to the interface.
$. Ajax ({type: 'post', url: AppDomain + 'chat', async: true, // asynchronous 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
Here I have attached the complete directory structure and complete code of the system->
8. directory structure
9. Python server code
#!/usr/bin/env python# -*- coding: utf-8 -*-import os.pathimport tornado.authimport tornado.escapeimport tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webfrom tornado.options import define, optionsimport osimport aimlos.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 front-end code
<! DOCTYPE html>
System Test]
1. First, we can run our services.
2. Call Test
Then we call the front-end interface.
Here we can see that our project runs perfectly and achieves the expected results.
[Problems may occur]
Chinese garbled characters
[System outlook]
After testing, the Chinese language currently cannot be used for dialog, and only English can be used for dialog operations, which need to be improved.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.