-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_handler.py
More file actions
1595 lines (1513 loc) · 69.5 KB
/
Copy pathcommand_handler.py
File metadata and controls
1595 lines (1513 loc) · 69.5 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
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 re
from fuzzywuzzy import fuzz
from file_command_handler import FileCommandHandler
from os_command_handler import OSCommandHandler
from general_command_handler import GeneralCommandHandler
import time
import threading
import tkinter as tk
import ctypes
import win32con
import webbrowser
import os
import pickle
import logging
import subprocess
import sys
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# Vision mode keywords for offline priority
VISION_MODE_KEYWORDS = [
"go vision",
"vision mode",
"activate vision",
"hand control",
"gesture control",
"visual input"
]
class CommandHandler:
"""
Initializes the CommandHandler with a FileManager and an OSManager.
Handles commands like 'create folder <name>', 'delete folder <name>',
'rename folder <old_name> to <new_name>', 'open folder <name>',
'open my computer', 'open disk <letter>', and 'go back'.
Uses context to track the current working directory.
"""
COMMANDS = {
"create folder": {
"handler": "handle_create_folder",
"handler_module": "file",
"params": "folder_name"
},
"open folder": {
"handler": "handle_open_folder",
"handler_module": "file",
"params": "folder_name"
},
"delete folder": {
"handler": "handle_delete_folder",
"handler_module": "file",
"params": "folder_name"
},
"rename folder": {
"handler": "handle_rename_folder",
"handler_module": "file",
"params": "old_name_new_name"
},
"open my computer": {
"handler": "handle_open_my_computer",
"handler_module": "file",
"params": None
},
"open this pc": {
"handler": "handle_open_my_computer",
"handler_module": "file",
"params": None
},
"open my pc": {
"handler": "handle_open_my_computer",
"handler_module": "file",
"params": None
},
"go to my computer": {
"handler": "handle_open_my_computer",
"handler_module": "file",
"params": None
},
"go to this pc": {
"handler": "handle_open_my_computer",
"handler_module": "file",
"params": None
},
"open disk": {
"handler": "handle_open_disk",
"handler_module": "file",
"params": "disk_letter"
},
"open drive": {
"handler": "handle_open_disk",
"handler_module": "file",
"params": "disk_letter"
},
"go to disk": {
"handler": "handle_open_disk",
"handler_module": "file",
"params": "disk_letter"
},
"go to drive": {
"handler": "handle_open_disk",
"handler_module": "file",
"params": "disk_letter"
},
"access drive": {
"handler": "handle_open_disk",
"handler_module": "file",
"params": "disk_letter"
},
"go back": {
"handler": "handle_go_back",
"handler_module": "file",
"params": None
},
"list commands": {
"handler": "handle_list_commands",
"handler_module": "general",
"params": None
},
"exit": {
"handler": "handle_exit",
"handler_module": "general",
"params": None
},
"mute volume": {
"handler": "handle_mute_toggle",
"handler_module": "os",
"params": None
},
"unmute volume": {
"handler": "handle_mute_toggle",
"handler_module": "os",
"params": None
},
"maximize volume": {
"handler": "handle_maximize_volume",
"handler_module": "os",
"params": None
},
"set volume": {
"handler": "handle_set_volume",
"handler_module": "os",
"params": "number"
},
"maximize brightness": {
"handler": "handle_maximize_brightness",
"handler_module": "os",
"params": None
},
"set brightness": {
"handler": "handle_set_brightness",
"handler_module": "os",
"params": "number"
},
"switch tab": {
"handler": "handle_switch_tab",
"handler_module": "os",
"params": "number"
},
"switch window": {
"handler": "handle_switch_window",
"handler_module": "os",
"params": None
},
"minimize all windows": {
"handler": "handle_minimize_all_windows",
"handler_module": "os",
"params": None
},
"show desktop": {"handler": "handle_go_to_desktop", "handler_module": "os", "params": None},
"change wallpaper": {"handler": "handle_change_wallpaper", "handler_module": "os", "params": None},
"next wallpaper": {"handler": "handle_change_wallpaper", "handler_module": "os", "params": None},
"set wallpaper to": {"handler": "handle_set_wallpaper", "handler_module": "general", "params": "image_file"},
"show grid": {"handler": "handle_show_grid", "handler_module": "os", "params": None},
"hide grid": {"handler": "handle_hide_grid", "handler_module": "os", "params": None},
"click cell": {"handler": "handle_click_cell", "handler_module": "os", "params": "number"},
"double click cell": {"handler": "handle_double_click_cell", "handler_module": "os", "params": "number"},
"right click cell": {"handler": "handle_right_click_cell", "handler_module": "os", "params": "number"},
"drag from": {"handler": "handle_drag_from", "handler_module": "os", "params": "number"},
"drop on": {"handler": "handle_drop_on", "handler_module": "os", "params": "number"},
"zoom cell": {"handler": "handle_zoom_cell", "handler_module": "os", "params": "number"},
"exit zoom": {"handler": "handle_exit_zoom", "handler_module": "os", "params": None},
"set grid size": {"handler": "handle_set_grid_size", "handler_module": "os", "params": "number"},
"maximize window": {
"handler": "handle_maximize_current_window",
"handler_module": "os",
"params": None
},
"minimize window": {
"handler": "handle_minimize_current_window",
"handler_module": "os",
"params": None
},
"close window": {
"handler": "handle_close_current_window",
"handler_module": "os",
"params": None
},
"move window left": {
"handler": "handle_move_window_left",
"handler_module": "os",
"params": None
},
"move window right": {
"handler": "handle_move_window_right",
"handler_module": "os",
"params": None
},
"take screenshot": {
"handler": "handle_take_screenshot",
"handler_module": "os",
"params": None
},
"run application": {
"handler": "handle_run_application",
"handler_module": "os",
"params": "app_name"
},
"add numbers": {
"handler": "handle_add_numbers",
"handler_module": "general",
"params": "numbers"
},
"subtract numbers": {
"handler": "handle_subtract_numbers",
"handler_module": "general",
"params": "numbers"
},
"multiply numbers": {
"handler": "handle_multiply_numbers",
"handler_module": "general",
"params": "numbers"
},
"divide numbers": {
"handler": "handle_divide_numbers",
"handler_module": "general",
"params": "numbers"
},
"show system info": {
"handler": "handle_system_info",
"handler_module": "general",
"params": None
},
"tell time": {
"handler": "handle_tell_time",
"handler_module": "general",
"params": None
},
"tell date": {
"handler": "handle_tell_date",
"handler_module": "general",
"params": None
},
"tell day": {
"handler": "handle_tell_day",
"handler_module": "general",
"params": None
},
"tell weather": {
"handler": "handle_tell_weather",
"handler_module": "general",
"params": "city_name"
},
"tell joke": {
"handler": "handle_tell_joke",
"handler_module": "general",
"params": None
},
"check internet": {
"handler": "handle_check_internet",
"handler_module": "general",
"params": None
},
"check internet speed": {
"handler": "handle_check_internet_speed",
"handler_module": "general",
"params": None
},
"check bmi": {
"handler": "handle_check_bmi",
"handler_module": "general",
"params": "bmi_data"
},
"take a photo": {
"handler": "handle_take_photo",
"handler_module": "general",
"params": None
},
"go to desktop": {
"handler": "handle_go_to_desktop",
"handler_module": "os",
"params": None
},
"countdown": {
"handler": "handle_countdown",
"handler_module": "general",
"params": "seconds"
},
"empty recycle bin": {
"handler": "handle_empty_recycle_bin",
"handler_module": "os",
"params": None
},
"find my phone": {
"handler": "handle_find_phone",
"handler_module": "general",
"params": None
},
"spell": {
"handler": "handle_spell",
"handler_module": "general",
"params": "text"
},
"previous tab": {
"handler": "handle_previous_tab",
"handler_module": "os",
"params": None
},
"next tab": {
"handler": "handle_next_tab",
"handler_module": "os",
"params": None
},
"close tab": {
"handler": "handle_close_tab",
"handler_module": "os",
"params": None
},
"refresh": {
"handler": "handle_refresh",
"handler_module": "os",
"params": None
},
"zoom in": {
"handler": "handle_zoom_in",
"handler_module": "os",
"params": None
},
"zoom out": {
"handler": "handle_zoom_out",
"handler_module": "os",
"params": None
},
"bookmark tab": {
"handler": "handle_bookmark_tab",
"handler_module": "os",
"params": None
},
"open incognito": {
"handler": "handle_open_incognito",
"handler_module": "os",
"params": None
},
"search": {
"handler": "handle_search",
"handler_module": "os",
"params": "query"
},
"clear browsing data": {
"handler": "handle_clear_browsing_data",
"handler_module": "os",
"params": None
},
"scroll up": {
"handler": "handle_scroll_up",
"handler_module": "os",
"params": None
},
"scroll down": {
"handler": "handle_scroll_down",
"handler_module": "os",
"params": None
},
"scroll left": {
"handler": "handle_scroll_left",
"handler_module": "os",
"params": None
},
"scroll right": {
"handler": "handle_scroll_right",
"handler_module": "os",
"params": None
},
"stop scrolling": {
"handler": "handle_stop_scrolling",
"handler_module": "os",
"params": None
},
"open": {
"handler": "handle_open_generic",
"handler_module": "os",
"params": "open_target"
},
"play on youtube": {
"handler": "handle_play_on_youtube",
"handler_module": "os",
"params": "query"
},
"check disk space": {
"handler": "handle_check_disk_space",
"handler_module": "general",
"params": None
},
"read most recent email": {
"handler": "handle_read_most_recent_email",
"handler_module": "general",
"params": None
},
"read oldest email": {
"handler": "handle_read_oldest_email",
"handler_module": "general",
"params": None
},
"read nth most recent email": {
"handler": "handle_read_nth_most_recent_email",
"handler_module": "general",
"params": "nth_email"
},
"read nth oldest email": {
"handler": "handle_read_nth_oldest_email",
"handler_module": "general",
"params": "nth_email"
},
"copy": {
"handler": "handle_copy",
"handler_module": "os",
"params": None
},
"paste": {
"handler": "handle_paste",
"handler_module": "os",
"params": None
},
"read clipboard": {
"handler": "handle_read_clipboard",
"handler_module": "os",
"params": None
},
"select all": {
"handler": "handle_select_all",
"handler_module": "os",
"params": None
},
"open word": {
"handler": "handle_open_word",
"handler_module": "os",
"params": None
},
"write essay": {
"handler": "handle_write_essay",
"handler_module": "general",
"params": "topic"
},
"save file": {
"handler": "handle_save_file",
"handler_module": "os",
"params": "filename"
},
"remove this": {
"handler": "handle_remove_selection",
"handler_module": "os",
"params": None
},
"undo": {
"handler": "handle_undo_action",
"handler_module": "os",
"params": None
},
"redo": {
"handler": "handle_redo_action",
"handler_module": "os",
"params": None
},
"send to chatgpt": {
"handler": "handle_send_to_chatgpt",
"handler_module": "general",
"params": "query"
},
"start dictation": {
"handler": "handle_noop", # This command is handled in main.py
"handler_module": "general",
"params": None
},
"stop dictation": {
"handler": "handle_noop", # This command is handled in main.py
"handler_module": "general",
"params": None
},
"lock computer": {
"handler": "handle_lock_computer",
"handler_module": "os",
"params": None
},
"take a note": {
"handler": "handle_noop", # This command is handled in main.py
"handler_module": "general",
"params": None
},
"read last note": {
"handler": "handle_read_last_note",
"handler_module": "general",
"params": None
},
"show all notes": {
"handler": "handle_show_all_notes",
"handler_module": "general",
"params": None
},
"summarize clipboard": {
"handler": "handle_summarize_clipboard",
"handler_module": "general",
"params": None
},
"open file": {
"handler": "handle_open_file",
"handler_module": "file",
"params": "file_name"
},
}
# Synonyms for natural language commands
COMMAND_SYNONYMS = {
"create folder": ["make folder", "new folder", "add folder"],
"open folder": ["access folder", "go to folder"],
"delete folder": ["remove folder", "delete directory"],
"rename folder": ["change folder name"],
"open my computer": ["open this pc", "this pc", "my computer"],
"open disk": [
"open drive", "access disk", "access drive", "open disc", "access disc",
"open local disk", "access local disk"
],
"go back": ["back", "return", "go up"],
"list commands": ["help", "commands", "what can you do"],
"exit": [
"quit", "stop program", "bye", "good bye", "goodbye",
"shut down", "terminate", "kill program", "shutdown assistant"
],
"mute volume": ["mute", "silence"],
"unmute volume": ["unmute"],
"maximize volume": ["max volume", "full volume"],
"set volume": ["set volume to", "turn volume to", "adjust volume to"],
"maximize brightness": ["max brightness", "full brightness"],
"set brightness": ["set brightness to", "turn brightness to", "adjust brightness to"],
"switch tab": ["next tab", "change tab", "switch tab", "switch to next tab"],
"switch window": ["next window", "change window", "switch"],
"minimize all windows": ["minimize all"],
"restore windows": ["restore all windows", "bring back windows"],
"show grid": ["show grade", "display grid", "open grid", "grid on", "show mouse grid"],
"show desktop": ["show desktop", "go to desktop", "display desktop"],
"hide grid": ["close grid", "grid off", "remove grid"],
"click cell": ["click", "left click"],
"double click cell": ["double click", "double-click"],
"right click cell": ["right click", "right-click"],
"drag from": ["drag", "start drag"],
"drop on": ["drop", "to"],
"zoom cell": ["zoom cell", "zoom into cell"],
"exit zoom": ["exit grid zoom", "go back", "back from zoom"],
"maximize window": ["maximize this window", "full screen"],
"minimize window": ["minimize this window"],
"close window": [
"close app", "close application", "close program",
"close current window", "close current app", "close active window",
"close focused window", "close this window", "close that window", "kill window", "kill app"
],
"move window left": ["snap window left"],
"move window right": ["snap window right"],
"take screenshot": ["screenshot", "capture screen"],
"run application": ["run", "launch", "start"],
"add numbers": ["plus", "add", "sum"],
"subtract numbers": ["minus", "subtract", "difference"],
"multiply numbers": ["times", "multiply", "product"],
"divide numbers": ["divide", "division", "quotient"],
"show system info": ["system info", "check ram", "tell me battery status"],
"tell time": ["what time is it", "current time", "time now"],
"tell date": ["tell me the date", "what is the date", "current date", "today's date"],
"tell day": ["what day is it", "current day", "today is"],
"tell weather": ["weather in", "what's the weather in", "weather forecast for", "weather", "tell weather"],
"tell joke": ["tell me a joke", "joke", "make me laugh"],
"check internet": ["is internet working", "check connection"],
"check internet speed": ["test internet speed", "internet speed", "check my internet speed"],
"check bmi": ["calculate bmi", "what is my bmi", "bmi check", "bmi"],
"take a photo": ["capture photo", "take picture", "snap a photo"],
"set wallpaper to": ["change wallpaper to", "update wallpaper to"],
"go to desktop": [
"show desktop", "take me to desktop", "open desktop",
"minimize all", "desktop please"
],
"change wallpaper": [
"next wallpaper", "next background", "change background",
"switch wallpaper", "next slide"
],
"countdown": ["start countdown", "timer", "count down", "set timer"],
"empty recycle bin": ["clear trash", "delete trash", "empty trash", "clear bin"],
"find my phone": ["ring my phone", "locate my phone", "where is my phone"],
"spell": ["phonetic", "phonetically", "spelling"],
"previous tab": ["back tab", "prev tab", "go back"],
"next tab": ["forward tab", "next browser tab"],
"close tab": ["close current tab", "close browser tab", "close this tab", "close active tab"],
"refresh": ["reload tab", "refresh tab"],
"zoom in": ["increase zoom", "zoom bigger", "zooming"],
"zoom out": ["decrease zoom", "zoom smaller", "zoom out", "zoomed out"],
"set grid size": ["zoom", "grid"],
"bookmark tab": ["save tab", "bookmark current tab"],
"open incognito": ["private tab", "incognito window"],
"switch tab": ["go to tab", "jump to tab"],
"search": ["google", "look up", "find"],
"clear browsing data": ["clear history", "delete cache", "clear browser data"],
"scroll up": ["scroll upward", "move up", "page up"],
"scroll down": ["scroll downward", "move down", "page down"],
"scroll left": ["move left", "pan left"],
"scroll right": ["move right", "pan right"],
"stop scrolling": ["cancel scrolling", "halt scrolling", "stop scroll"],
"open": ["launch", "start", "go to"],
"play on youtube": ["youtube", "play youtube", "play video", "play song", "play music on youtube", "search youtube"],
"check disk space": [
"disk space", "show disk space", "free space", "storage info", "check storage", "disk usage", "drive space", "space left on disk"
],
"read most recent email": ["read latest email", "read newest email", "read top email"],
"read oldest email": ["read first email", "read very first email", "read bottom email"],
"read nth most recent email": ["read {n}th most recent email", "read {n} most recent email", "read {n}th latest email", "read {n} latest email"],
"read nth oldest email": ["read {n}th oldest email", "read {n} oldest email", "read {n}th first email", "read {n} first email"],
"copy": ["copy that", "copy this"],
"paste": ["paste that", "paste this", "paste here"],
"read clipboard": ["what's on the clipboard", "read my clipboard", "tell me what's on the clipboard"],
"select all": ["select everything"],
"open word": ["launch word", "start word", "microsoft word"],
"write essay": ["write an essay on", "write about", "compose an essay on"],
"save file": ["save this file", "save it", "save the file"],
"remove this": ["delete this", "remove selection", "delete selection", "clear selection"],
"undo": ["undo that", "control z", "that was a mistake", "go back"],
"redo": ["redo that", "control y"],
"send to chatgpt": ["chatgpt", "ask chatgpt", "tell chatgpt", "on chatgpt"],
"start dictation": ["start dictation mode", "begin dictation", "dictation on"],
"stop dictation": ["stop dictation mode", "end dictation", "dictation off"],
"take a note": ["add a note", "new note", "write a note", "note this down"],
"read last note": ["what was my last note", "read the last note"],
"show all notes": ["open my notes", "show notes", "view all notes"],
"lock computer": ["lock my computer", "lock the screen", "lock screen", "lock pc"],
"summarize clipboard": ["summarize this", "summarize the clipboard", "give me a summary", "summarise", "summary"],
}
ORDINAL_WORDS = {
"first": 1, "second": 2, "third": 3, "fourth": 4, "fifth": 5,
"sixth": 6, "seventh": 7, "eighth": 8, "ninth": 9, "tenth": 10,
"eleventh": 11, "twelfth": 12, "thirteenth": 13, "fourteenth": 14, "fifteenth": 15,
"sixteenth": 16, "seventeenth": 17, "eighteenth": 18, "nineteenth": 19, "twentieth": 20
}
def __init__(self, file_manager, os_manager, voice_recognizer=None, speech=None, is_online=True):
self.file_manager = file_manager
self.os_manager = os_manager
self.voice_recognizer = voice_recognizer
self.speech = speech
self.hybrid_processor = None # Will be set from main.py
# Initialize specific command handlers
self.file_handler = FileCommandHandler(file_manager, voice_recognizer)
self.os_handler = OSCommandHandler(os_manager)
self.general_handler = GeneralCommandHandler(file_manager, self, speech)
# Command context for tracking recent actions
self.context = {
"last_created_folder": None,
"last_opened_item": None,
"working_directory": None,
"last_read_email": None,
}
# Gmail API setup (conditional)
self.gmail_service = None
if is_online:
try:
self._setup_gmail_api()
except Exception as e:
print(f"Failed to setup Gmail API even in online mode: {e}")
self.gmail_service = None # Ensure it's None on failure
else:
print("Offline mode: Gmail API and email commands are disabled.")
# Remove email commands if offline to prevent errors
email_commands = [
"read most recent email",
"read oldest email",
"read nth most recent email",
"read nth oldest email",
]
for cmd in email_commands:
if cmd in self.COMMANDS:
del self.COMMANDS[cmd]
def _setup_gmail_api(self):
print("Setting up Gmail API...")
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
creds = None
# Get the directory where this script is located
script_dir = os.path.dirname(os.path.abspath(__file__))
credentials_path = os.path.join(script_dir, 'credentials.json')
token_path = os.path.join(script_dir, 'token.pickle')
if os.path.exists(token_path):
print("Found token.pickle")
with open(token_path, 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
print("No valid creds, starting OAuth flow")
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES)
creds = flow.run_local_server(port=0)
with open(token_path, 'wb') as token:
pickle.dump(creds, token)
self.gmail_service = build('gmail', 'v1', credentials=creds)
print("Gmail API setup complete.")
def ordinal_to_index(self, ordinal):
# Supports both words and numbers ("first"/"1st", etc.)
ordinals = {
'first': 0, '1st': 0, 'one': 0, '1': 0,
'second': 1, '2nd': 1, 'two': 1, '2': 1,
'third': 2, '3rd': 2, 'three': 2, '3': 2,
'fourth': 3, '4th': 3, 'four': 3, '4': 3,
'fifth': 4, '5th': 4, 'five': 4, '5': 4,
'sixth': 5, '6th': 5, 'six': 5, '6': 5,
'seventh': 6, '7th': 6, 'seven': 6, '7': 6,
'eighth': 7, '8th': 7, 'eight': 7, '8': 7,
'ninth': 8, '9th': 8, 'nine': 8, '9': 8,
'tenth': 9, '10th': 9, 'ten': 9, '10': 9
}
return ordinals.get(ordinal.lower(), None)
def handle_read_nth_email(self, ordinal):
print(f"handle_read_nth_email called with ordinal: {ordinal}")
idx = self.ordinal_to_index(ordinal)
print(f"Resolved ordinal to index: {idx}")
if idx is None:
self.file_manager.speech.speak("I didn't understand which email you want to read.")
print("Ordinal not understood.")
return
try:
service = self.gmail_service
print("Fetching messages from Gmail...")
results = service.users().messages().list(userId='me', maxResults=idx+1).execute()
messages = results.get('messages', [])
print(f"Fetched {len(messages)} messages.")
if not messages or len(messages) <= idx:
self.file_manager.speech.speak("There aren't that many emails in your inbox.")
print("Not enough emails.")
return
msg_id = messages[idx]['id']
print(f"Fetching message with id: {msg_id}")
msg_data = service.users().messages().get(userId='me', id=msg_id, format='full').execute()
headers = msg_data['payload'].get('headers', [])
subject = next((h['value'] for h in headers if h['name'] == 'Subject'), '(No Subject)')
from_ = next((h['value'] for h in headers if h['name'] == 'From'), '(Unknown Sender)')
snippet = msg_data.get('snippet', '')
self.context['last_read_email'] = {'id': msg_id, 'subject': subject}
self.file_manager.speech.speak(f"Email from {from_}, subject: {subject}. {snippet}")
print(f"Read email: From: {from_}, Subject: {subject}, Snippet: {snippet}")
url = f"https://mail.google.com/mail/u/0/#inbox/{msg_id}"
webbrowser.open(url)
except Exception as e:
self.file_manager.speech.speak(f"Failed to read email: {e}")
print(f"Exception in handle_read_nth_email: {e}")
def handle_open_that_email(self):
email = self.context.get('last_read_email')
if not email:
self.file_manager.speech.speak("No email has been read yet.")
return
url = f"https://mail.google.com/mail/u/0/#inbox/{email['id']}"
webbrowser.open(url)
self.file_manager.speech.speak(f"Opening the last read email: {email['subject']}")
def get_command_list(self):
"""Return the list of available commands."""
return list(self.COMMANDS.keys())
def preprocess_command(self, cmd_text):
"""Preprocess the command text to remove polite phrases and normalize."""
cmd_text = cmd_text.lower().strip()
# Remove polite phrases
polite_phrases = [
r"can you please\s*", r"please\s*", r"could you\s*", r"would you\s*",
r"kindly\s*", r"i want to\s*", r"i would like to\s*"
]
for phrase in polite_phrases:
cmd_text = re.sub(phrase, "", cmd_text)
# Handle number-only inputs by prepending the last command
if re.match(r'^\s*\d+\s+\d+\s*$', cmd_text) and self.context.get("last_command"):
cmd_text = f"{self.context['last_command']} {cmd_text}"
print(f"Prepended last command: {cmd_text}")
# Replace pronouns with context
if " it " in cmd_text or cmd_text.endswith(" it"):
if self.context["last_created_folder"]:
directory, name = self.context["last_created_folder"]
cmd_text = cmd_text.replace(" it", f" {name}")
elif self.context["last_opened_item"]:
directory, name = self.context["last_opened_item"]
cmd_text = cmd_text.replace(" it", f" {name}")
print(f"Preprocessed command: {cmd_text}")
return cmd_text
def find_command(self, cmd_text):
# cmd_text is already preprocessed by execute_command
print(f"Preprocessed command for matching: '{cmd_text}'")
# Normalize the first word to 'read' if it is a close fuzzy match
words = cmd_text.split()
if words and fuzz.ratio(words[0], 'read') > 80:
print(f"Normalizing first word '{words[0]}' to 'read'")
words[0] = 'read'
cmd_text = ' '.join(words)
print(f"Command after normalization: '{cmd_text}'")
cmd_name = None
params = None
# --- PATTERN MATCHING FIRST (HIGHEST PRIORITY) ---
# Browser zoom commands (must come before grid size pattern)
m_zoom_in = re.match(r'^zoom\s+in$', cmd_text, re.IGNORECASE)
if m_zoom_in:
print("Pattern matched 'zoom in'")
cmd_name = "zoom in"
params = None
return cmd_name, params
m_zoom_out = re.match(r'^zoom\s+out$', cmd_text, re.IGNORECASE)
if m_zoom_out:
print("Pattern matched 'zoom out'")
cmd_name = "zoom out"
params = None
return cmd_name, params
# Handle "zooming" as "zoom in"
m_zooming = re.match(r'^zooming$', cmd_text, re.IGNORECASE)
if m_zooming:
print("Pattern matched 'zooming' as 'zoom in'")
cmd_name = "zoom in"
params = None
return cmd_name, params
# Handle "zoom bigger" as "zoom in"
m_zoom_bigger = re.match(r'^zoom\s+bigger$', cmd_text, re.IGNORECASE)
if m_zoom_bigger:
print("Pattern matched 'zoom bigger' as 'zoom in'")
cmd_name = "zoom in"
params = None
return cmd_name, params
# Handle "zoom smaller" as "zoom out"
m_zoom_smaller = re.match(r'^zoom\s+smaller$', cmd_text, re.IGNORECASE)
if m_zoom_smaller:
print("Pattern matched 'zoom smaller' as 'zoom out'")
cmd_name = "zoom out"
params = None
return cmd_name, params
# Handle "zoomed" as "zoom in"
m_zoomed = re.match(r'^zoomed$', cmd_text, re.IGNORECASE)
if m_zoomed:
print("Pattern matched 'zoomed' as 'zoom in'")
cmd_name = "zoom in"
params = None
return cmd_name, params
# Scroll commands pattern matching
m_scroll_up = re.match(r'^scroll\s+up$', cmd_text, re.IGNORECASE)
if m_scroll_up:
print("Pattern matched 'scroll up'")
cmd_name = "scroll up"
params = None
return cmd_name, params
m_scroll_down = re.match(r'^scroll\s+down$', cmd_text, re.IGNORECASE)
if m_scroll_down:
print("Pattern matched 'scroll down'")
cmd_name = "scroll down"
params = None
return cmd_name, params
m_scroll_left = re.match(r'^scroll\s+left$', cmd_text, re.IGNORECASE)
if m_scroll_left:
print("Pattern matched 'scroll left'")
cmd_name = "scroll left"
params = None
return cmd_name, params
m_scroll_right = re.match(r'^scroll\s+right$', cmd_text, re.IGNORECASE)
if m_scroll_right:
print("Pattern matched 'scroll right'")
cmd_name = "scroll right"
params = None
return cmd_name, params
m_stop_scrolling = re.match(r'^stop\s+scrolling$', cmd_text, re.IGNORECASE)
if m_stop_scrolling:
print("Pattern matched 'stop scrolling'")
cmd_name = "stop scrolling"
params = None
return cmd_name, params
# Browser tab commands pattern matching
m_close_tab = re.match(r'^close\s+tab$', cmd_text, re.IGNORECASE)
if m_close_tab:
print("Pattern matched 'close tab'")
cmd_name = "close tab"
params = None
return cmd_name, params
m_next_tab = re.match(r'^next\s+tab$', cmd_text, re.IGNORECASE)
if m_next_tab:
print("Pattern matched 'next tab'")
cmd_name = "next tab"
params = None
return cmd_name, params
m_previous_tab = re.match(r'^previous\s+tab$', cmd_text, re.IGNORECASE)
if m_previous_tab:
print("Pattern matched 'previous tab'")
cmd_name = "previous tab"
params = None
return cmd_name, params
# Prefer specific disk open phrases over generic 'open'
m_open_disk = re.match(r'^(?:open|access|go to)\s+(?:disk|disc|drive)\s+([a-zA-Z]):?(?:\b|$)', cmd_text, re.IGNORECASE)
if m_open_disk:
print("Pattern matched 'open disk'")
cmd_name = "open disk"
params = None
return cmd_name, params
# Also support reversed phrasing like 'open C drive' or 'go to D disk'
m_open_disk_rev = re.match(r'^(?:open|access|go to)\s+([a-zA-Z])\s*(?:drive|disk|disc)(?:\b|$)', cmd_text, re.IGNORECASE)
if m_open_disk_rev:
print("Pattern matched 'open <letter> drive'")
cmd_name = "open disk"
params = None
return cmd_name, params
# Pattern match for grid sizing: 'zoom 15', 'grid 10', 'zoom fifteen' (but not 'zoom in' or 'zoom out')
m_zoom_size = re.match(r'^(?:zoom|grid)\s+([a-z0-9 -]+)$', cmd_text, re.IGNORECASE)
if m_zoom_size and cmd_text.lower() not in ['zoom in', 'zoom out']:
print("Pattern matched 'set grid size'")
cmd_name = "set grid size"
params = None # will be extracted later by extract_parameters("number")
return cmd_name, params
# Pattern match for 'read [the] {ordinal|number} (most recent|oldest|recent) [email]'
match = re.match(r'read\s+(?:the\s+)?(\d+|[a-z]+)(?:st|nd|rd|th)?\s+(most recent|oldest|recent)(?:\s+email)?$', cmd_text, re.IGNORECASE)
if match:
idx_raw = match.group(1)
which = match.group(2)
print(f"Pattern match: idx_raw='{idx_raw}', which='{which}'")
# Treat 'recent' as 'most recent'
if which == 'recent':
which = 'most recent'
if idx_raw.isdigit():
idx = int(idx_raw) - 1
else:
idx = self.ORDINAL_WORDS.get(idx_raw.lower(), None)
if idx is not None:
idx -= 1
cmd_name = f"read nth {which} email"
params = (idx, which)
print(f"Pattern matched '{cmd_name}' with index: {params[0]}")
return cmd_name, params
# Pattern match for 'read [the] (most recent|oldest|recent) [email]'
match = re.match(r'read\s+(?:the\s+)?(most recent|oldest|recent)(?:\s+email)?$', cmd_text, re.IGNORECASE)
if match:
which = match.group(1)
print(f"Pattern match: which='{which}'")
if which == 'recent':
which = 'most recent'
cmd_name = f"read {which} email"
params = None
print(f"Pattern matched '{cmd_name}'")
return cmd_name, params
# --- END PATTERN MATCHING ---
# --- FIX: More flexible matching for commands with parameters ---
# This helps catch commands like "on chat gpt write a poem" where the trigger has variations.
# This block is now placed before the direct/synonym matching.
text_lower = cmd_text.lower().strip()
# Define commands that often start with a trigger phrase.
# --- FIX: Prioritize suffix commands to override prefixes ---
# If a command ends with a target ("on gpt" or "on word"), identify it first.
if any(text_lower.endswith(" " + trigger) for trigger in ["gpt", "chat gpt", "chatgpt", "on gpt", "on chat gpt", "on chatgpt"]):
cmd_name = "send to chatgpt"
elif any(text_lower.endswith(" " + trigger) for trigger in ["word", "on word", "in word"]):
cmd_name = "write essay"
prefix_commands = {
"send to chatgpt": ["ask chatgpt", "tell chatgpt", "on chatgpt", "chatgpt", "chat gpt", "on chat gpt"],
"write essay": ["write an essay on", "write about", "compose an essay on", "write a"],
"search": ["search for", "google", "look up", "find"],