-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.py
More file actions
175 lines (140 loc) · 6.07 KB
/
project.py
File metadata and controls
175 lines (140 loc) · 6.07 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
from textblob import TextBlob
import sys
import random
from termcolor import colored
import json
from datetime import datetime
def analyze_sentiment(text):
# Analyze the sentiment of input text.
# Returns a dictionary containing polarity, subjectivity, and category.
if not isinstance(text, str) or not text.strip():
raise ValueError("Input must be a non-empty string")
analysis = TextBlob(text)
polarity = analysis.sentiment.polarity
subjectivity = analysis.sentiment.subjectivity
# Determine sentiment category
if polarity > 0.3:
category = "very positive"
elif polarity > 0:
category = "positive"
elif polarity == 0:
category = "neutral"
elif polarity > -0.3:
category = "negative"
else:
category = "very negative"
return {
"polarity": polarity,
"subjectivity": subjectivity,
"category": category
}
def get_response(sentiment_category):
# Generate appropriate response based on sentiment category.
# Returns a string containing the chatbot's response.
if not isinstance(sentiment_category, str):
raise ValueError("Sentiment category must be a string")
responses = {
"very positive": [
"That's wonderful to hear! Your positive energy is contagious!",
"Wow, you seem to be having a great day! Tell me more!",
"Your enthusiasm is inspiring! Keep that amazing attitude!"
],
"positive": [
"I'm glad you're feeling good! Keep that positive spirit!",
"Nice to hear something positive! What's making you happy?",
"Sounds like things are going well for you!"
],
"neutral": [
"I understand. Would you like to tell me more about that?",
"Interesting. Can you elaborate on your thoughts?",
"Sometimes neutral feelings can be complex. What's on your mind?"
],
"negative": [
"I'm sorry you're feeling down. Would you like to talk about it?",
"That sounds challenging. How can I help you through this?",
"It seems like you're going through a tough time. I'm here to listen."
],
"very negative": [
"I hear that you're going through a very difficult time. I'm here to listen and support you.",
"This sounds incredibly tough. Would you like to share more about what's troubling you?",
"I'm truly sorry you're experiencing such intense negative emotions. Can I help in any way?"
]
}
sentiment_category = sentiment_category.lower()
if sentiment_category not in responses:
raise ValueError("Invalid sentiment category")
return random.choice(responses[sentiment_category])
def save_conversation(conversation_history, filename="chat_history.json"):
# Save the conversation history to a JSON file.
# Returns True if successful, raises an exception if not.
if not isinstance(conversation_history, list):
raise ValueError("Conversation history must be a list")
try:
with open(filename, 'w') as f:
json.dump(conversation_history, f, indent=4)
return True
except Exception as e:
raise IOError(f"Error saving conversation: {str(e)}")
def format_message(speaker, message, sentiment=None):
# Format a chat message with timestamp and optional sentiment.
# Returns a dictionary containing the formatted message.
if not isinstance(speaker, str) or not isinstance(message, str):
raise ValueError("Speaker and message must be strings")
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if sentiment:
return {
"timestamp": timestamp,
"speaker": speaker,
"message": message,
"sentiment": sentiment
}
return {
"timestamp": timestamp,
"speaker": speaker,
"message": message
}
def main():
conversation_history = []
# Welcome message
print(colored("Welcome to Sentiment Analysis Chatbot!", "cyan"))
name = input(colored("What's your name? ", "cyan")).strip()
if not name:
name = "User"
print(colored(f"\nHello {name}! Type 'quit' or 'exit' or 'bye' or 'goodbye' to end the conversation.", "cyan"))
print(colored("\nBot: How are you feeling today?", "green"))
while True:
try:
# Get user input
user_input = input(colored(f"\n{name}: ", "yellow")).strip()
# Check for exit command
if user_input.lower() in ['quit', 'exit', 'bye', 'goodbye']:
print(colored("\nBot: Goodbye! Take care!", "green"))
save_conversation(conversation_history)
print(colored("\nConversation saved to chat_history.json!", "cyan"))
break
# Analyze sentiment
sentiment = analyze_sentiment(user_input)
# Store user message
user_message = format_message(name, user_input, sentiment)
conversation_history.append(user_message)
# Generate and display bot response
bot_response = get_response(sentiment["category"])
print(colored(f"\nBot: {bot_response}", "green"))
# Store bot message
bot_message = format_message("Bot", bot_response)
conversation_history.append(bot_message)
# Display sentiment analysis
print(colored(
f"\nSentiment Analysis: {sentiment['category'].title()} "
f"(Polarity: {sentiment['polarity']:.2f}, "
f"Subjectivity: {sentiment['subjectivity']:.2f})",
"magenta"
))
except KeyboardInterrupt:
print(colored("\n\nChatbot terminated by user.", "red"))
break
except Exception as e:
print(colored(f"\nAn error occurred: {str(e)}", "red"))
continue
if __name__ == "__main__":
main()