Skip to content

Commit 7070c71

Browse files
authored
Add files via upload
1 parent 550f2c8 commit 7070c71

15 files changed

+1075
-2
lines changed

README.md

+37-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,37 @@
1-
# CHAT_BOT_PYTHON
2-
THIS IS CHAT BOT BUILD IN PYTHON
1+
# Chatbot Deployment with Flask and JavaScript
2+
3+
4+
5+
## Initial Setup:
6+
This repo currently contains the starter files.
7+
8+
Clone repo and create a virtual environment
9+
```
10+
$ git clone https://github.com/python-engineer/chatbot-deployment.git
11+
$ cd chatbot-deployment
12+
$ python3 -m venv venv
13+
$ . venv/bin/activate
14+
```
15+
Install dependencies
16+
```
17+
$ (venv) pip install Flask torch torchvision nltk
18+
```
19+
Install nltk package
20+
```
21+
$ (venv) python
22+
>>> import nltk
23+
>>> nltk.download('punkt')
24+
```
25+
Modify `intents.json` with different intents and responses for your Chatbot
26+
27+
Run
28+
```
29+
$ (venv) python train.py
30+
```
31+
This will dump data.pth file. And then run
32+
the following command to test it in the console.
33+
```
34+
$ (venv) python chat.py
35+
```
36+
37+

app.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from flask import Flask,render trmplate, request,jsonify
2+
from flask_cors import CORS
3+
4+
from chat import get_response
5+
6+
app=Flask(__name__)
7+
CORS(app)
8+
9+
10+
11+
12+
@app.post("/predict")
13+
14+
15+
def predictt():
16+
text = request.get_json().get("message")
17+
18+
#check text is valied
19+
20+
responce =get_response(text)
21+
message ={"answer":responce}
22+
23+
return jsonify(message)
24+
25+
26+
if __name__ == '__main__':
27+
app.run(debug=True)

chat.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import random
2+
import json
3+
4+
import torch
5+
6+
from model import NeuralNet
7+
from nltk_utils import bag_of_words, tokenize
8+
9+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
10+
11+
with open('intents.json', 'r') as json_data:
12+
intents = json.load(json_data)
13+
14+
FILE = "data.pth"
15+
data = torch.load(FILE)
16+
17+
input_size = data["input_size"]
18+
hidden_size = data["hidden_size"]
19+
output_size = data["output_size"]
20+
all_words = data['all_words']
21+
tags = data['tags']
22+
model_state = data["model_state"]
23+
24+
model = NeuralNet(input_size, hidden_size, output_size).to(device)
25+
model.load_state_dict(model_state)
26+
model.eval()
27+
28+
bot_name = "Sam"
29+
30+
def get_response(msg):
31+
sentence = tokenize(msg)
32+
X = bag_of_words(sentence, all_words)
33+
X = X.reshape(1, X.shape[0])
34+
X = torch.from_numpy(X).to(device)
35+
36+
output = model(X)
37+
_, predicted = torch.max(output, dim=1)
38+
39+
tag = tags[predicted.item()]
40+
41+
probs = torch.softmax(output, dim=1)
42+
prob = probs[0][predicted.item()]
43+
if prob.item() > 0.75:
44+
for intent in intents['intents']:
45+
if tag == intent["tag"]:
46+
return random.choice(intent['responses'])
47+
48+
return "I do not understand..."
49+
50+
51+
if __name__ == "__main__":
52+
print("Let's chat! (type 'quit' to exit)")
53+
while True:
54+
# sentence = "do you use credit cards?"
55+
sentence = input("You: ")
56+
if sentence == "quit":
57+
break
58+
59+
resp = get_response(sentence)
60+
print(resp)
61+

intents.json

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
{
2+
"intents": [
3+
{
4+
"tag": "greeting",
5+
"patterns": [
6+
"Hi",
7+
"Hey",
8+
"How are you",
9+
"Is anyone there?",
10+
"Hello",
11+
"Good day"
12+
],
13+
"responses": [
14+
"Hey :-)",
15+
"Hello, thanks for visiting",
16+
"Hi there, what can I do for you?",
17+
"Hi there, how can I help?"
18+
]
19+
},
20+
{
21+
"tag": "goodbye",
22+
"patterns": ["Bye", "See you later", "Goodbye"],
23+
"responses": [
24+
"See you later, thanks for visiting",
25+
"Have a nice day",
26+
"Bye! Come back again soon."
27+
]
28+
},
29+
{
30+
"tag": "thanks",
31+
"patterns": ["Thanks", "Thank you", "That's helpful", "Thank's a lot!"],
32+
"responses": ["Happy to help!", "Any time!", "My pleasure"]
33+
},
34+
{
35+
"tag": "items",
36+
"patterns": [
37+
"Which items do you have?",
38+
"What kinds of items are there?",
39+
"What do you sell?"
40+
],
41+
"responses": [
42+
"We sell coffee and tea",
43+
"We have coffee and tea"
44+
]
45+
},
46+
{
47+
"tag": "payments",
48+
"patterns": [
49+
"Do you take credit cards?",
50+
"Do you accept Mastercard?",
51+
"Can I pay with Paypal?",
52+
"Are you cash only?"
53+
],
54+
"responses": [
55+
"We accept VISA, Mastercard and Paypal",
56+
"We accept most major credit cards, and Paypal"
57+
]
58+
},
59+
{
60+
"tag": "delivery",
61+
"patterns": [
62+
"How long does delivery take?",
63+
"How long does shipping take?",
64+
"When do I get my delivery?"
65+
],
66+
"responses": [
67+
"Delivery takes 2-4 days",
68+
"Shipping takes 2-4 days"
69+
]
70+
},
71+
{
72+
"tag": "funny",
73+
"patterns": [
74+
"Tell me a joke!",
75+
"Tell me something funny!",
76+
"Do you know a joke?"
77+
],
78+
"responses": [
79+
"Why did the hipster burn his mouth? He drank the coffee before it was cool.",
80+
"What did the buffalo say when his son left for college? Bison."
81+
]
82+
}
83+
]
84+
}

model.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import torch
2+
import torch.nn as nn
3+
4+
5+
class NeuralNet(nn.Module):
6+
def __init__(self, input_size, hidden_size, num_classes):
7+
super(NeuralNet, self).__init__()
8+
self.l1 = nn.Linear(input_size, hidden_size)
9+
self.l2 = nn.Linear(hidden_size, hidden_size)
10+
self.l3 = nn.Linear(hidden_size, num_classes)
11+
self.relu = nn.ReLU()
12+
13+
def forward(self, x):
14+
out = self.l1(x)
15+
out = self.relu(out)
16+
out = self.l2(out)
17+
out = self.relu(out)
18+
out = self.l3(out)
19+
# no activation and no softmax at the end
20+
return out

nltk_utils.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import numpy as np
2+
import nltk
3+
# nltk.download('punkt')
4+
from nltk.stem.porter import PorterStemmer
5+
stemmer = PorterStemmer()
6+
7+
8+
def tokenize(sentence):
9+
"""
10+
split sentence into array of words/tokens
11+
a token can be a word or punctuation character, or number
12+
"""
13+
return nltk.word_tokenize(sentence)
14+
15+
16+
def stem(word):
17+
"""
18+
stemming = find the root form of the word
19+
examples:
20+
words = ["organize", "organizes", "organizing"]
21+
words = [stem(w) for w in words]
22+
-> ["organ", "organ", "organ"]
23+
"""
24+
return stemmer.stem(word.lower())
25+
26+
27+
def bag_of_words(tokenized_sentence, words):
28+
"""
29+
return bag of words array:
30+
1 for each known word that exists in the sentence, 0 otherwise
31+
example:
32+
sentence = ["hello", "how", "are", "you"]
33+
words = ["hi", "hello", "I", "you", "bye", "thank", "cool"]
34+
bog = [ 0 , 1 , 0 , 1 , 0 , 0 , 0]
35+
"""
36+
# stem each word
37+
sentence_words = [stem(word) for word in tokenized_sentence]
38+
# initialize bag with 0 for each word
39+
bag = np.zeros(len(words), dtype=np.float32)
40+
for idx, w in enumerate(words):
41+
if w in sentence_words:
42+
bag[idx] = 1
43+
44+
return bag

standalone-frontend/app.js

+91
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
class Chatbox {
2+
constructor() {
3+
this.args = {
4+
openButton: document.querySelector('.chatbox__button'),
5+
chatBox: document.querySelector('.chatbox__support'),
6+
sendButton: document.querySelector('.send__button')
7+
}
8+
9+
this.state = false;
10+
this.messages = [];
11+
}
12+
13+
display() {
14+
const {openButton, chatBox, sendButton} = this.args;
15+
16+
openButton.addEventListener('click', () => this.toggleState(chatBox))
17+
18+
sendButton.addEventListener('click', () => this.onSendButton(chatBox))
19+
20+
const node = chatBox.querySelector('input');
21+
node.addEventListener("keyup", ({key}) => {
22+
if (key === "Enter") {
23+
this.onSendButton(chatBox)
24+
}
25+
})
26+
}
27+
28+
toggleState(chatbox) {
29+
this.state = !this.state;
30+
31+
// show or hides the box
32+
if(this.state) {
33+
chatbox.classList.add('chatbox--active')
34+
} else {
35+
chatbox.classList.remove('chatbox--active')
36+
}
37+
}
38+
39+
onSendButton(chatbox) {
40+
var textField = chatbox.querySelector('input');
41+
let text1 = textField.value
42+
if (text1 === "") {
43+
return;
44+
}
45+
46+
let msg1 = { name: "User", message: text1 }
47+
this.messages.push(msg1);
48+
49+
fetch('http://127.0.0.1:5000/predict', {
50+
method: 'POST',
51+
body: JSON.stringify({ message: text1 }),
52+
mode: 'cors',
53+
headers: {
54+
'Content-Type': 'application/json'
55+
},
56+
})
57+
.then(r => r.json())
58+
.then(r => {
59+
let msg2 = { name: "Sam", message: r.answer };
60+
this.messages.push(msg2);
61+
this.updateChatText(chatbox)
62+
textField.value = ''
63+
64+
}).catch((error) => {
65+
console.error('Error:', error);
66+
this.updateChatText(chatbox)
67+
textField.value = ''
68+
});
69+
}
70+
71+
updateChatText(chatbox) {
72+
var html = '';
73+
this.messages.slice().reverse().forEach(function(item, index) {
74+
if (item.name === "Sam")
75+
{
76+
html += '<div class="messages__item messages__item--visitor">' + item.message + '</div>'
77+
}
78+
else
79+
{
80+
html += '<div class="messages__item messages__item--operator">' + item.message + '</div>'
81+
}
82+
});
83+
84+
const chatmessage = chatbox.querySelector('.chatbox__messages');
85+
chatmessage.innerHTML = html;
86+
}
87+
}
88+
89+
90+
const chatbox = new Chatbox();
91+
chatbox.display();

0 commit comments

Comments
 (0)