-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbot.py
More file actions
119 lines (105 loc) · 3.99 KB
/
chatbot.py
File metadata and controls
119 lines (105 loc) · 3.99 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import random
import time
def get_sentiment_label(scores):
"""Convert VADER compound score to sentiment label."""
if scores['compound'] >= 0.05:
return 'Positive'
elif scores['compound'] <= -0.05:
return 'Negative'
else:
return 'Neutral'
def get_bot_reply(user_sentiment, user_input, conversation):
# More varied (humanlike) responses
positive_responses = [
"That's wonderful!",
"I'm really glad to hear that!",
"Keep it up!",
"You sound happy today!",
"That's great to hear!",
"That made me smile!"
]
negative_responses = [
"I'm sorry that happened.",
"That sounds tough. Want to talk more?",
"I'm here to listen if you need me.",
"Let me know if I can do anything.",
"Oh no, I'm sorry. Can I help?",
"I hope things get better soon."
]
neutral_responses = [
"I see.",
"Tell me more.",
"Got it. Is there anything else?",
"Okay, let me think about that.",
"Interesting! Anything else you'd like to share?",
"Alright. I'm here if you want to chat."
]
follow_ups = [
"What else do you want to talk about?",
"Do you want advice or just to chat?",
"Is there something specific on your mind?",
"How's your day overall?"
]
# Occasional follow-up after every 3 messages
follow_up = ""
if len([m for m in conversation if m[0] == "User"]) % 3 == 0 and len(conversation) > 2:
follow_up = " " + random.choice(follow_ups)
# Choose reply
if user_sentiment == 'Negative':
reply = random.choice(negative_responses)
elif user_sentiment == 'Positive':
reply = random.choice(positive_responses)
else:
reply = random.choice(neutral_responses)
return reply + follow_up
def main():
analyzer = SentimentIntensityAnalyzer()
conversation = []
# Welcome and instructions
print("Welcome to the Sentiment Chatbot!")
print("Type your message and press Enter to chat.")
print("To end the conversation, type 'bye' and press Enter.\n")
print("Bot: Hello! How are you feeling today?")
while True:
user_input = input("You: ")
if user_input.strip().lower() == "bye":
print("\nBot: It was great chatting! Take care.\n")
print("You ended the conversation.")
break
user_scores = analyzer.polarity_scores(user_input)
user_sentiment = get_sentiment_label(user_scores)
conversation.append(('User', user_input, user_sentiment))
print(f"(Sentiment: {user_sentiment})") # Per-message sentiment
# Simulated "bot typing" delay
print("Bot is typing...")
time.sleep(random.uniform(0.3, 1.0))
bot_reply = get_bot_reply(user_sentiment, user_input, conversation)
conversation.append(('Bot', bot_reply, None))
print("Bot:", bot_reply)
# ---- Show full conversation and summary sentiment ----
print("\n--- Full Conversation History ---")
for speaker, message, sentiment in conversation:
if speaker == 'User':
print(f"{speaker}: {message} (Sentiment: {sentiment})")
else:
print(f"{speaker}: {message}")
# Overall sentiment analysis (Tier 1)
user_sentiments = [sent for sp, msg, sent in conversation if sp == 'User']
pos = user_sentiments.count('Positive')
neg = user_sentiments.count('Negative')
neu = user_sentiments.count('Neutral')
total = len(user_sentiments)
# Majority voting for overall sentiment
if total == 0:
overall = 'Neutral'
elif pos > neg and pos > neu:
overall = 'Positive'
elif neg > pos and neg > neu:
overall = 'Negative'
else:
overall = 'Neutral'
print("\n--- Overall Conversation Sentiment ---")
print(f"Overall mood: {overall} (Positives: {pos}, Negatives: {neg}, Neutrals: {neu})")
if __name__ == "__main__":
main()