简体   繁体   中英

I have a python app locally that I am trying to interact with on my webpage with flask. How do I do this?

I have a chat frame on my html page that uses js to have the user type in a message and "talk" to a chatbot. I have the chatbot in a file stored locally. I am trying to call the function of the chatbot with the input data from the user. I am relatively new to Flask and just started learning about apis. Do I need to do a simultaneous get and post from the html file? Here's my flask code for the webpage:

@app.route("/therapist", methods=['GET', 'POST'])
def therapist():
    def therapist_chat():
        userText = request.args.get('msg')
        return chat(userText)
    return render_template("therapist.html")

Here's my html form data that also has js:

<div id="userInput">
              <input id="textInput" class="form-control" type="text" name="msg" placeholder="Type Your Message Here">
              <input id="buttonInput" class="btn btn-success form-control" type="submit" value="Send">
          </div>
      </div>
    </div>

  <script>
    function getResponse() {
        let userText = $("#textInput").val();
        let userHtml = '<p class="userText"><span>' + userText + '</span></p>';
        $("#textInput").val("");
        $("#chatbox").append(userHtml);
        document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
        $.get("/get", { msg: userText }).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 enter key is pressed
        if(e.which == 13) {
            getResponse();
        }
    });
    $("#buttonInput").click(function() {
        getResponse();
    });
    </script>

Here's my chatbot python file function:

def chat(str):
    while True:
        inp = input("You: ")
        if inp.lower() == "quit":
            break
        # uses the model to predict the best response from inp after bag of words is created for inp
        results = model.predict([bag_of_words(inp, words)])[0]
        # sort the prediction by most likely, finds the index with the largest number
        results_index = np.argmax(results)
        # then go thru and assign the probability to the actual tag
        tag = labels[results_index]
        # sets an error threshold that probability must be higher to output a response
        if results[results_index] > 0.7:
            # then looks at tag and choices a random response
            for tg in data["intents"]:
                if tg["tag"] == tag:
                    responses = tg["responses"]
            # prints the response
            print(random.choice(responses))
        else:
            noresponses = ["Why's that?", "Can you tell me more?", "Can you please elaborate?",
                           "We're here to try and help you, so can you please just tell us what is going on?"]
            print(random.choice(noresponses))

The api routing is really screwing me up.

The easiest fix I can think of is just fix this:

@app.route("/therapist", methods=['GET', 'POST'])
def therapist():
    def therapist_chat():
        userText = request.args.get('msg')
        return chat(userText)
    return render_template("therapist.html")

into:

@app.route("/therapist", methods=['GET'])
def therapist():
    userText = request.args.get('msg')
    return chat(userText)

Basically, what I do here is that, when ever user types in something, a GET request will be called, and it will return a text generated by your chat bot.

However, you should first check to see if you can actually send a GET or not.

**Friendly note:

therapist , honestly, is a terrible choice of word for a route.. it's confusing..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM