-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1709 lines (1407 loc) · 60.1 KB
/
main.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import os
import random
import smtplib
import subprocess
import time
import tkinter as tk
import webbrowser
from contextvars import Token
from math import sqrt
from time import sleep
from tkinter import messagebox
from tkinter import ttk, filedialog, scrolledtext
import PyPDF2
import cv2
import geocoder
from gtts import gTTS
import os
# from test import numbe
import folium
import google.generativeai as genai
import mediapipe as mp
import notification
import openai as openai
import phonenumbers
import psutil
import pyautogui
import pywhatkit
import pywhatkit as kit
import requests
import speech_recognition as sr # pip install speechRecognition
import speedtest
import wikipedia
import wikipedia as googleScrap
from bs4 import BeautifulSoup
from instaloader import instaloader
from plyer import notification # pip install plyer
from pygments.lexers import PythonLexer
from pygments.token import Token
from requests import get
from ttkthemes import ThemedStyle
from word2number import w2n
from config import api_key
# todo: Main Code Starts here:
# engine = pyttsx3.init('sapi5')
# voices = engine.getProperty('voices')
# # print(voices[1].id)
# engine.setProperty('voice', voices[0].id)
recognizer = sr.Recognizer()
def tracker():
Key = "6d6f969fd9024ac8afde957f0c86a5ba"
number = input("Enter phone number with country code:")
check_number = phonenumbers.parse(number)
number_location = geocoder.description_for_number(check_number, "en")
print(number_location)
from phonenumbers import carrier
service_provider = phonenumbers.parse(number)
print(carrier.name_for_number(service_provider, "en"))
from opencage.geocoder import OpenCageGeocode
geocoder = OpenCageGeocode(Key)
query = str(number_location)
results = geocoder.geocode(query)
lat = results[0]['geometry']['lat']
lng = results[0]['geometry']['lng']
print(lat, lng)
map_location = folium.Map(location=[lat, lng], zoom_start=9)
folium.Marker([lat, lng], popup=number_location).add_to(map_location)
map_location.save("mylocation.html")
chatStr = ""
def ai(prompt):
openai.api_key = api_key
text = f"Open AI Response for Prompt: {prompt} \n ***********************\n\n"
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
temperature=0.7,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
print(response["choices"][0]["text"])
speak(response["choices"][0]["text"])
text += response["choices"][0]["text"]
if not os.path.exists("Openai"):
os.mkdir("Openai")
with open(f"Openai/{''.join(prompt.split('intelligence')[1:])}.txt", "w") as f:
f.write(text)
def virtual_mouse():
cap = cv2.VideoCapture(0)
hand_detector = mp.solutions.hands.Hands()
drawing_utils = mp.solutions.drawing_utils
screen_width, screen_height = pyautogui.size()
index_y = 0
while True:
_, frame = cap.read()
frame = cv2.flip(frame, 1)
frame_height, frame_width, _ = frame.shape
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
output = hand_detector.process(rgb_frame)
hands = output.multi_hand_landmarks
if hands:
for hand in hands:
drawing_utils.draw_landmarks(frame, hand)
landmarks = hand.landmark
for id, landmark in enumerate(landmarks):
x = int(landmark.x * frame_width)
y = int(landmark.y * frame_height)
if id == 8:
cv2.circle(img=frame, center=(x, y), radius=10, color=(0, 255, 255))
index_x = screen_width / frame_width * x
index_y = screen_height / frame_height * y
if id == 4:
cv2.circle(img=frame, center=(x, y), radius=10, color=(0, 255, 255))
thumb_x = screen_width / frame_width * x
thumb_y = screen_height / frame_height * y
print('outside', abs(index_y - thumb_y))
if abs(index_y - thumb_y) < 20:
pyautogui.click()
pyautogui.sleep(1)
elif abs(index_y - thumb_y) < 100:
pyautogui.moveTo(index_x, index_y)
cv2.imshow('Virtual Mouse', frame)
cv2.waitKey(1)
def open_app(app_name):
try:
subprocess.run(["open", "-a", app_name])
print(f"Opening {app_name}...")
except Exception as e:
print(f"An error occurred: {e}")
def debug_code(code):
try:
# Create a dictionary for the local and global variables
local_vars = {}
global_vars = {}
# Execute the code
exec(code, global_vars, local_vars)
# Return the result
result = f"Execution Result: {local_vars}"
except Exception as e:
# If an error occurs during execution, return the error message
result = f"Error: {str(e)}"
return result
# def get_random_quote():
# # API endpoint for fetching a random quote
# api_url = "https://api.quotable.io/random"
#
# try:
# # Make a GET request to the API
# response = requests.get(api_url)
#
# # Check if the request was successful (status code 200)
# if response.status_code == 200:
# # Parse the JSON response
# quote_data = response.json()
#
# # Extract the quote and author
# quote = quote_data.get("content")
# author = quote_data.get("author")
#
# # Print the quote
# print(f'"{quote}" - {author}')
# else:
# print(f"Failed to fetch a random quote. Status Code: {response.status_code}")
# except Exception as e:
# print(f"An error occurred: {e}")
def main():
print("Please Repeat the name of application")
speak("Please Repeat the name of application")
app_name = listen().lower()
open_app(app_name)
class SnakeGame:
def __init__(self, master):
self.master = master
self.master.title("Snake Game")
self.master.geometry("500x500")
self.canvas = tk.Canvas(self.master, bg="black", width=400, height=360)
self.canvas.pack()
self.canvas.create_rectangle(0, 0, 400, 400, outline="white")
self.snake = [(100, 100), (90, 100), (80, 100)]
self.food = self.create_food()
self.direction = "Right"
self.score = 0
self.is_paused = False
self.score_label = tk.Label(self.master, text=f"Score: {self.score}", fg="white", bg="black")
self.score_label.pack()
self.high_score_label = tk.Label(self.master, text=f"High Score: {self.get_high_score()}", fg="white", bg="black")
self.high_score_label.pack()
self.start_time = time.time()
self.pause_button = tk.Button(self.master, text="Pause/Resume", command=self.toggle_pause)
self.pause_button.pack()
self.restart_button = tk.Button(self.master, text="Restart", command=self.restart_game)
self.restart_button.pack()
self.reset_button = tk.Button(self.master, text="Reset High Score", command=self.reset_high_score)
self.reset_button.pack()
self.master.bind("<Key>", self.change_direction)
self.update()
def reset_high_score(self):
response = messagebox.askyesno("Reset High Score",
"Are you sure you want to reset the high score? This action cannot be undone.")
if response:
self.set_high_score(0)
self.update_score()
def create_food(self):
x = random.randrange(1, 39) * 10
y = random.randrange(1, 39) * 10
return self.canvas.create_rectangle(x, y, x + 10, y + 10, fill="red")
def move(self):
if not self.is_paused:
head = list(self.snake[0])
if self.direction == "Up":
head[1] -= 10
elif self.direction == "Down":
head[1] += 10
elif self.direction == "Left":
head[0] -= 10
elif self.direction == "Right":
head[0] += 10
self.snake.insert(0, tuple(head))
if self.snake[0] == (self.canvas.coords(self.food)[0], self.canvas.coords(self.food)[1]):
self.canvas.delete(self.food)
self.food = self.create_food()
self.score += 1
self.update_score()
else:
self.canvas.delete(self.snake[-1])
self.snake.pop()
if self.is_game_over():
self.game_over()
self.draw_snake()
def draw_snake(self):
self.canvas.delete("snake")
for segment in self.snake:
self.canvas.create_rectangle(
segment[0], segment[1], segment[0] + 10, segment[1] + 10, fill="green", tags="snake"
)
def change_direction(self, event):
if event.keysym in ["Up", "Down", "Left", "Right"]:
if (
(event.keysym == "Up" and self.direction != "Down")
or (event.keysym == "Down" and self.direction != "Up")
or (event.keysym == "Left" and self.direction != "Right")
or (event.keysym == "Right" and self.direction != "Left")
):
self.direction = event.keysym
def update(self):
self.move()
if not self.is_game_over() and not self.is_paused:
self.master.after(100, self.update)
def update_score(self):
self.score_label.config(text=f"Score: {self.score}")
high_score = self.get_high_score()
self.high_score_label.config(text=f"High Score: {high_score}")
def toggle_pause(self):
self.is_paused = not self.is_paused
if self.is_paused:
self.pause_button.config(text="Resume")
else:
self.pause_button.config(text="Pause")
self.update()
def restart_game(self):
self.snake = [(100, 100), (90, 100), (80, 100)]
self.direction = "Right"
self.score = 0
self.is_paused = False
self.start_time = time.time()
# Clear the canvas
self.canvas.delete("all")
# Recreate the background rectangle
self.canvas.create_rectangle(0, 0, 400, 400, outline="white")
# Recreate the score label
self.score_label = tk.Label(self.master, text=f"Score: {self.score}", fg="white", bg="black")
self.score_label.pack()
# Update the high score label
high_score = self.get_high_score()
self.high_score_label.config(text=f"High Score: {high_score}")
# Recreate the food object
self.food = self.create_food()
# Check if the snake is not empty before accessing its coordinates
if self.snake:
self.update_score()
self.update()
def game_over(self):
end_time = time.time()
play_time = round(end_time - self.start_time, 2)
high_score = self.get_high_score()
if self.score > high_score:
self.set_high_score(self.score)
self.canvas.create_text(
200, 240, text=f"Congratulations!\nNew High Score: {self.score}", font=("Helvetica", 16), fill="white"
)
else:
self.canvas.create_text(
200, 240, text=f"High Score: {high_score}", font=("Helvetica", 16), fill="white"
)
self.canvas.create_text(
200, 180, text=f"Game Over\nScore: {self.score}\nTime: {play_time} seconds", font=("Helvetica", 16), fill="white"
)
self.master.after_cancel(self.update)
def is_game_over(self):
if any(
[
self.snake[0][0] < 0,
self.snake[0][0] >= 400,
self.snake[0][1] < 0,
self.snake[0][1] >= 400,
self.snake[0] in self.snake[1:],
]
):
return True
return False
def get_high_score(self):
try:
with open("high_score.txt", "r") as file:
high_score = int(file.read())
except FileNotFoundError:
high_score = 0
return high_score
def set_high_score(self, score):
with open("high_score.txt", "w") as file:
file.write(str(score))
def reset_high_score(self):
response = messagebox.askyesno("Reset High Score", "Are you sure you want to reset the high score?")
if response:
self.set_high_score(0)
self.update_score()
def create_food(self):
x = random.randrange(1, 39) * 10
y = random.randrange(1, 39) * 10
return self.canvas.create_rectangle(x, y, x + 10, y + 10, fill="red")
def move(self):
if not self.is_paused:
head = list(self.snake[0])
if self.direction == "Up":
head[1] -= 10
elif self.direction == "Down":
head[1] += 10
elif self.direction == "Left":
head[0] -= 10
elif self.direction == "Right":
head[0] += 10
self.snake.insert(0, tuple(head))
if self.snake[0] == (self.canvas.coords(self.food)[0], self.canvas.coords(self.food)[1]):
self.canvas.delete(self.food)
self.food = self.create_food()
self.score += 1
self.update_score()
else:
self.canvas.delete(self.snake[-1])
self.snake.pop()
if self.is_game_over():
self.game_over()
self.draw_snake()
def draw_snake(self):
self.canvas.delete("snake")
for segment in self.snake:
self.canvas.create_rectangle(
segment[0], segment[1], segment[0] + 10, segment[1] + 10, fill="green", tags="snake"
)
def change_direction(self, event):
if event.keysym in ["Up", "Down", "Left", "Right"]:
if (
(event.keysym == "Up" and self.direction != "Down")
or (event.keysym == "Down" and self.direction != "Up")
or (event.keysym == "Left" and self.direction != "Right")
or (event.keysym == "Right" and self.direction != "Left")
):
self.direction = event.keysym
def update(self):
self.move()
if not self.is_game_over() and not self.is_paused:
self.master.after(100, self.update)
def update_score(self):
self.score_label.config(text=f"Score: {self.score}")
high_score = self.get_high_score()
self.high_score_label.config(text=f"High Score: {high_score}")
def toggle_pause(self):
self.is_paused = not self.is_paused
if self.is_paused:
self.pause_button.config(text="Resume")
else:
self.pause_button.config(text="Pause")
self.update()
def restart_game(self):
self.snake = [(100, 100), (90, 100), (80, 100)]
self.food = self.create_food()
self.direction = "Right"
self.score = 0
self.is_paused = False
self.start_time = time.time()
self.update_score()
self.update()
def game_over(self):
end_time = time.time()
play_time = round(end_time - self.start_time, 2)
high_score = self.get_high_score()
if self.score > high_score:
self.set_high_score(self.score)
self.canvas.create_text(
200, 240, text=f"Congratulations!\nNew High Score: {self.score}", font=("Helvetica", 16), fill="white"
)
else:
self.canvas.create_text(
200, 240, text=f"High Score: {high_score}", font=("Helvetica", 16), fill="white"
)
self.canvas.create_text(
200, 180, text=f"Game Over\nScore: {self.score}\nTime: {play_time} seconds", font=("Helvetica", 16), fill="white"
)
self.master.after_cancel(self.update)
def is_game_over(self):
if any(
[
self.snake[0][0] < 0,
self.snake[0][0] >= 400,
self.snake[0][1] < 0,
self.snake[0][1] >= 400,
self.snake[0] in self.snake[1:],
]
):
return True
return False
def get_high_score(self):
try:
with open("high_score.txt", "r") as file:
high_score = int(file.read())
except FileNotFoundError:
high_score = 0
return high_score
def set_high_score(self, score):
with open("high_score.txt", "w") as file:
file.write(str(score))
def search_google(query):
google_url = f"https://www.google.com/search?q={query}"
webbrowser.open(google_url)
def search_youtube(query):
youtube_url = f"https://www.youtube.com/results?search_query={query}"
webbrowser.open(youtube_url)
class ModernCalculator:
def __init__(self, master):
self.master = master
self.master.title("Modern Calculator")
# Apply a themed style
style = ThemedStyle(self.master)
style.set_theme("plastik")
# Entry widget
self.entry = ttk.Entry(self.master, font=('Arial', 16), justify='right')
self.entry.grid(row=0, column=0, columnspan=4, pady=10, sticky="nsew")
# Buttons
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3), ('sqrt', 1, 4),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3), ('^', 2, 4),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3), ('(', 3, 4),
('0', 4, 0), ('C', 4, 1), ('=', 4, 2), ('+', 4, 3), (')', 4, 4),
]
for (text, row, col) in buttons:
btn = ttk.Button(self.master, text=text, style="TButton", command=lambda t=text: self.on_button_click(t))
btn.grid(row=row, column=col, sticky='nsew', padx=5, pady=5)
# Configure row and column weights so that they expand proportionally
for i in range(5):
self.master.grid_rowconfigure(i, weight=1)
self.master.grid_columnconfigure(i, weight=1)
# Memory
self.memory = None
def on_button_click(self, text):
if text == '=':
try:
result = eval(self.entry.get())
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, str(result))
except Exception as e:
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, "Error")
elif text == 'C':
self.entry.delete(0, tk.END)
elif text == 'sqrt':
value = float(self.entry.get())
result = sqrt(value)
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, str(result))
else:
current_text = self.entry.get()
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, current_text + str(text))
class CurrencyConverter:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://open.er-api.com/v6/latest"
def get_exchange_rate(self, base_currency, target_currency):
params = {'apikey': self.api_key, 'base': base_currency}
response = requests.get(self.base_url, params=params)
if response.status_code == 200:
data = response.json()
exchange_rate = data['rates'].get(target_currency)
if exchange_rate:
return exchange_rate
else:
print(f"Currency code '{target_currency}' not found.")
return None
else:
print("Failed to fetch exchange rates.")
return None
def convert(self, numamount, base_currency, target_currency):
exchange_rate = self.get_exchange_rate(base_currency, target_currency)
if exchange_rate is not None:
converted_amount = numamount * exchange_rate
return converted_amount
else:
return None
def Quiz():
questions = {
"What is the capital of France?": "paris",
"Who wrote 'Romeo and Juliet'?": "shakespeare",
"What is the largest mammal on Earth?": "blue whale",
"What country has the highest life expectancy?": "hong kong",
"Where would you be if you were standing on the Spanish Steps?": "rome",
"Which language has more native speakers: English or Spanish?": "spanish",
"What is the most common surname in the United States?": "smith",
"What disease commonly spread on pirate ships?": "scurvy",
"Who was the Ancient Greek God of the Sun?": "apollo",
"What was the name of the crime boss who was head of the feared Chicago Outfit?": "al capone",
"What year was the United Nations established?": "1945",
"Who has won the most total Academy Awards?": "walt disney",
"What artist has the most streams on Spotify?": "drake",
"How many minutes are in a full week?": "10,080",
"What car manufacturer had the highest revenue in 2020?": "volkswagen",
"How many elements are in the periodic table?": "118",
"What company was originally called 'Cadabra'?": "amazon",
"How many faces does a Dodecahedron have?": "12",
"Queen guitarist Brian May is also an expert in what scientific field?": "astrophysics",
"Aureolin is a shade of what color?": "yellow",
"How many ghosts chase Pac-Man at the start of each game?": "4",
"What Renaissance artist is buried in Rome's Pantheon?": "raphael",
"What shoe brand makes the 'Mexico 66'?": "onitsuka tiger",
"What game studio makes the Red Dead Redemption series?": "rockstar games",
"Who was the last Tsar of Russia?": "nicholas ii",
"What character have both Robert Downey Jr. and Benedict Cumberbatch played?": "sherlock holmes",
"What country drinks the most coffee per capita?": "finland",
"Which planet in the Milky Way is the hottest?": "venus",
"What is the 4th letter of the Greek alphabet?": "delta",
"What sports car company manufactures the 911?": "porsche",
"What city is known as 'The Eternal City'?": "rome",
"Roald Amundsen was the first man to reach the South Pole, but where was he from?": "norway",
"What is the highest-rated film on IMDb as of January 1st, 2022?": "the shawshank redemption",
"Who discovered that the earth revolves around the sun?": "nicolaus copernicus",
"What company was initially known as 'Blue Ribbon Sports'?": "nike",
"What art form is described as 'decorative handwriting or handwritten lettering'?": "calligraphy",
"Which planet has the most moons?": "saturn",
"What country has won the most World Cups?": "brazil",
"Complete the following lyrics - 'I should have changed that stupid lock.....'": "i should have made you leave your key",
"Kratos is the main character of what video game series?": "god of war",
"In what country would you find Mount Kilimanjaro?": "tanzania",
"What is a group of pandas known as?": "an embarrassment",
"What European country experienced the highest rate of population decline from 2015 - 2020?": "lithuania",
"How many bones do we have in an ear?": "3",
"Who famously crossed the Alps with elephants on the way to war with the Romans?": "hannibal",
"True or False: Halloween originated as an ancient Irish festival.": "true",
"What Netflix show had the most streaming views in 2021?": "squid game",
"Which Grammy-nominated New York rapper died in April of 2021?": "dmx",
"What software company is headquartered in Redmond, Washington?": "microsoft",
"What is the largest Spanish-speaking city in the world?": "mexico city",
"What is the world's fastest bird?": "the peregrine falcon",
"In what country is the Chernobyl nuclear plant located?": "ukraine",
"The Parthenon Marbles are controversially located in what museum?": "the british museum",
# ... add more questions here
}
score = 0
for question, correct_answer in questions.items():
speak(question)
user_answer = listen()
if user_answer is not None and user_answer == correct_answer:
speak("Correct!")
score += 1
elif user_answer == "quit":
speak("Quitting the quiz. Your final score is {} out of {}.".format(score, len(questions)))
break
else:
speak(f"Wrong! The correct answer is {correct_answer}.")
speak(f"You scored {score} out of {len(questions)}.")
def get_random_quote():
url = "https://api.quotable.io/random"
response = requests.get(url)
if response.status_code == 200:
quote_data = response.json()
return f'"{quote_data["content"]}" - {quote_data["author"]}'
else:
return "Failed to fetch a quote."
def play_song(category):
songs = {
"pop": "https://www.youtube.com/watch?v=3tmd-ClpJxA", # Example song link
"rock": "https://www.youtube.com/watch?v=3tmd-ClpJxA", # Replace with actual links
"hip hop": "https://www.youtube.com/watch?v=3tmd-ClpJxA",
# Add more categories and songs here
}
category_lower = category.lower()
if category_lower in songs:
song_url = songs[category_lower]
speak(f"Playing a {category_lower} song.")
webbrowser.open(song_url)
speak("Enjoy The music")
exit()
else:
speak(f"Sorry, I don't have songs for the {category_lower} category.")
def rock_stone_paper_scissor_game():
speak("Lets Play ROCK PAPER SCISSORS !!")
print("LETS PLAYYYYYYYYYYYYYY")
i = 0
Me_score = 0
Com_score = 0
while (i < 5):
speak('choose = ("rock", "paper", "scissors")')
choose = ("rock", "paper", "scissors") # Tuple
com_choose = random.choice(choose)
query = listen().lower()
if (query == "rock"):
if (com_choose == "rock"):
speak("ROCK")
print(f"Score:- ME :- {Me_score} : COM :- {Com_score}")
elif (com_choose == "paper"):
speak("paper")
Com_score += 1
print(f"Score:- ME :- {Me_score} : COM :- {Com_score}")
else:
speak("Scissors")
Me_score += 1
print(f"Score:- ME :- {Me_score} : COM :- {Com_score}")
elif (query == "paper"):
if (com_choose == "rock"):
speak("ROCK")
Me_score += 1
print(f"Score:- ME :- {Me_score + 1} : COM :- {Com_score}")
elif (com_choose == "paper"):
speak("paper")
print(f"Score:- ME :- {Me_score} : COM :- {Com_score}")
else:
speak("Scissors")
Com_score += 1
print(f"Score:- ME :- {Me_score} : COM :- {Com_score}")
elif (query == "scissors" or query == "scissor"):
if (com_choose == "rock"):
speak("ROCK")
Com_score += 1
print(f"Score:- ME :- {Me_score} : COM :- {Com_score}")
elif (com_choose == "paper"):
speak("paper")
Me_score += 1
print(f"Score:- ME :- {Me_score} : COM :- {Com_score}")
else:
speak("Scissors")
print(f"Score:- ME :- {Me_score} : COM :- {Com_score}")
i += 1
print(f"FINAL SCORE :- ME :- {Me_score} : COM :- {Com_score}")
def guess_number_game():
# Generate a random number between 1 and 100
target_number = random.randint(1, 100)
attempts = 0
print("Welcome to the Number Guessing Game!")
while True:
try:
# Get user input for the guess
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
# Compare the guess with the target number
if guess < target_number:
print("low! Try again.")
elif guess > target_number:
print("high! Try again.")
else:
print(f"Congratulations! You guessed the number {target_number} in {attempts} attempts.")
break
except ValueError:
print("Invalid input. Please enter a valid number.")
def currency_converter():
api_key = 'ca6bed7a7193138ee549fcb5' # Replace with your actual API key
currency_converter = (CurrencyConverter(api_key))
print("Enter the amount to convert:")
amount = input()
numamount = w2n.word_to_num(amount)
print("Enter the source currency code like INR, USD:")
source_currency = input().upper()
print("Enter the target currency code like INR, USD:")
target_currency = input().upper()
converted_amount = currency_converter.convert(numamount, source_currency, target_currency)
if converted_amount is not None:
print(f"{numamount} {source_currency} is equivalent to {converted_amount:.2f} {target_currency}")
else:
print("Conversion failed")
def open_website(url):
try:
subprocess.run(["open", url])
print(f"Opening {url}...")
except Exception as e:
print(f"An error occurred: {e}")
def speak(text):
tts = gTTS(text=text, lang='en')
tts.save("output.mp3")
os.system("afplay output.mp3")
def listen():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
print("Recognizing...")
query = recognizer.recognize_google(audio)
print(f"You said: {query}")
return query.lower()
except sr.UnknownValueError:
print("Sorry, I could not understand what you said.")
return ""
except sr.RequestError as e:
print(f"Could not request results from Google Speech Recognition service; {e}")
return ""
# def bardchat():
# cookie_dict = {
# "__Secure-1PSID": "bQhuVisizX6gmibLTAyPNMPbm7CdwC9mKI7NY2BCyCFg2G6HN1vMtA7KxVoMPgYAc0Z44w.",
# "__Secure-1PSIDTS": "sidts-CjEB3e41hTLESRukhfkjDV2L50qZ0JqxzG_R7bMl8l_4nkywGAEm3FfCzz8nhseX36G1EAA",
# "__Secure-1PSIDCC": "ACA-OxMad6pjXJ2tYFDrIxUE2NQnjNHYo2WB2DJaM5oWPk4nxb4LyqLijsfCrj-ewB47-LpLKQPr"
# }
# bard = BardCookies(cookie_dict=cookie_dict)
#
# while True:
# speak("Enter The Query : ")
# Query = listen().lower()
# Reply = bard.get_answer(Query)['content']
# speak(Reply)
# print(Reply)
# if Query == "quit" or "stop":
# break
# else:
# continue
class CodeEditor:
def __init__(self, root):
self.root = root
self.root.title("Feature-Rich IDE")
# Menu Bar
self.menu_bar = tk.Menu(self.root)
self.root.config(menu=self.menu_bar)
# File Menu
self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="File", menu=self.file_menu)
self.file_menu.add_command(label="New File", command=self.new_file)
self.file_menu.add_command(label="Open File", command=self.open_file)
self.file_menu.add_command(label="Save", command=self.save_file)
self.file_menu.add_command(label="Save As", command=self.save_file_as)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", command=self.root.destroy)
# Edit Menu (Add more features as needed)
# Code Editor
self.code_editor = scrolledtext.ScrolledText(self.root, wrap="word", undo=True)
self.code_editor.pack(expand="yes", fill="both")
# Button Frame
button_frame = ttk.Frame(self.root)
button_frame.pack(pady=5)
# Run Button
self.run_button = ttk.Button(button_frame, text="Run", command=self.run_code)
self.run_button.pack(side="left", padx=5)
# Save Button
self.save_button = ttk.Button(button_frame, text="Save", command=self.save_file)
self.save_button.pack(side="left", padx=5)
# Open Button
self.open_button = ttk.Button(button_frame, text="Open File", command=self.open_file)
self.open_button.pack(side="left", padx=5)
# Syntax Highlighting Tags
self.code_editor.tag_configure("keyword", foreground="blue")
self.code_editor.tag_configure("string", foreground="orange")
self.code_editor.tag_configure("comment", foreground="gray")
# Binding for Syntax Highlighting
self.code_editor.bind("<KeyRelease>", self.update_syntax_highlighting)
# Autocompletion
self.autocomplete_list = ["if", "else", "while", "for", "def", "class", "import", "from", "True", "False", "None"]
self.autocomplete_popup = AutocompletePopup(self.root, self.code_editor, self.autocomplete_list)
# Variable to store the last cursor position
self.last_cursor_position = "1.0"
# Auto-save interval in milliseconds (adjust as needed)
self.auto_save_interval = 60000 # 1 minute
# Schedule auto-save
self.root.after(self.auto_save_interval, self.auto_save)
def new_file(self):
self.code_editor.delete(1.0, tk.END)
self.root.title("Feature-Rich IDE - Untitled")
def open_file(self):
file_path = filedialog.askopenfilename(defaultextension=".py",
filetypes=[("Python files", "*.py"), ("All files", "*.*")])
if file_path:
self.code_editor.delete(1.0, tk.END)
with open(file_path, "r") as file:
self.code_editor.insert(tk.END, file.read())
self.root.title(f"Feature-Rich IDE - {file_path}")
def save_file(self):
# Save existing file
if hasattr(self, 'current_file'):
with open(self.current_file, "w") as file:
file.write(self.code_editor.get(1.0, tk.END))
# If it's a new file, ask for a file name
else:
self.save_file_as()
def save_file_as(self):
file_path = filedialog.asksaveasfilename(defaultextension=".py",
filetypes=[("Python files", "*.py"), ("All files", "*.*")])
if file_path:
with open(file_path, "w") as file:
file.write(self.code_editor.get(1.0, tk.END))
self.current_file = file_path
self.root.title(f"Feature-Rich IDE - {file_path}")
def run_code(self):
# Clear previous output
self.clear_output()
code = self.code_editor.get(1.0, tk.END)
try:
result = subprocess.run(["python3", "-c", code], capture_output=True, text=True, timeout=5)
self.display_output(result)
except subprocess.TimeoutExpired:
self.code_editor.insert(tk.END, "\nError: Execution timed out.", "comment")
except subprocess.CalledProcessError as e:
self.code_editor.insert(tk.END, f"\nError: {e}", "comment")
def display_output(self, result):
# Output tab
output_frame = ttk.Frame(self.root)
output_frame.pack(side="bottom", fill="both", expand=True)
# Add a scrolled text widget (output) to the Output tab
output_widget = scrolledtext.ScrolledText(output_frame, wrap="word", undo=True)
output_widget.pack(expand="yes", fill="both")
# Highlight stdout and stderr
for line in result.stdout.splitlines():
output_widget.insert(tk.END, line + "\n", "comment")
for line in result.stderr.splitlines():
output_widget.insert(tk.END, line + "\n", "comment")
# Scroll to the end
output_widget.yview(tk.END)
self.root.update()
def clear_output(self):
# Clear previous output
for widget in self.root.winfo_children():
if isinstance(widget, ttk.Frame) and widget != self.code_editor: # Exclude the code editor from destruction
widget.destroy()
def update_syntax_highlighting(self, event=None):