Ошибка возврата массива для контекста в фляге; Функция просмотра не вернула ответ - PullRequest
0 голосов
/ 19 апреля 2020

Я пытаюсь вернуть ответ из файла json, и он не прошел из-за того, что flask не прошел проверку контекста context_filtering, которая есть в функции chat(user_inp). chat(user_inp) проверяет данные json для context_set и проверяет следующий тег намерений, является ли тот факт, что context_filter совпадает с context_set, логика c выглядит нормально, но не удалось чтобы вернуть ответ, и ошибка была подсказка: View function did not return a response.

app_1.py

app = Flask(__name__)
CORS(app, support_credentials=True)


@app.route('/', methods=['GET', 'POST'])
def session():
    return render_template('index.html')


def chat(user_inp):
    inp = user_inp
    results = model.predict([BagOfWords(inp, words)])[0]
    results_index = numpy.argmax(results)
    tag = labels[results_index]
    context = []

    if results[results_index] > 0.7:
        for tg in data["intents"]:
            if tg['tag'] == tag:
                if 'context_set' in tg:
                    context = tg['context_set']
                if not 'context_filter' in tg or ('context_filter' in tg and tg['context_filter'] == context):
                    responses = tg['responses']
                    return random.choice(responses)
    else:
        return "Sorry, I can't understand what are you asking for. Pleas ask another question or be more specific."


@app.route("/send", methods=['GET'])
def post_bot_response():
    usr_inp = request.args.get('msg')
    res = chat(usr_inp)
    return res


if __name__ == '__main__':
    app.run(debug=True, port=8009)

Примеры моих JSON элементов:

{"tag": "greeting",
         "patterns": ["Hey", "Is anyone there?", "Hello", "Whats up", "Hi"],
         "responses": ["Hello there, how are you?", "Hi, you alright?"],
         "context_set": "reply_greet"
        },
        {"tag": "reply_good",
         "patterns": ["I feel great", "I'm fine. Thank you", "I feel amazing", "I'm feeling wonderful", "I'm alright", "I'm ok", "Im good"],
         "responses": ["That great to hear. Nice."],
         "context_filter": "reply_greet"
        },
        {"tag": "reply_bad",
         "patterns": ["I dont feel fine", "I'm not ok", "I dont feel great"],
         "responses": ["Oh no, I'm sorry to hear that."],
         "context_filter": "reply_greet"
        }

И мои html, которые отправляют входные данные бэкэнду и выводят его sh на внешний интерфейс после того, как бот получит ответ. index.html

<button class="open-button" onclick="openChat()">Click here to chat with me</button>

    <div class="chatPopUp" id="chat-PopUp">
        <div id="chatBox" class="chatContainer">
            <p class="botText"><span>Hi! I'm a chatbot, how can I help you today?</span></p>
        </div>
        <input id="textInput" type="text" name="msg" placeholder="Message"/>
        <input type="submit" class="SubmitMsg" value="Send" onclick="getBotResponse()"/>
        <button type="button" class="btn_cancel" onclick="closeChat()">Close</button>
    </div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
    function getBotResponse() {
        var rawText = $("#textInput").val();
        var userHtml = '<p class="userText">You: <span>' + rawText + "</span></p>";
        $("#textInput").val("");
        $("#chatBox").append(userHtml);
        document
        .getElementById("textInput")
        .scrollIntoView({ block: "start", behavior: "smooth" });
        $.get("http://127.0.0.1:8009/send", { msg: rawText }).done(function(data) {
        var botHtml = '<p class="botText">Bot: <span>' + data + "</span></p>";
        $("#chatBox").append(botHtml);
        document.getElementById("textInput")
        .scrollIntoView({ block: "start", behavior: "smooth" });
        });
    }
    $("#textInput").keypress(function(e)  {
    if (e.which == 13) {
        getBotResponse();
    }
</script>```
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...