-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbot.py
More file actions
309 lines (250 loc) · 11.1 KB
/
chatbot.py
File metadata and controls
309 lines (250 loc) · 11.1 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import subprocess
import requests
from datetime import datetime
import psutil
import tkinter as tk
from tkinter import Label
from PIL import Image, ImageTk
import os
import re
import pyautogui
pyautogui.write('\n Hi Bro..! I am your ChatBot...!', interval=0.1)
print('\n \n \n')
a = (r'''
██████╗██╗ ██╗ █████╗ ████████╗ ██████╗ ██████╗ ████████╗
██╔════╝██║ ██║██╔══██╗╚══██╔══╝ ██╔══██╗██╔═══██╗╚══██╔══╝
██║ ███████║███████║ ██║ ██████╔╝██║ ██║ ██║
██║ ██╔══██║██╔══██║ ██║ ██╔══██╗██║ ██║ ██║
╚██████╗██║ ██║██║ ██║ ██║ ██████╔╝╚██████╔╝ ██║
╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝
--Author : AJ ABDUL ''')
print(a)
# Function to check all predefined messages
def check_all_messages(message):
highest_prob_list = {}
def response(bot_response, list_of_words, single_response=False, required_words=[]):
nonlocal highest_prob_list
highest_prob_list[bot_response] = message_probability(message, list_of_words, single_response, required_words)
response('Hi Bro ,My name is IGRIs ,Developed by AJ ABDUL...!', ['hello', 'hi', 'hey'], single_response=True)
response('See you!', ['bye', 'goodbye'], single_response=True)
response('Ok bro...! \n \n EXITING ======>>>', ["stop"], single_response=False)
response('MM .. I\'m fine, and you?', ['how', 'are', 'you', 'doing'], required_words=['how'])
response('You\'re welcome!', ['thankyou', 'thanks'], single_response=True)
response('Thank you!', ['i', 'useful', 'code'], required_words=['useful'])
best_match = max(highest_prob_list, key=highest_prob_list.get)
return "......" if highest_prob_list[best_match] < 1 else best_match
# Emotional Intelligence model - simple emotion detection
def detect_emotion(text):
text = text.lower()
if any(word in text for word in ['sad', 'unhappy', 'depressed']):
return "I'm sorry to hear you're feeling down. How can I help?"
elif any(word in text for word in ['happy', 'good', 'great', 'excited']):
return "That's great to hear! How can I assist you further?"
elif any(word in text for word in ['angry', 'frustrated', 'annoyed']):
return "It seems you're feeling frustrated. Let's try to solve this together."
return "I'm here to assist you. Let me know how I can help!"
# Function to calculate message probability
def message_probability(user_message, recognised_words, single_response=False, required_words=[]):
message_certainty = 0
has_required_words = True
for word in user_message:
if word in recognised_words:
message_certainty += 1
percentage = float(message_certainty) / float(len(recognised_words))
for word in required_words:
if word not in user_message:
has_required_words = False
break
if has_required_words or single_response:
return int(percentage * 100)
else:
return 0
# Weather checking using OpenWeatherMap API
def get_weather(city):
api_key = "bd5e378503939ddaee76f12ad7a97608"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = f"{base_url}q={city}&appid={api_key}&units=metric"
response = requests.get(complete_url)
data = response.json()
if data["cod"] != "404":
main_data = data["main"]
temperature = main_data["temp"]
humidity = main_data["humidity"]
description = data["weather"][0]["description"]
return (f"\nWeather in {city}:\nTemperature: {temperature}°C\n"
f"Humidity: {humidity}%\nDescription: {description.capitalize()}")
else:
return "City not found. Please try again."
# Using SerpAPI for Google search results
def search_google(query):
api_key="your_api_key"
params = {
"engine": "google",
"q": query,
"api_key": api_key,
"num": 1
}
response = requests.get("https://serpapi.com/search", params=params)
if response.status_code == 200:
data = response.json()
if "organic_results" in data and len(data["organic_results"]) > 0:
# Fetch the first result's snippet
snippet = data["organic_results"][0].get("snippet", "No snippet available")
print(f"\n I found this:{snippet}")
# Function to get system status
def get_system_status():
cpu = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
disk = psutil.disk_usage('/')
return (f"CPU Usage: {cpu}%\n"
f"Memory Usage: {memory.percent}%\n"
f"Swap Usage: {swap.percent}%\n"
f"Disk Usage: {disk.percent}%")
# Function to get date and time
def get_date_time():
now = datetime.now()
return f"Current Date and Time: {now.strftime('%Y-%m-%d %H:%M:%S')}"
# Function to shutdown the system
def shutdown_system():
subprocess.run(['sudo', 'shutdown', '-h', 'now'])
# Function to restart the system
def restart_system():
subprocess.run(['sudo', 'reboot'])
# Function to logout the system
def logout_system():
subprocess.run(['gnome-session-quit', '--logout', '--no-prompt'])
# Function to open an application
def open_application(app_name):
try:
subprocess.Popen([app_name])
return f"Opening {app_name}..."
except Exception as e:
return f"Error opening {app_name}: {str(e)}"
# Function to close an application
def close_application(app_name):
try:
subprocess.run(["pkill", app_name])
return f"Closing {app_name}..."
except Exception as e:
return f"Error closing {app_name}: {str(e)}"
def show_help():
help_text = '''
Available Commands:
1. commuincation response.
2. Emotion detection on chatbot.
3. Weather in <city> - Get the current weather for a specific city.
4. Date - Get the current date.
5. Time - Get the current time.
6. Search about <query> - Perform a Google search on a specific topic.
7. Open <application_name> - Open an application on the system.
8. Close <application_name> - Close an open application on the system.
9. System status - Get the current system status (CPU, memory, disk usage).
10. Shutdown - Shutdown the system.
11. Restart - Restart the system.
12. Logout - Logout of the system.
13. Show your brain - Show the chatbot's brain.
14. open browser to search - Perform a Google search on a specific topic.
15. Help - Display this help text.
Type the command you'd like assistance with, and I'll do my best to help!
'''
return help_text
def show_you():
"""Display an image or GIF at program startup."""
# Create a Tkinter window
root = tk.Tk()
root.title("Brain")
root.geometry("800x600") # Adjust the window size
# Load the image or GIF
try:
gif_path = "brain.gif" # Replace with your image or GIF path
img = Image.open(gif_path)
gif_frames = []
# If it's a GIF, split into frames
try:
while True:
gif_frames.append(ImageTk.PhotoImage(img.copy()))
img.seek(len(gif_frames)) # Move to the next frame
except EOFError:
pass
def animate(index=0):
"""Animate the GIF frames."""
frame = gif_frames[index]
image_label.config(image=frame)
index += 1
if index == len(gif_frames):
index = 0
root.after(100, animate, index) # Adjust the delay for your GIF
# Display the first frame
image_label = Label(root)
image_label.pack(expand=True)
animate() # Start animation if it's a GIF
except Exception as e:
# If loading fails, show an error
error_label = Label(root, text="Failed to load image or GIF!", font=("Arial", 16))
error_label.pack(expand=True)
# Start the Tkinter event loop
root.mainloop()
# Main chatbot handler
def chatbot_response(user_input):
user_input_lower = user_input.lower()
# Emotional Intelligence response
if any(word in user_input_lower for word in ['sad', 'happy', 'angry', 'excited']):
return detect_emotion(user_input)
# Help command
elif 'help' in user_input_lower:
return show_help()
# Date and time
elif 'date' in user_input_lower or 'time' in user_input_lower:
return get_date_time()
# Web search using SerpAPI
elif 'search about' in user_input_lower:
query = user_input.split("search ")[1]
return search_google(query)
elif "show your brain" in user_input_lower:
return show_you()
elif "search" in user_input_lower:
query = user_input.replace("search ", "").strip()
url = f"https://www.google.com/search?q={query}"
subprocess.Popen(["xdg-open", url])
# Weather check
elif 'weather in' in user_input_lower:
city = user_input.split("weather in")[1]
return get_weather(city)
# Shutdown, restart, logout commands
elif 'shutdown' in user_input_lower:
shutdown_system()
return "System is shutting down."
elif 'restart' in user_input_lower:
restart_system()
return "System is restarting."
elif 'logout' in user_input_lower:
logout_system()
return "Logging out..."
# System status
elif 'system status' in user_input_lower:
return get_system_status()
# Open application
elif 'open' in user_input_lower:
app_name = user_input.split("open ")[1]
return open_application(app_name)
# Close application
elif 'close' in user_input_lower:
app_name = user_input.split("close ")[1]
return close_application(app_name)
else:
split_message = re.split(r'\s+|[, ;?!.-]\s*', user_input.lower())
return check_all_messages(split_message)
# Main loop
def chatbot():
pyautogui.write(" \n I'm your AI chat Assistant for help...\n", interval=0.1)
while True:
user_input = input("\n \t 🆄🆂🅴🆁 :")
if user_input.lower() == 'exit':
print("\n ok bro,Goodbye!")
break
response = chatbot_response(user_input)
print(f"\n \t 🅰🆂🆂🅸🆂🆃🅰🅽🆃 : {response}")
# Start the chatbot
if __name__ == "__main__":
chatbot()