简体   繁体   English

如何将变量/函数从 javaScript 传递到 Python,反之亦然?

[英]How to pass variables/functions from javaScript to Python and vice versa?

I am creating a website in HTML, CSS and JavaScript where I require an AI powered chatbot.我正在 HTML、CSS 和 JavaScript 创建一个网站,我需要一个 AI 驱动的聊天机器人。 I have the required python file which consists of the logic for the chatbot (AI, NLTK).我有所需的 python 文件,其中包含聊天机器人(AI、NLTK)的逻辑。 Now, in the python file, I have a function named "response()" which takes the user message as an argument and returns the processed response after running the NLP logic.现在,在 python 文件中,我有一个名为“response()”的 function,它将用户消息作为参数并在运行 NLP 逻辑后返回处理后的响应。 What I want to do is, As soon as the user sends a message,我想要做的是,一旦用户发送消息,

  1. The JavaScript would store that message in a variable (say, user-response) and should send that variable as an argument to the python file's "response()" function: response(user-response) JavaScript 将该消息存储在一个变量中(比如用户响应),并且应该将该变量作为参数发送给 python 文件的“response()” function: response(user-response)

  2. The Python file should use the response(user-response) function and send the processed output to the JavaScript file Python文件应该使用响应(user-response)function并将处理后的output发送到JavaScript文件

How do I achieve this?我如何实现这一目标?

Here's the python logic这是 python 逻辑

def response(user_response):     #This argument has to be passed from JavaScript
    robo_response = ''
    sent_tokens.append(user_response)
    TfIdVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
    tfidf = TfIdVec.fit_transform(sent_tokens)
    vals = cosine_similarity(tfidf[-1], tfidf)
    idx = vals.argsort()[0][-2]
    flat = vals.flatten()
    flat.sort()
    req_tfidf = flat[-2]

    GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up", "hey")
    GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I'm glad you're talking to me"]
    for word in user_response.split():
        if (word.lower() in GREETING_INPUTS):
            return random.choice(GREETING_RESPONSES)


    if(req_tfidf == 0):
        robo_response = [
            "Sorry, I have not been trained to answer that yet!", 
            "Sorry, I cannot answer to that!
            ]
        return random.choice(robo_response);
        
        robo_response = robo_response+sent_tokens[idx]
        return robo_response;

response("")     #This response has to be sent back to JavaScript

Here's the JavaScript code这是 JavaScript 代码

function returnsUserMessage(){
    var userResponse = document.getElementById('input-chat').value;
    console.log(userResponse);
    return userResponse;
}

I will put few steps for you to go through but as @Pointy said in the comment, "Exactly how you do all that is a very large topic for a single Stack Overflow question", so consider this as a roadmap.我将通过几个步骤帮助您完成 go,但正如@Pointy 在评论中所说,“对于单个 Stack Overflow 问题,您究竟如何完成所有这些是一个非常大的主题”,因此请将其视为路线图。

Side note: I assume you don't want to execute the AI logic in the frontend as this will be heavy on the client.旁注:我假设您不想在前端执行 AI 逻辑,因为这对客户端来说很繁重。

1- Create a backend server (or REST API) with Python. 1- 使用 Python 创建后端服务器(或 REST API)。

2- Inject your AI logic in HTTP requests (GET/POST). 2- 在 HTTP 请求 (GET/POST) 中注入您的 AI 逻辑。

Backend is a big topic but I will provide a small example here:后端是一个很大的话题,但我将在这里提供一个小例子:

from flask import Flask, json, request

def response(user_response):
    ...
api = Flask(__name__)

@api.route('/response', methods=['POST'])
def post_response():
  user_response = json.loads(request.json)["user_response"]
  return json.dumps({response: response(user_response)})

if __name__ == '__main__':
    api.run()

3- From the frontend, send the user input to the backend (using the HTTP request you created in step 2) and then write back the response. 3- 从前端将用户输入发送到后端(使用您在第 2 步中创建的 HTTP 请求),然后写回响应。

Example:例子:

<button onclick="returnsUserMessage()">Send</button>

<script>
async function returnsUserMessage() {
  var user_input = document.getElementById("input-chat").value;
  var bot_reponse = await fetch('localhost/response',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({user_response: user_input})
    });
  // Then you need to present the bot response in your element
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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