«По мере того, как все больше и больше искусственного интеллекта входит в мир, все больше и больше эмоционального интеллекта должно входить в лидерство».
Мы говорим здесь о каком-то ИИ?
Позвольте мне немного пояснить, что мы собираемся здесь разработать. Чат-бот – это бот на основе машинного обучения, скука. Он основан на Python, который может возвращать ответы на основе разговоров.
Базовый (или сумасшедший) пример архитектуры чат-бота может быть таким:
Human : Hi, how are you doing ? ChatBot : I'm good, how are you doing ? Human : Trying to live upto my Manger's expectations. ChatBot : Try harder or I'm soon gonna take your place. Human : Would you mind converting me into one of you ? ChatBot : Sorry, didn't understand XD
Как это работает?
Чат-бот подобен новорожденному ребенку, он не знает ничего, кроме как открывать глаза (показывая встроенный экран), пока вы не заполните его всеми бессмысленными данными. Просто введите в него данные, и библиотека сохранит его. Затем позже он отвечает закрытыми соответствующими данными, которые он сохранил. Так что в целом, например, речь идет о том, что такое «Как приручить дракона».
Теперь приступим к делу
- Установите ChatterBot с помощью pip
$ pip3 install ChatterBot
- Установите Flask Micro Web Framework
$ pip3 install Flask
- Создайте файл app.py и заполните его следующим кодом
# importing files and required libraries from flask import Flask, render_template, request from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from chatterbot.trainers import ListTrainer # Create an app from Flask app = Flask(__name__) # Create an instance of the ChatBot class bot = ChatBot("Candice") #Create a new trainer for the Chatbot
trainer = ChatterBotCorpusTrainer(bot) #Train the chatbot based on the english corpus
trainer.train('chatterbot.corpus.english') #app routing is used to map the specific URL with the associated #function that is intended to perform some tasks. Such as to access #partcular page @app.route("/") def home(): return render_template("index.html") @app.route("/get") def get_bot_response(): userText = request.args.get('msg') return str(bot.get_response(userText)) if __name__ == "__main__": app.run()
- Создайте симпатичный занудный index.html с помощью CSS (подготовьтесь к долгой прокрутке).
<!DOCTYPE html> <html> <title>Bot Chintu</title> <head> <link rel="shortcut icon" type="image/x-icon" href="https://user-images.githubusercontent.com/20112458/49326597-773b7280-f57a-11e8-853d-20ed61d18b0d.png" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <style> body { font-family: monospace; background-image: url("https://i.pinimg.com/originals/08/3f/ce/083fce221878de72f0fdede553cd8545.jpg") } h1 { font-size: 3em; margin: 0; color: rgb(255, 99, 71); padding: 14px; } h3 { color: red; font-size: 20px; margin-top: 3px; text-align: center; } #chatbox { margin-left: auto; margin-right: auto; width: 40%; margin-top: 60px; } #userInput { margin-left: auto; margin-right: auto; width: 40%; margin-top: 60px; } #textInput { width: 90%; border: none; border-bottom: 3px solid black; font-family: monospace; font-size: 17px; } .userText { color: white; font-family: monospace; font-size: 17px; text-align: right; line-height: 30px; } .userText span { background-color: #ffc0cb; padding: 10px; border-radius: 2px; } .botText { color: white; font-family: monospace; font-size: 17px; text-align: left; line-height: 30px; } .botText span { background-color: #4169e1; padding: 10px; border-radius: 2px; } #tidbit { position: absolute; bottom: 0; right: 0; width: 300px; } .boxed { margin-left: auto; margin-right: auto; width: 78%; margin-top: 60px; } .box { border: 2px solid black; } </style> </head> <body> <img /> <center> <h1> 🗽 Your Personal Bolbachhan </h1> </center> <h3> <p> Do you feel its interesting? ❤️ Tweet me 👉 <a href="https://twitter.com/saurabh_thakre_">@saurabh_thakre</a>. You can find this project on <a href="https://www.github.com/saurabh-thakre/Chintu_Python_Flask_Bot">GitHub</a>. </p> </h3> <div class="box"></div> <div class="boxed"> <div> <div id="chatbox"> <p class="botText"> <span>🍔 Hi! I'm Chintu yours personal bolbachhan ❤️</span> </p> </div> <div id="userInput"> <input id="textInput" type="text" name="msg" placeholder="Message" /> </div> </div> <script> function getBotResponse() { var rawText = $("#textInput").val(); var userHtml = '<p class="userText"><span>' + rawText + "</span></p>"; $("#textInput").val(""); $("#chatbox").append(userHtml); document .getElementById("userInput") .scrollIntoView({ block: "start", behavior: "smooth" }); $.get("/get", { msg: rawText }).done(function(data) { var botHtml = '<p class="botText"><span>' + data + "</span></p>"; $("#chatbox").append(botHtml); document .getElementById("userInput") .scrollIntoView({ block: "start", behavior: "smooth" }); }); } $("#textInput").keypress(function(e) { if (e.which == 13) { getBotResponse(); } }); </script> </div> </body> </html>
- Вуаля! Мы почти закончили. Теперь запустите файл app.py
[saurabh@linux ~]# python3 app.py Training ai.yml: [####################] 100% Training botprofile.yml: [####################] 100% Training computers.yml: [####################] 100% Training conversations.yml: [####################] 100% Training emotion.yml: [####################] 100% Training food.yml: [####################] 100% Training gossip.yml: [####################] 100% Training greetings.yml: [####################] 100% Training health.yml: [####################] 100% Training history.yml: [####################] 100% Training humor.yml: [####################] 100% Training literature.yml: [####################] 100% Training money.yml: [####################] 100% Training movies.yml: [####################] 100% Training politics.yml: [####################] 100% Training psychology.yml: [####################] 100% Training science.yml: [####################] 100% Training sports.yml: [####################] 100% Training trivia.yml: [####################] 100% * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Ваш красивый чат-бот готов,
Я знаю, я знаю, я уже разместил код на GitHub, Saurabh-Thakre/Chintu_Python_Flask_Bot
Я оставил некоторый код необъяснимым, поэтому я знаю, что вы вернетесь в этот блог снова и зададите свои вопросы ;). И наверняка вы получите пару ошибок зависимостей при попытке запустить app.py. Но не волнуйтесь, как я уже упоминал, комментируйте все ваши запросы здесь, и я буду вашим Google.
Тата, увидимся, надеюсь, не в масках :\