[英]How to pass variables/functions from javaScript to Python and vice versa?
我正在 HTML、CSS 和 JavaScript 創建一個網站,我需要一個 AI 驅動的聊天機器人。 我有所需的 python 文件,其中包含聊天機器人(AI、NLTK)的邏輯。 現在,在 python 文件中,我有一個名為“response()”的 function,它將用戶消息作為參數並在運行 NLP 邏輯后返回處理后的響應。 我想要做的是,一旦用戶發送消息,
JavaScript 將該消息存儲在一個變量中(比如用戶響應),並且應該將該變量作為參數發送給 python 文件的“response()” function: response(user-response)
Python文件應該使用響應(user-response)function並將處理后的output發送到JavaScript文件
我如何實現這一目標?
這是 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
這是 JavaScript 代碼
function returnsUserMessage(){
var userResponse = document.getElementById('input-chat').value;
console.log(userResponse);
return userResponse;
}
我將通過幾個步驟幫助您完成 go,但正如@Pointy 在評論中所說,“對於單個 Stack Overflow 問題,您究竟如何完成所有這些是一個非常大的主題”,因此請將其視為路線圖。
旁注:我假設您不想在前端執行 AI 邏輯,因為這對客戶端來說很繁重。
1- 使用 Python 創建后端服務器(或 REST API)。
2- 在 HTTP 請求 (GET/POST) 中注入您的 AI 邏輯。
后端是一個很大的話題,但我將在這里提供一個小例子:
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- 從前端將用戶輸入發送到后端(使用您在第 2 步中創建的 HTTP 請求),然后寫回響應。
例子:
<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.