0

I am trying to make a Flask app for a chatbot. My bot code is in main.py, my flask code is in app.py. The flask app will make calls to the chat() function in main.py. I want to take inputs from the user and also print it along with the return from the chat() function.

So far, I got this.

Here is my main.py

def chat():

print("Bot: Hello! How can I help? (type 'quit' to stop)")
while True:
    inp = input("You: ")
    if inp.lower() == "quit":
        break

    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']
    print("Bot: ", random.choice(responses))

Here is my app.py

from flask import Flask, render_template, url_for, request, redirect
from datetime import datetime
from main import chat

DEBUG = True
app = Flask(__name__)
@app.route('/')
def index():


if __name__ == "__main__":
    app.run(debug=True)

Please guide me, on how to achieve it.

2 Answers2

0

Welcome to SO!

HTTP does work with request and response. For each request your Flask server receives (on an endpoint, cf. What is an 'endpoint' in Flask?), you can do some logic with your python script and send the results as response, like so:

@app.route('/chatbot/', methods=['GET', 'POST'])
def question():
    # request.args is to get urls arguments 
    if request.method == 'GET':
        data = { "message": "Hi, how can I help you?" }
        return jsonify(isError= False, message="Success", statusCode=200, data=data), 200

    # request.form to get form parameter
    if request.method == 'POST':
        // get your user data from the `requests` object
        inp = ...

        results = model.predict([bag_of_words(inp, words)])
        results_index = numpy.argmax(results)
        tag = labels[results_index]
        for tg in data["intents"]:
            if tg['tag'] == tag:
                responses = tg['responses']
        data = { "message": random.choice(responses) }
        return jsonify(isError=False, message="Success", statusCode=200, data=data), 200

This merely shows you how it could be done, however, the code does not compile out of the box. Now it is up to you to catch on with the Flask docs and improve on this piece of code or start from scratch. :-)

tafaust
  • 1,457
  • 16
  • 32
0

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.

suryasankar
  • 4,821
  • 2
  • 14
  • 13