-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatbot.py
101 lines (89 loc) · 2.3 KB
/
chatbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import spacy
from spacy.matcher import Matcher
# Load the spaCy English model
nlp = spacy.load("en_core_web_sm")
# Define the chatbot's responses
responses = {
"greeting": "Hello! How can I assist you today?",
"recommendation":
"Based on your preferences, I recommend trying our new product X.",
"goodbye": "Thank you for using our smart web app. Have a great day!",
}
# Define the chatbot's patterns
patterns = [
{
"label": "GREETING",
"pattern": [{
"LOWER": "hello"
}]
},
{
"label": "GREETING",
"pattern": [{
"LOWER": "hi"
}]
},
{
"label": "GREETING",
"pattern": [{
"LOWER": "hey"
}]
},
{
"label": "RECOMMENDATION",
"pattern": [{
"LOWER": "recommend"
}, {
"LOWER": "product"
}],
},
{
"label": "GOODBYE",
"pattern": [{
"LOWER": "bye"
}]
},
{
"label": "GOODBYE",
"pattern": [{
"LOWER": "goodbye"
}]
},
{
"label": "GOODBYE",
"pattern": [{
"LOWER": "see"
}, {
"LOWER": "you"
}]
},
]
# Initialize the matcher with the patterns
matcher = Matcher(nlp.vocab)
for pattern in patterns:
matcher.add(pattern["label"], None, pattern["pattern"])
# Define the chatbot function
def chatbot(text):
doc = nlp(text)
matches = matcher(doc)
for match_id, start, end in matches:
if nlp.vocab.strings[match_id] == "GREETING":
return responses["greeting"]
elif nlp.vocab.strings[match_id] == "RECOMMENDATION":
return responses["recommendation"]
elif nlp.vocab.strings[match_id] == "GOODBYE":
return responses["goodbye"]
return "I'm sorry, I didn't understand. Can you please rephrase your query?"
# Sample conversation
user_input = "Hello"
chatbot_response = chatbot(user_input)
print("User: ", user_input)
print("Chatbot: ", chatbot_response)
user_input = "Can you recommend a product for me?"
chatbot_response = chatbot(user_input)
print("User: ", user_input)
print("Chatbot: ", chatbot_response)
user_input = "Goodbye"
chatbot_response = chatbot(user_input)
print("User: ", user_input)
print("Chatbot: ", chatbot_response)