If you are planning to build a real-time chat system, you should consider using websockets. But for the example you have described, it should be sufficient to demonstrate the functionality via HTTP itself.
First convert your main.py to provide a method which will accept an input and return an output
def response_for_input(inp):
results = model.predict([bag_of_words(inp, words)])
results_index = numpy.argmax(results)
tag = labels[results_index]
# print(tag)
for tg in data["intents"]:
if tg['tag'] == tag:
responses = tg['responses']
response = random.choice(responses)
return response
Then in your app.py
from flask import Flask, render_template, url_for, request, redirect, jsonify
from datetime import datetime
from .main import response_for_input
DEBUG = True
app = Flask(__name__)
@app.route('/')
def index():
return render_template("index.html")
@app.route("/chat", methods=["POST"])
def chat():
input_data = request.get_json()
input_msg = input_data.get("msg")
response = response_for_input(input_msg)
return jsonify({"status": "success", "msg": response})
if __name__ == "__main__":
app.run(debug=True)
You will need to implement index.html to have a form which will do json post. I have provided a rough example here, which has an input form, processes the input text, appends it to DOM, posts it to server and then appends the response from server also to DOM.
<html>
<head>
<link rel="icon" href="data:,">
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
crossorigin="anonymous"></script>
</head>
<body>
<h1>Chat Demo</h1>
<div id="chat-contents">
<div class="input-msg">Some msg</div>
<div class="chat-response">Some response</div>
</div>
<form method="POST" id="chat-form" action="/chat">
<div>
<label for="msg">Message Body: </label>
<textarea rows="10" cols="100" name="msg" id ="chat-input-msg"></textarea>
</div>
<input type="submit" value="Ask Bot">
</form>
<script type="text/javascript">
$(function(){
$("#chat-form").submit(function(event){
event.preventDefault();
var chatInputMsg = $("#chat-input-msg").val();
$("#chat-contents").append("<div class='input-msg'>"+chatInputMsg+"</div>");
$.ajax({
type: 'POST',
url: $("#chat-form").attr("action"),
contentType: 'application/json',
processData: false,
data: JSON.stringify({msg: chatInputmsg}),
success: function(response) {
console.log("received response ", response);
$("#chat-contents").append("<div class='chat-response'>"+response.msg+"</div>");
},
});
});
});
</script>
</body>
</html>
I haven't tested any of the code above. It is just meant to serve as a starting point to investigate and continue upon.