Search code examples
javascriptpythonartificial-intelligencenltk

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. I have the required python file which consists of the logic for the chatbot (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. 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)

  2. The Python file should use the response(user-response) function and send the processed output to the JavaScript file

How do I achieve this?

Here's the python logic

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

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


Solution

  • 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.

    Side note: I assume you don't want to execute the AI logic in the frontend as this will be heavy on the client.

    1- Create a backend server (or REST API) with Python.

    2- Inject your AI logic in HTTP requests (GET/POST).

    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.

    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>