I can‘t link the chatbot model with react

news2024/9/22 2:04:33

题意:我无法将聊天机器人模型 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.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1943472.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

英特尔终于宣布了解决CPU崩溃和不稳定性问题的方法,声称过高的电压是根本原因;补丁预计将于8月中旬推出【更新】

英特尔终于宣布了解决CPU崩溃和不稳定性问题的方法,声称过高的电压是根本原因;补丁预计将于8月中旬推出【更新】 英特尔官方宣布,已找到困扰其CPU的崩溃问题的根本原因,并将于8月中旬前发布微码更新以解决这一问题,从而…

聊聊 C# 中的顶级语句

前言 在 C# 9.0 版本之前,即使只编写一行输出 “Hello world” 的 C# 代码,也需要创建一个 C# 类,并且需要为这个 C# 类添加 Main 方法,才能在 Main 方法中编写代码。从 C# 9.0 开始,C# 增加了 “顶级语句” 语法&…

获取对象碎片情况

查看oracle数据库表上碎片 先创建个函数 FUNCTION get_space_usage1(owner IN VARCHAR2,object_name IN VARCHAR2,segment_type IN VARCHAR2,partition_name IN VARCHAR2 DEFAULT NULL) RETURN sys.DBMS_DEBUG_VC2COLL PIPELINEDASufbl NUMBER;ufby NUMBER;fs1bl NUMBER…

赋值运算符重载和运算符重载

1.运算符重载 在C中,运算符重载是一种强大的特性,它允许我们为已有的运算符赋予新的意义,以便它们能够应用于自定义类型上。 这一特性极大地增强了C的表达能力,使得自定义类型的使用更加直观和自然。例如,如果我们定义…

【区块链+绿色低碳】包头林草市域碳中和体系建设项目 | FISCO BCOS应用案例

在双碳体系建设背景下,政府、企业都在积极探索碳中和价值实现路径。但是在林业碳汇场景中,存在着林权认证、 身份授权、多方机构协作、数据交换等流程,在这些复杂的业务协作中存在一些风险,如:身份信息泄漏、数据造假、…

BSV区块链技术现实应用原理解析

BSV区块链以其卓越的可扩展性、坚如磐石的安全性、极低的交易成本等特性,成为满足企业当下需求并为企业未来成功奠基铺路的理想技术。 BSV协会近期发布了一个题为《驾驭数字化转型:在自动化世界中建立信任——区块链在数据保护和交易优化中的角色》的报…

Java代码基础算法练习-竞猜卡片值-2024.07.22

任务描述: 小米和小王玩竞猜游戏:准备7张卡片包含数字2、3、4、5、6、7、8,从中抽出2张(有 顺序之分,抽2、3跟抽3、2是两种情况),猜2张卡片的和,如果是奇数,则猜对。小米…

mmpretrain报错解决记录-socket.gaierror: [Errno -2] Name or service not known

在使用Beit模型时出现 mmengine - INFO - load model from: https://download.openmmlab.com/mmselfsup/1.x/target_generator_ckpt/dalle_encoder.pth 07/19 11:27:30 - mmengine - INFO - Loads checkpoint by http backend from path: https://download.openmmlab.com/mmsel…

unity2022 il2cpp 源码编译

新建一个XCODE静态库工程 从unity安装目录中找到il2cpp源码 Editor\Data\il2cpp\ 改名 il2cpp/libil2cpp -> il2cpp/il2cpp 加入工程中 ->工程根目录 extends/zlib libil2cpp/ buildSettings 相关设置 IOS Deployment Target ios 12.0 Header Search Paths $(in…

总结——TI_音频信号分析仪

一、简介 设备:MSPM0G3507 库:CMSIS-DSP TI 数据分析:FFT 软件:CCS CLion MATLAB 目的:对音频信号进行采样(滤波偏置处理),通过FFT获取信号的频率成分&am…

7.23模拟赛总结 [数据结构优化dp] + [神奇建图]

目录 复盘题解T2T4 复盘 浅复盘下吧… 7:40 开题 看 T1 ,起初以为和以前某道题有点像,子序列划分,注意到状态数很少,搜出来所有状态然后 dp,然后发现这个 T1 和那个毛关系没有 浏览了一下,感觉 T2 题面…

前端(1)HTML

1、标签 创建1.html文件&#xff0c;浏览器输入E:/frontheima/1.html&#xff0c;可以访问页面 页面展示 在VSCODE安装IDEA的快捷键&#xff0c;比如ctld复制一行、ctrlx剪切 <p id"p1" title"标题1">Hello,world!</p> <p id"p2"…

Java | Leetcode Java题解之第268题丢失的数字

题目&#xff1a; 题解&#xff1a; class Solution {public int missingNumber(int[] nums) {int n nums.length;int total n * (n 1) / 2;int arrSum 0;for (int i 0; i < n; i) {arrSum nums[i];}return total - arrSum;} }

[排序]hoare快速排序

今天我们继续来讲排序部分&#xff0c;顾名思义&#xff0c;快速排序是一种特别高效的排序方法&#xff0c;在C语言中qsort函数&#xff0c;底层便是用快排所实现的&#xff0c;快排适用于各个项目中&#xff0c;特别的实用&#xff0c;下面我们就由浅入深的全面刨析快速排序。…

PHP接入consul,注册服务和发现服务【学习笔记】

PHP接入consul,注册服务和发现服务 consul安装 链接: consul安装 启动consul C:\Users\14684>consul agent -dev安装TP5 composer create-project topthink/think5.0.* tp5_pro --prefer-dist配置consul 创建tp5_pro/application/service/Consul.php <?php /*****…

环境变量配置文件中两种路径添加方式

环境变量配置文件中两种路径添加方式 文章目录 环境变量配置文件中两种路径添加方式代码示例区别和作用 代码示例 export HBASE_HOME/opt/software/hbase-2.3.5 export PATH$PATH:$HBASE_HOME/binexport SPARK_HOME/opt/software/spark-3.1.2 export PATH$SPARK_HOME/bin:$PAT…

【MySQL是怎样运行的 | 第一篇】Explain执行计划上

文章目录 1.查询优化-Explain语句详解上1.1前言1.2执行计划输出各列详解1.2.1 table1.2.2 id1.2.3 select_type1.2.4 partitions1.2.5 type1.2.6 possible_keys和key1.2.7 key_len1.2.8 ref1.2.9 rows 世纪晚霞 1.查询优化-Explain语句详解上 1.1前言 一条查询语句在经过 MyS…

在 CentOS 7 上安装 Docker 并安装和部署 .NET Core 3.1

1. 安装 Docker 步骤 1.1&#xff1a;更新包索引并安装依赖包 先安装yum的扩展&#xff0c;yum-utils提供了一些额外的工具&#xff0c;这些工具可以执行比基本yum命令更复杂的任务 sudo yum install -y yum-utils sudo yum update -y #更新系统上已安装的所有软件包到最新…

视频分帧【截取图片】(YOLO目标检测【生成数据集】)

高效率制作数据集【按这个流程走&#xff0c;速度很顶】 本次制作&#xff0c;1059张图片【马路上流动车辆】 几乎就是全自动了&#xff0c;只要视频拍得好&#xff0c;YOLO辅助制作数据集就效率极高 视频中的图片抽取&#xff1a; 【由于视频内存过大&#xff0c;遇到报错执行…

2024导游资格考试,这些材料提前准备✅

2024年导游考试报名本月开始&#xff01; &#x1f499;大家提前准备好报名材料 1、个人近期白底1寸证件照。 2、身份证照片 3、学历照片 4、健康证明或健康承诺书 5、其他需要上传的材料 &#x1f499;照片文件不通过原因汇总&#xff0c;记得避开这些坑&#xff01; &#x1…