如何将Python集成到我的JavaScript代码中?

huangapple go评论77阅读模式
英文:

How can I integrate python into my javascript code?

问题

I have programmed a ChatBot with Spacy in Python, which I now want to integrate somehow into my website (with HTML and JavaScript), as I have made an interface in HTML for the bot. But my webserver doesn't support Python so I have to do it somehow via JavaScript or something. My code:

import spacy
import random

# load NLP model
nlp = spacy.load("en_core_news_sm")
nlp.max_length = 10000000

# load text from file
with open("deutsch_corpus.txt", encoding='utf-8') as f:
    text = f.read()

# parse text with NLP model
doc = nlp(text)

# define function to generate bot response
def generate_response(user_input):
    # parse user input with NLP model
    user_doc = nlp(user_input)

    # check if the user input contains information that should be stored
    remember = False
    remember_text = ""
    for sent in user_doc.sents:
        if any(word in sent.text.lower() for word in ["I am", "my friend", "my girlfriend", "I was", "I have", "I have", "my mother is", "my mother is", "I would be", "I find", "my name is"]):
            remember = True
            remember_text = sent.text
            break

    # If the user input contains information to remember, store it in the memory file
    if remember:
        remember_text = remember_text.lower()
        with open("german_corpus.txt", "a", encoding='utf-8') as f:
            f.write(remember_text.replace("ich bin", "Du bist").replace("mein", "Dein").replace("meine", "Deine").replace("meine mutter ist", "deine Mutter ist").replace("meine freundin ist", "deine Freundin ist"). replace("would have", "would have").replace("have", "have").replace("have", "have").replace("I would be", "you would be").replace("I find", "you find").replace("my name", "your name is").replace("my name is", "your name is") + "\n")
        return "Ok, I'll remember that!"

    # search for sentences in the corpus that are similar to the user input
    similarity_scores = []
    for sentence in doc.sents:
        score = sentence.similarity(user_doc)
        similarity_scores.append((sentence, score))

    # sort sentences by similarity score
    similarity_scores.sort(key=lambda x: x[1], reverse=True)

    # if no similar sentence is found, a random answer is returned
    if similarity_scores[0][1] < 0.5:
        return "Sorry, I don't understand."

    # Return the most similar sentence as a bot response.
    return similarity_scores[0][0].text

... and my HTML Code:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TalkyAI</title>
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="#">KI trainieren</a></li>
                <li><a href="#" class="active">Chat</a></li>
                <li><a href="#">Account</a></li>
            </ul>
            <div class="logout-btn"><a href="#">Abmelden</a></div>
        </nav>
    </header>
    <main>
        <div id="chat-container">
            <div id="chat-output"></div>
            <div id="chat-input">
                <input type="text" id="message-input" placeholder="Gib deine Nachricht ein...">
                <button id="send-btn">Senden</button>
            </div>
        </div>
    </main>
    <script>

    </script>
</body>
</html>

I already tried to translate my code to JavaScript, which all didn't really work (NLP, Tensorflow, etc.) and my code doesn't work like it does in Python.

英文:

I have programmed a ChatBot with Spacy in Python, which I now want to integrate somehow into my website (with HTML and JavaScript), as I have made an interface in HTML for the bot. But my webserver doesn't support Python so I have to do it somehow via JavaScript or something. My code:

import spacy
import random
# load NLP model
nlp = spacy.load(&quot;en_core_news_sm&quot;)
nlp.max_length = 10000000
# load text from file
with open(&quot;deutsch_corpus.txt&quot;, encoding=&#39;utf-8&#39;) as f:
text = f.read()
# parse text with NLP model
doc = nlp(text)
# define function to generate bot response
def generate_response(user_input):
# parse user input with NLP model
user_doc = nlp(user_input)
# check if the user input contains information that should be stored
remember = False
remember_text = &quot;&quot;
for sent in user_doc.sents:
if any(word in sent.text.lower() for word in [&quot;I am&quot;, &quot;my friend&quot;, &quot;my girlfriend&quot;, &quot;I was&quot;, &quot;I have&quot;, &quot;I have&quot;, &quot;my mother is&quot;, &quot;my mother is&quot;, &quot;I would be&quot;, &quot;I find&quot;, &quot;my name is&quot;]):
remember = True
remember_text = sent.text
break
# If the user input contains information to remember, store it in the memory file
if remember:
remember_text = remember_text.lower()
with open(&quot;german_corpus.txt&quot;, &quot;a&quot;, encoding=&#39;utf-8&#39;) as f:
f.write(remember_text.replace(&quot;ich bin&quot;, &quot;Du bist&quot;).replace(&quot;mein&quot;, &quot;Dein&quot;).replace(&quot;meine&quot;, &quot;Deine&quot;).replace(&quot;meine mutter ist&quot;, &quot;deine Mutter ist&quot;).replace(&quot;meine freundin ist&quot;, &quot;deine Freundin ist&quot;). replace(&quot;would have&quot;, &quot;would have&quot;).replace(&quot;have&quot;, &quot;have&quot;).replace(&quot;have&quot;, &quot;have&quot;).replace(&quot;I would be&quot;, &quot;you would be&quot;).replace(&quot;I find&quot;, &quot;you find&quot;).replace(&quot;my name&quot;, &quot;your name is&quot;).replace(&quot;my name is&quot;, &quot;your name is&quot;) + &quot;\n&quot;)
return &quot;Ok, I&#39;ll remember that!&quot;
# search for sentences in the corpus that are similar to the user input
similarity_scores = []
for sentence in doc.sents:
score = sentence.similarity(user_doc)
similarity_scores.append((sentence, score))
# sort sentences by similarity score
similarity_scores.sort(key=lambda x: x[1], reverse=True)
# if no similar sentence is found, a random answer is returned
if similarity_scores[0][1] &lt; 0.5:
return &quot;Sorry, I don&#39;t understand.&quot;
# Return most similar sentence as bot response.
return similarity_scores[0][0].text

... and my HTML Code:

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;de&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;upgrade-insecure-requests&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;title&gt;TalkyAI&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;header&gt;
&lt;nav&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#&quot;&gt;KI trainieren&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#&quot; class=&quot;active&quot;&gt;Chat&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Account&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;logout-btn&quot;&gt;&lt;a href=&quot;#&quot;&gt;Abmelden&lt;/a&gt;&lt;/div&gt;
&lt;/nav&gt;
&lt;/header&gt;
&lt;main&gt;
&lt;div id=&quot;chat-container&quot;&gt;
&lt;div id=&quot;chat-output&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;chat-input&quot;&gt;
&lt;input type=&quot;text&quot; id=&quot;message-input&quot; placeholder=&quot;Gib deine Nachricht ein...&quot;&gt;
&lt;button id=&quot;send-btn&quot;&gt;Senden&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/main&gt;
&lt;script&gt;
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

I already tried to translate my code to JavaScript, which all didn't really work (NLP, Tensorflow, etc.) and my code doesn't work like it does in Python.

答案1

得分: 1

将您的Spacy聊天机器人集成到您的网站中的一种方法是使用Flask(一个Python Web框架)创建服务器端API,并从您网站的JavaScript代码中对API进行AJAX请求。

from flask import Flask, request, jsonify
import spacy

app = Flask(__name__)

@app.route('/api/chatbot', methods=['POST'])
def chatbot():
    #您的代码在此处
    return jsonify({'response': response})

if __name__ == '__main__':
    app.run(debug=True)

请注意,上述代码部分未被翻译。

英文:

One way to integrate your Spacy ChatBot into your website is to create a server-side API with Flask (a Python web framework) and make AJAX requests to the API from your website's JavaScript code.

from flask import Flask, request, jsonify
import spacy
app = Flask(__name__)
@app.route(&#39;/api/chatbot&#39;, methods=[&#39;POST&#39;])
def chatbot():
#your code here
return jsonify({&#39;response&#39;: response})
if __name__ == &#39;__main__&#39;:
app.run(debug=True)

答案2

得分: 0

目前,spaCy似乎只支持Python。spacy-js仅提供了JavaScript接口,但在底层仍然使用Python。我似乎找不到其他选项,除了为您的Web服务器创建一个Python API,这似乎是不可行的。

英文:

As of now, spaCy seems to support Python only. spacy-js just exposes a Javascript interface but still uses Python under the hood. I can't seem to find any options other than creating a Python API for your webserver, which seems to be out of the question.

huangapple
  • 本文由 发表于 2023年3月10日 00:56:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定