首页 > 其他分享 >I can‘t link the chatbot model with react

I can‘t link the chatbot model with react

时间:2024-07-20 17:27:26浏览次数:13  
标签:chatbot react train link words output test import model

题意:我无法将聊天机器人模型 chatbot 与React连接起来

问题背景:

This is the model

from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import nltk
import numpy as np
import random
import pickle
from time import sleep
from nltk.stem.lancaster import LancasterStemmer
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from pathlib import Path
from pyngrok import ngrok

stemmer = LancasterStemmer()

# Load intents file
with open("intents2.json") as file:
    data = json.load(file)
    
app = Flask(__name__)
CORS(app)  # Enable CORS for all routes    

# Load preprocessed data or process it if not available
try:
    with open("data.pickle", "rb") as f:
        words, labels, training, output = pickle.load(f)
except:
    words = []
    labels = []
    docs_x = []
    docs_y = []

    for intent in data["intents"]:
        for pattern in intent["patterns"]:
            wrds = nltk.word_tokenize(pattern)
            words.extend(wrds)
            docs_x.append(wrds)
            docs_y.append(intent["tag"])

        if intent["tag"] not in labels:
            labels.append(intent["tag"])

    words = [stemmer.stem(w.lower()) for w in words if w != "?"]
    words = sorted(list(set(words)))

    labels = sorted(labels)

    training = []
    output = []

    out_empty = [0 for _ in range(len(labels))]

    for x, doc in enumerate(docs_x):
        bag = []

        wrds = [stemmer.stem(w) for w in doc]

        for w in words:
            if w in wrds:
                bag.append(1)
            else:
                bag.append(0)

        output_row = out_empty[:]
        output_row[labels.index(docs_y[x])] = 1

        training.append(bag)
        output.append(output_row)

    training = np.array(training)
    output = np.array(output)

    with open("data.pickle", "wb") as f:
        pickle.dump((words, labels, training, output), f)

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(training, output, test_size=0.2)

# Define the Keras model
model = Sequential()
model.add(Dense(20, input_shape=(len(X_train[0]),), activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(len(y_train[0]), activation='softmax'))

# Compile the model
model.compile(optimizer=Adam(learning_rate=0.01), loss='categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=1)

# Save the model
model.save("model.h5")

# Evaluate the model
y_train_pred = model.predict(X_train)
f1_train = f1_score(y_train.argmax(axis=1), y_train_pred.argmax(axis=1), average='weighted')
print(f"F1 Score (Training): {f1_train:.4f}")

test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test Loss: {test_loss:.4f}")
print(f"Test Accuracy: {test_acc:.4f}")

def bag_of_words(s, words):
    bag = [0 for _ in range(len(words))]

    s_words = nltk.word_tokenize(s)
    s_words = [stemmer.stem(word.lower()) for word in s_words]

    for se in s_words:
        for i, w in enumerate(words):
            if w == se:
                bag[i] = 1

    return np.array(bag)

@app.route('/chat', methods=['POST'])
def chat():
    user_input = request.form.get('message')
    if not user_input:
        return jsonify({"error": "No message provided"}), 400
    
    #print("Hi, How can I help you?")
    #while True:
     #   inp = input("You: ")
      #  if inp.lower() == "quit":
       #     break

    results = model.predict(np.array([bag_of_words(user_input, words)]))[0]
    results_index = np.argmax(results)
    tag = labels[results_index]
        
    if results[results_index] > 0.8:
        for tg in data["intents"]:
            if tg['tag'] == tag:
                responses = tg['responses']
        sleep(1)
        bot_response = random.choice(responses)
    else:
        bot_response = "I don't understand!"

    return jsonify({"response": bot_response})    
if __name__ == '__main__':
    # Set up ngrok
    ngrok.set_auth_token("2i16Qv3WbGVeggfwzrzUGEZbEK5_3d5kArxvbSNbwB6kQsJZA")
    public_url = ngrok.connect(5000).public_url
    print(" * ngrok tunnel \"{}\" -> \"http://127.0.0.1:5000/\"".format(public_url))

    # Run Flask app
    app.run(debug=True, use_reloader=False)

#chat()

this is the error i got while i tried to see the output i will get

I made AI model that answer your questions and in work well in python so i used flask to link it to front end i got the api link and try it on postman and it goes well but i can't link it with react

问题解决:

In your flask Code, at the top of your Chat Route you have:

user_input = request.form.get("message")

But in the flask Api, the form.get only works If the Data is NOT JSON. But INSIDE your fetch call in the react code, you JSON stringify your Message Object. Now the form.get function cannot get the Message. If you deleted the JSON.stringify INSIDE your Body, It should Work then.

标签:chatbot,react,train,link,words,output,test,import,model
From: https://blog.csdn.net/suiusoar/article/details/140574494

相关文章

  • /usr/lib/wsl/lib/libcuda.so.1 is not a symbolic link
    wsl中执行aptinstall或aptupgrade的时候会在最后有一个报错:/sbin/ldconfig.real:/usr/lib/wsl/lib/libcuda.so.1isnotasymboliclink意思是/usr/lib/wsl/lib/libcuda.so.1不是软链接。。。用ll看一下,这个确实不是软连接。不知道为啥需要这个必须是软链接。。-r-xr-xr-......
  • Society-Links-Taiwan朋友们的链接列表
    王彦仁https://wangyenjen.github.io/部落格,簡報名稱網址經歷侯欣緯競程筆記部落格2022國手賴昭勳slides入營考比賽策略2022國手吳柏燁部落格CSESsolution20222!李政遠部落格wikiNHDK講師UMDCS李旺陽slides20152!王淇部落格202......
  • 案例研究:小企业利用PlugLink的运营革新(附源码)
    PlugLink:小企业运营自动化的利器在当今快速发展的商业环境中,小企业面临的挑战之一是资源有限,尤其是人力资源和时间。为了在这个竞争激烈的市场中保持竞争力,小企业必须找到创新的方法来提高效率和生产力。这就是PlugLink发挥作用的地方。PlugLink是一个开源的自动化框架,它允......
  • [react] react18核心语法
    react项目的目录结构public文件夹用于存放静态页面资源,src文件夹用于存放react关键代码。如何创建项目npxcreate-react-app项目名记得安装nodejs环境Windows下使用命令提示符或者powershell创建,Linux或macos使用对应的shell创建。出现上图内容即为创建成功。一些杂乱......
  • 【大数据专题】Flink题库
    1.简述什么是ApacheFlink?ApacheFlink是一个开源的基于流的有状态计算框架。它是分布式地执行的,具备低延迟、高吞吐的优秀性能,并且非常擅长处理有状态的复杂计算逻辑场景2.简述Flink的核心概念?Flink的核心概念主要有四个:EventStreams、State、Time和Snapsho......
  • 链表(Linked List)-Python实现-使用类和使用函数
    链表链表(LinkedList)单链表(SinglyLinkedList)节点类(NodeClass)链表类(LinkedListClass)使用链表类不用类的方法实现链表实现单链表使用函数实现链表具体讲解类的方法实现链表Node类LinkedList类不用类的方法实现链表创建节点添加节点删除节点搜索节点显示链表总......
  • yearrecord——一个类似痕迹墙的React数据展示组件
    yearrecord——一个类似痕迹墙的React数据展示组件 介绍一下自己做的一个类似于力扣个人主页提交记录和GitHub主页贡献记录的React组件。下图分别是力扣个人主页提交记录和GitHub个人主页的贡献记录,像这样类似痕迹墙的形式可以比较直观且高效得展示一段时间内得数据记录。......
  • 日常工作中需要避免的9个React坏习惯
    日常工作中需要避免的9个React坏习惯前言React是前端开发领域中最受欢迎的JavaScript库之一,但有时候在编写React应用程序时,可能陷入一些不佳的习惯和错误做法。这些不佳的习惯可能导致性能下降、代码难以维护,以及其他问题。在本文中,我们将探讨日常工作中应该避免的9个坏React......
  • Java中的流式数据处理与Apache Flink应用
    Java中的流式数据处理与ApacheFlink应用大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天,我们将探讨如何使用Java与ApacheFlink进行流式数据处理。ApacheFlink是一个开源的流处理框架,支持大规模数据流的实时处理和分析。它以其高性能、低延迟和强大......
  • [email protected](62)[email protected](11)- 中间件2 - redux-thunk
    目录1,介绍举例2,原理和实现实现3,注意点1,介绍一般情况下,action是一个平面对象,并会通过纯函数来创建。exportconstcreateAddUserAction=(user)=>({type:ADD_USER,payload:user,});这样是有一些限制的无法使用异步的,比如在请求接口之后再做一......