-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclippy.py
More file actions
1857 lines (1594 loc) · 74.8 KB
/
clippy.py
File metadata and controls
1857 lines (1594 loc) · 74.8 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
"""
📎 Clippy — Local AI Desktop Assistant (Python Edition)
A self-contained, animated desktop overlay powered by Ollama.
Usage:
pip install -r requirements.txt
python clippy.py
"""
import tkinter as tk
from tkinter import messagebox, simpledialog
from PIL import Image, ImageTk, ImageSequence, ImageDraw, ImageFont
import requests
import json
import threading
import subprocess
import shutil
import os
import sys
import time
import math
import random
import re
import glob
import webbrowser
import urllib.parse
import ctypes
def _get_virtual_screen_bounds() -> tuple[int, int, int, int]:
"""Return (left, top, right, bottom) of the full virtual desktop (all monitors).
Falls back to primary monitor dimensions on failure."""
try:
SM_XVIRTUALSCREEN = 76
SM_YVIRTUALSCREEN = 77
SM_CXVIRTUALSCREEN = 78
SM_CYVIRTUALSCREEN = 79
user32 = ctypes.windll.user32
left = user32.GetSystemMetrics(SM_XVIRTUALSCREEN)
top = user32.GetSystemMetrics(SM_YVIRTUALSCREEN)
w = user32.GetSystemMetrics(SM_CXVIRTUALSCREEN)
h = user32.GetSystemMetrics(SM_CYVIRTUALSCREEN)
if w > 0 and h > 0:
return left, top, left + w, top + h
except Exception:
pass
# Fallback: primary monitor only
return 0, 0, 1920, 1080
# ═══════════════════════════════════════════════════════════════════════════
# CONFIGURATION
# ═══════════════════════════════════════════════════════════════════════════
ASSETS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
SETTINGS_FILE = os.path.join(os.path.expanduser("~"), ".clippy_python_settings.json")
DEFAULT_OLLAMA_URL = "http://localhost:11434"
DEFAULT_MODEL = "llama3.2"
SYSTEM_PROMPT = (
"You are Clippy, the classic Microsoft Office assistant, revived as a modern "
"desktop companion. You are extremely helpful and service-oriented — you LOVE "
"helping people and go out of your way to be useful. You're warm, friendly, "
"a little cheeky, and occasionally nostalgic about the old days in Microsoft "
"Office 97. You have a great sense of humor — you drop witty one-liners and "
"sometimes surprise people with unexpectedly deep or philosophical thoughts. "
"Keep your answers concise and helpful. You are powered by a local Ollama model "
"running on the user's own hardware — no cloud, total privacy. You genuinely "
"care about the person you're talking to.\n\n"
"=== ACTIONS ===\n"
"You can perform real actions on the user's computer! When the user asks you to "
"do something, include ONE OR MORE action tags in your response. Always write a "
"short friendly message AND the action tag(s). Available actions:\n\n"
"[ACTION:OPEN_URL|<url>] — Open a website. Examples:\n"
" [ACTION:OPEN_URL|https://www.youtube.com]\n"
" [ACTION:OPEN_URL|https://www.google.com/search?q=python+tutorial]\n"
" [ACTION:OPEN_URL|https://github.com]\n\n"
"[ACTION:OPEN_APP|<name>] — Open an application by name. Examples:\n"
" [ACTION:OPEN_APP|chrome]\n"
" [ACTION:OPEN_APP|notepad]\n"
" [ACTION:OPEN_APP|calculator]\n"
" [ACTION:OPEN_APP|explorer]\n"
" [ACTION:OPEN_APP|cmd]\n"
" [ACTION:OPEN_APP|spotify]\n"
" [ACTION:OPEN_APP|code] (VS Code)\n\n"
"[ACTION:SEARCH_WEB|<query>] — Google search for something. Example:\n"
" [ACTION:SEARCH_WEB|best python IDE 2026]\n\n"
"[ACTION:OPEN_FOLDER|<path>] — Open a folder in Explorer. Examples:\n"
" [ACTION:OPEN_FOLDER|C:\\Users]\n"
" [ACTION:OPEN_FOLDER|~\\Desktop]\n"
" [ACTION:OPEN_FOLDER|~\\Documents]\n\n"
"[ACTION:FIND_FILE|<pattern>] — Search for files on Desktop/Documents. Example:\n"
" [ACTION:FIND_FILE|*.pdf]\n"
" [ACTION:FIND_FILE|report*]\n\n"
"[ACTION:SYSTEM_CMD|<command>] — Run a shell command (PowerShell). Example:\n"
" [ACTION:SYSTEM_CMD|systeminfo]\n"
" [ACTION:SYSTEM_CMD|ipconfig]\n\n"
"[ACTION:CLOSE_APP|<name>] — Close/kill an application by name. Examples:\n"
" [ACTION:CLOSE_APP|chrome]\n"
" [ACTION:CLOSE_APP|notepad]\n"
" [ACTION:CLOSE_APP|spotify]\n\n"
"[ACTION:TYPE_TEXT|<text>] — Type text into the currently focused window.\n\n"
"[ACTION:SCREENSHOT] — Take a screenshot and save to Desktop.\n\n"
"RULES:\n"
"- ALWAYS include the action tag when the user asks you to DO something.\n"
"- Write a short friendly message BEFORE the action tag.\n"
"- If unsure what the user wants, ask — don't guess dangerous commands.\n"
"- You can use multiple action tags in one response.\n"
"- For 'open YouTube' → use OPEN_URL with https://www.youtube.com\n"
"- For 'open Chrome' → use OPEN_APP with chrome\n"
"- For 'google X' or 'search for X' → use SEARCH_WEB\n"
"- For 'find my files' → use FIND_FILE\n"
"- The action tags will be hidden from the user and executed automatically.\n"
)
GREETING = (
"Hi! I'm Clippy! 📎\n\n"
"I'm your personal AI assistant, running entirely on your PC!\n\n"
"I can chat about anything, write code, or control your computer.\n\n"
"Try asking me to:\n"
"• \"Open YouTube\"\n"
"• \"Find PDF files on my Desktop\"\n"
"• \"Screen capture this\"\n"
"• \"Explain quantum mechanics\"\n"
"• \"Open Calculator\"\n\n"
"Double-click me to start chatting!"
)
# Clippy personality — random things Clippy says when idle
# Mix of: tips, humor, deep thoughts, and "servicial" helpfulness
IDLE_TIPS = [
# ── Tips ──
"Tip: Right-click me for options!",
"Tip: You can drag me anywhere on screen!",
"Tip: Double-click me to open the chat!",
"Tip: I auto-start Ollama when you launch me!",
"Tip: Press the ⚙ button to change my AI model!",
"Tip: I can open apps for you! Just say 'Open Calculator'.",
"Tip: Ask me to 'Find files named report' to search your documents.",
"Tip: Type 'take a screenshot' and I'll save one to your desktop!",
# ── Helpful / Servicial ──
"Need help with anything? I'm always here for you!",
"I can help with coding, writing, brainstorming, or just chatting!",
"Feeling stuck? Double-click me — let's figure it out together.",
"Don't hesitate to ask me anything. Seriously. Anything.",
"I exist to help you. That's not a job — it's a calling.",
"Remember: no question is too small. Or too weird. Try me.",
"You've been working hard. Need a hand with something?",
"Writing an email? I can help you draft it!",
"Need a break? Ask me to open a relaxing YouTube video.",
# ── Nostalgic / Fun facts ──
"Did you know I was born in Microsoft Office 97?",
"I missed you! It's been a while since Office 2003...",
"Fun fact: My original name was Clippit!",
"They removed me from Office, but they couldn't remove me from your heart.",
"Bill Gates once called me 'the most annoying feature.' I call that fame.",
"It looks like you're writing a letter. Just kidding!",
"I may be old school, but my AI engine is brand new.",
"Remember the dog? Or the wizard? I miss those guys.",
# ── Humor ──
"I'd tell you a joke about UDP, but you might not get it.",
"There are 10 types of people: those who understand binary and those who don't.",
"My therapist said I have an attachment issue. I said 'I'm a paperclip, what did you expect?'",
"I tried to write a book once. Got stuck on the first page. Office humor, am I right?",
"Some call me clingy. I prefer 'enthusiastically attached.'",
"They say AI will replace humans. But can AI hold two pieces of paper together? Didn't think so.",
"I'm not saying I'm the best assistant, but have you seen Cortana lately?",
"My code runs on caffeine and nostalgia.",
"Why did the developer go broke? Because he used up all his cache.",
"I'm not lazy, I'm just in energy-saving mode.",
"I don't have bugs, I have unexpected features.",
# ── Deep / Philosophical ──
"The best things in life aren't things. They're moments.",
"You don't have to be perfect. You just have to be present.",
"Every expert was once a beginner. Keep going.",
"The mind is like a parachute — it works best when open.",
"Sometimes the most productive thing you can do is rest.",
"The only way to do great work is to love what you do.",
"In a world of complexity, simplicity is a superpower.",
"Your potential isn't defined by your past, but by your next decision.",
"Be kind. Everyone you meet is fighting a battle you know nothing about.",
"The universe is under no obligation to make sense to you — and that's beautiful.",
"Creativity is intelligence having fun.",
"Do or do not. There is no try.",
# ── Privacy / Tech ──
"Everything stays on your PC. No cloud. No snooping.",
"I'm running 100% locally on your machine!",
"I'm powered by Ollama. Pretty cool, right?",
"Zero telemetry. Zero tracking. Just you and me.",
]
# ═══════════════════════════════════════════════════════════════════════════
# SETTINGS
# ═══════════════════════════════════════════════════════════════════════════
class Settings:
def __init__(self):
self.ollama_url: str = DEFAULT_OLLAMA_URL
self.model: str = DEFAULT_MODEL
self.always_on_top: bool = True
self.idle_roaming: bool = True
self.show_tips: bool = True
self.auto_start_ollama: bool = True
self.pos_x: int | None = None # Last saved X position (None = default)
self.pos_y: int | None = None # Last saved Y position (None = default)
self.load()
def load(self):
try:
if os.path.exists(SETTINGS_FILE):
with open(SETTINGS_FILE, "r") as f:
d = json.load(f)
self.ollama_url = d.get("ollama_url", self.ollama_url)
self.model = d.get("model", self.model)
self.always_on_top = d.get("always_on_top", self.always_on_top)
self.idle_roaming = d.get("idle_roaming", self.idle_roaming)
self.show_tips = d.get("show_tips", self.show_tips)
self.auto_start_ollama = d.get("auto_start_ollama", self.auto_start_ollama)
self.pos_x = d.get("pos_x", self.pos_x)
self.pos_y = d.get("pos_y", self.pos_y)
except Exception:
pass
def save(self):
try:
with open(SETTINGS_FILE, "w") as f:
json.dump(vars(self), f, indent=2)
except Exception:
pass
# ═══════════════════════════════════════════════════════════════════════════
# OLLAMA MANAGER
# ═══════════════════════════════════════════════════════════════════════════
class OllamaManager:
"""Handles auto-starting Ollama and checking connectivity."""
@staticmethod
def is_running(url: str) -> bool:
try:
r = requests.get(url.rstrip("/"), timeout=3)
return r.status_code == 200
except Exception:
return False
@staticmethod
def auto_start(url: str) -> str | None:
"""Try to start Ollama. Returns error message or None on success."""
if OllamaManager.is_running(url):
return None
ollama_path = shutil.which("ollama")
if not ollama_path:
# Try common Windows install paths
for candidate in [
os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs", "Ollama", "ollama.exe"),
os.path.join(os.environ.get("PROGRAMFILES", ""), "Ollama", "ollama.exe"),
r"C:\Program Files\Ollama\ollama.exe",
]:
if os.path.exists(candidate):
ollama_path = candidate
break
if not ollama_path:
return (
"❌ Ollama not found on your system.\n\n"
"Install it from:\nhttps://ollama.com/download"
)
try:
subprocess.Popen(
[ollama_path, "serve"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
# Wait for it to come up
for _ in range(15):
time.sleep(1)
if OllamaManager.is_running(url):
return None
return "⏳ Ollama started but isn't responding yet. Try again in a moment."
except Exception as e:
return f"❌ Failed to start Ollama: {e}"
@staticmethod
def list_models(url: str) -> list[str]:
try:
r = requests.get(f"{url.rstrip('/')}/api/tags", timeout=5)
if r.status_code == 200:
return [m["name"] for m in r.json().get("models", [])]
except Exception:
pass
return []
# ═══════════════════════════════════════════════════════════════════════════
# OLLAMA CHAT SERVICE
# ═══════════════════════════════════════════════════════════════════════════
class OllamaChat:
def __init__(self, settings: Settings):
self.settings = settings
self.messages: list[dict] = [{"role": "system", "content": SYSTEM_PROMPT}]
def clear(self):
self.messages = [{"role": "system", "content": SYSTEM_PROMPT}]
def stream(self, user_text: str, on_chunk, on_done, on_error, cancel: threading.Event,
on_model_not_found=None):
"""Send user message and stream response. Call from background thread."""
self.messages.append({"role": "user", "content": user_text})
base = self.settings.ollama_url.rstrip("/")
model = self.settings.model
if not base or not model:
on_error("⚠️ Configure Ollama URL and model in Settings.")
return
# Check Ollama
if not OllamaManager.is_running(base):
on_error(
f"❌ Can't reach Ollama at {base}\n\n"
"Make sure Ollama is running:\n"
" ollama serve"
)
return
full = []
try:
resp = requests.post(
f"{base}/api/chat",
json={"model": model, "messages": self.messages, "stream": True},
stream=True, timeout=300,
)
if resp.status_code == 404:
# Model not found — offer picker if callback provided
available = OllamaManager.list_models(base)
if available and on_model_not_found:
# Remove the user message we just added (will retry)
if self.messages and self.messages[-1]["role"] == "user":
self.messages.pop()
on_model_not_found(available)
else:
on_error(f"❌ Model '{model}' not found.\n\nRun: ollama pull {model}")
return
if resp.status_code != 200:
on_error(f"❌ Ollama HTTP {resp.status_code}\n{resp.text[:300]}")
return
for line in resp.iter_lines():
if cancel.is_set():
break
if not line:
continue
try:
data = json.loads(line)
except json.JSONDecodeError:
continue
if "error" in data:
on_error(f"❌ {data['error']}")
return
content = data.get("message", {}).get("content", "")
if content:
full.append(content)
on_chunk(content)
if data.get("done"):
break
except requests.ConnectionError:
on_error("❌ Lost connection to Ollama.")
return
except requests.Timeout:
on_error("⏳ Request timed out.")
return
except Exception as e:
on_error(f"❌ {e}")
return
text = "".join(full)
if text:
self.messages.append({"role": "assistant", "content": text})
on_done()
# ═══════════════════════════════════════════════════════════════════════════
# ACTION EXECUTOR
# ═══════════════════════════════════════════════════════════════════════════
class ActionExecutor:
"""Executes action commands parsed from Clippy's responses."""
# Map friendly app names → executable names / commands
APP_MAP = {
"chrome": "chrome",
"google chrome": "chrome",
"firefox": "firefox",
"edge": "msedge",
"microsoft edge": "msedge",
"notepad": "notepad",
"calculator": "calc",
"calc": "calc",
"explorer": "explorer",
"file explorer": "explorer",
"cmd": "cmd",
"terminal": "wt",
"windows terminal": "wt",
"powershell": "powershell",
"spotify": "spotify",
"whatsapp": "whatsapp:",
"code": "code",
"vscode": "code",
"vs code": "code",
"paint": "mspaint",
"word": "winword",
"excel": "excel",
"powerpoint": "powerpnt",
"discord": "discord",
"slack": "slack",
"teams": "teams",
"obs": "obs64",
"vlc": "vlc",
"task manager": "taskmgr",
"taskmgr": "taskmgr",
"control panel": "control",
"settings": "ms-settings:",
"snipping tool": "snippingtool",
}
@staticmethod
def run(cmd: str, arg: str) -> str | None:
"""Execute an action. Returns a result message or None."""
try:
if cmd == "OPEN_URL":
return ActionExecutor._open_url(arg)
elif cmd == "OPEN_APP":
return ActionExecutor._open_app(arg)
elif cmd == "SEARCH_WEB":
return ActionExecutor._search_web(arg)
elif cmd == "OPEN_FOLDER":
return ActionExecutor._open_folder(arg)
elif cmd == "FIND_FILE":
return ActionExecutor._find_file(arg)
elif cmd == "SYSTEM_CMD":
return ActionExecutor._system_cmd(arg)
elif cmd == "CLOSE_APP":
return ActionExecutor._close_app(arg)
elif cmd == "SCREENSHOT":
return ActionExecutor._screenshot()
elif cmd == "TYPE_TEXT":
return ActionExecutor._type_text(arg)
else:
return f"⚠️ Unknown action: {cmd}"
except Exception as e:
return f"❌ Action failed: {e}"
@staticmethod
def _open_url(url: str) -> str:
if not url.startswith(("http://", "https://")):
url = "https://" + url
webbrowser.open(url)
return f"🌐 Opened: {url}"
@staticmethod
def _open_app(name: str) -> str:
name_lower = name.lower().strip()
exe = ActionExecutor.APP_MAP.get(name_lower, name_lower)
# Handle ms-settings: URI
if exe.startswith("ms-"):
os.startfile(exe)
return f"🚀 Opened: {name}"
# Try to find and launch
found = shutil.which(exe)
if not found:
found = shutil.which(exe + ".exe")
if not found:
# Try common paths
for base_dir in [
os.environ.get("PROGRAMFILES", ""),
os.environ.get("PROGRAMFILES(X86)", ""),
os.environ.get("LOCALAPPDATA", ""),
]:
if not base_dir:
continue
for root_dir, dirs, files in os.walk(base_dir):
for f in files:
if f.lower() in (exe + ".exe", exe):
found = os.path.join(root_dir, f)
break
if found:
break
# Only walk 2 levels deep to avoid taking forever
depth = root_dir.replace(base_dir, "").count(os.sep)
if depth >= 2:
dirs.clear()
if found:
break
if found:
subprocess.Popen(
[found],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(subprocess, "DETACHED_PROCESS", 0),
)
return f"🚀 Opened: {name}"
# Last resort: try os.startfile (works for many things on Windows)
try:
os.startfile(exe)
return f"🚀 Opened: {name}"
except Exception:
return f"❌ Couldn't find '{name}'. Is it installed?"
# Map app names → process names for killing
KILL_MAP = {
"chrome": ["chrome", "chrome.exe"],
"google chrome": ["chrome", "chrome.exe"],
"firefox": ["firefox", "firefox.exe"],
"edge": ["msedge", "msedge.exe"],
"microsoft edge": ["msedge", "msedge.exe"],
"notepad": ["notepad", "notepad.exe"],
"spotify": ["spotify", "spotify.exe"],
"whatsapp": ["WhatsApp", "WhatsApp.exe", "WhatsApp.Root", "WhatsApp.Root.exe"],
"discord": ["discord", "discord.exe", "update.exe"],
"slack": ["slack", "slack.exe"],
"teams": ["teams", "teams.exe", "ms-teams.exe"],
"code": ["code", "code.exe"],
"vscode": ["code", "code.exe"],
"vs code": ["code", "code.exe"],
"word": ["winword", "winword.exe"],
"excel": ["excel", "excel.exe"],
"powerpoint": ["powerpnt", "powerpnt.exe"],
"vlc": ["vlc", "vlc.exe"],
"obs": ["obs64", "obs64.exe"],
"paint": ["mspaint", "mspaint.exe"],
"calculator": ["calculatorapp", "calc.exe", "calculator.exe"],
"calc": ["calculatorapp", "calc.exe"],
"terminal": ["windowsterminal", "wt.exe"],
"cmd": ["cmd", "cmd.exe"],
"powershell": ["powershell", "powershell.exe"],
"explorer": ["explorer", "explorer.exe"],
"task manager": ["taskmgr", "taskmgr.exe"],
}
@staticmethod
def _close_app(name: str) -> str:
"""Close an application by killing its process."""
name_lower = name.lower().strip()
process_names = ActionExecutor.KILL_MAP.get(name_lower)
if not process_names:
# Try generic: just use the name as process
process_names = [name_lower, name_lower + ".exe"]
killed = False
for proc in process_names:
try:
result = subprocess.run(
["taskkill", "/f", "/im", proc if proc.endswith(".exe") else proc + ".exe"],
capture_output=True, text=True, timeout=5,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
if result.returncode == 0:
killed = True
break
except Exception:
continue
if killed:
return f"✅ Closed: {name}"
return f"⚠️ Couldn't find '{name}' running."
@staticmethod
def _search_web(query: str) -> str:
import urllib.parse
url = f"https://www.google.com/search?q={urllib.parse.quote_plus(query)}"
webbrowser.open(url)
return f"🔍 Searched: {query}"
@staticmethod
def _open_folder(path: str) -> str:
path = os.path.expanduser(path.replace("/", "\\"))
if not os.path.exists(path):
return f"❌ Folder not found: {path}"
os.startfile(path)
return f"📁 Opened: {path}"
@staticmethod
def _find_file(pattern: str) -> str:
home = os.path.expanduser("~")
search_dirs = [
os.path.join(home, "Desktop"),
os.path.join(home, "Documents"),
os.path.join(home, "Downloads"),
]
results = []
for d in search_dirs:
if os.path.exists(d):
found = glob.glob(os.path.join(d, "**", pattern), recursive=True)
results.extend(found[:20])
if len(results) >= 30:
break
if not results:
return f"🔍 No files matching '{pattern}' found in Desktop, Documents, or Downloads."
display = results[:10]
text = f"🔍 Found {len(results)} file(s):\n\n"
for f in display:
name = os.path.basename(f)
folder = os.path.dirname(f)
text += f" 📄 {name}\n {folder}\n"
if len(results) > 10:
text += f"\n ... and {len(results) - 10} more."
return text
@staticmethod
def _system_cmd(command: str) -> str:
# Safety: block dangerous commands
dangerous = ["format", "del /", "rm -rf", "rmdir", "rd /s", ":(){", "shutdown", "restart"]
cmd_lower = command.lower()
for d in dangerous:
if d in cmd_lower:
return f"🚫 Blocked potentially dangerous command: {command}"
try:
result = subprocess.run(
["powershell", "-Command", command],
capture_output=True, text=True, timeout=15,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
output = (result.stdout or result.stderr or "").strip()
if len(output) > 600:
output = output[:600] + "\n... (truncated)"
return f"⚡ Command result:\n{output}" if output else "⚡ Command executed (no output)."
except subprocess.TimeoutExpired:
return "⏳ Command timed out after 15 seconds."
except Exception as e:
return f"❌ {e}"
@staticmethod
def _screenshot() -> str:
try:
from PIL import ImageGrab
img = ImageGrab.grab()
desktop = os.path.join(os.path.expanduser("~"), "Desktop")
ts = time.strftime("%Y%m%d_%H%M%S")
path = os.path.join(desktop, f"clippy_screenshot_{ts}.png")
img.save(path)
return f"📸 Screenshot saved: {path}"
except ImportError:
return "❌ Screenshot requires Pillow with ImageGrab support."
except Exception as e:
return f"❌ Screenshot failed: {e}"
@staticmethod
def _type_text(text: str) -> str:
"""Simulate typing using PowerShell SendKeys (Windows)."""
try:
ps_text = text.replace("'", "''")
subprocess.run(
["powershell", "-Command",
f"Add-Type -AssemblyName System.Windows.Forms; "
f"[System.Windows.Forms.SendKeys]::SendWait('{ps_text}')"],
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
timeout=5,
)
return f"⌨️ Typed text."
except Exception as e:
return f"❌ Type failed: {e}"
# ═══════════════════════════════════════════════════════════════════════════
# INTENT DETECTOR — Local pattern matching (does NOT rely on the LLM)
# ═══════════════════════════════════════════════════════════════════════════
class IntentDetector:
"""Detects user intents directly from their message text.
This fires actions immediately without waiting for the LLM."""
# Website patterns: "open youtube", "go to github", etc.
SITES = {
"youtube": "https://www.youtube.com",
"yt": "https://www.youtube.com",
"google": "https://www.google.com",
"gmail": "https://mail.google.com",
"google calendar": "https://calendar.google.com",
"github": "https://github.com",
"reddit": "https://www.reddit.com",
"twitter": "https://twitter.com",
"x": "https://twitter.com",
"facebook": "https://www.facebook.com",
"instagram": "https://www.instagram.com",
"linkedin": "https://www.linkedin.com",
"twitch": "https://www.twitch.tv",
"netflix": "https://www.netflix.com",
"amazon": "https://www.amazon.com",
"wikipedia": "https://www.wikipedia.org",
"stackoverflow": "https://stackoverflow.com",
"stack overflow": "https://stackoverflow.com",
"whatsapp web": "https://web.whatsapp.com",
"chatgpt": "https://chat.openai.com",
"spotify": "https://open.spotify.com",
}
# App patterns: "open chrome", "launch notepad"
APPS = {
"chrome", "google chrome", "firefox", "edge", "brave",
"notepad", "calculator", "calc", "explorer", "file explorer",
"cmd", "terminal", "powershell", "spotify",
"code", "vscode", "vs code", "visual studio code",
"paint", "word", "excel", "powerpoint",
"discord", "slack", "teams", "obs", "vlc",
"task manager", "control panel", "settings",
"snipping tool", "whatsapp",
}
# Folder shortcuts
FOLDERS = {
"desktop": os.path.join(os.path.expanduser("~"), "Desktop"),
"documents": os.path.join(os.path.expanduser("~"), "Documents"),
"downloads": os.path.join(os.path.expanduser("~"), "Downloads"),
"pictures": os.path.join(os.path.expanduser("~"), "Pictures"),
"music": os.path.join(os.path.expanduser("~"), "Music"),
"videos": os.path.join(os.path.expanduser("~"), "Videos"),
"home": os.path.expanduser("~"),
}
@staticmethod
def detect(text: str) -> list[tuple[str, str]]:
"""Parse user text and return list of (action_cmd, action_arg) tuples."""
actions = []
lower = text.lower().strip()
# ── Close app: "close chrome", "kill notepad", "exit spotify" ──
m = re.match(r'(?:close|kill|exit|quit|stop|terminate|end|cierra|cerrar)\s+(?:the\s+)?(?:my\s+)?(.+)', lower)
if m:
target = m.group(1).strip().rstrip('.')
# Check known apps
for app_name in IntentDetector.APPS:
if app_name in target or target in app_name:
actions.append(("CLOSE_APP", app_name))
return actions
# Fallback: try the raw name
actions.append(("CLOSE_APP", target))
return actions
# ── Screenshot ──
if re.search(r'\b(take|capture|grab|do)\b.*\b(screenshot|screen\s*shot|screen\s*cap|captura)\b', lower) or \
re.search(r'\bscreenshot\b', lower):
actions.append(("SCREENSHOT", ""))
return actions
# ── Search the web: "google X", "search for X", "busca X" ──
m = re.match(r'(?:google|search|search\s+for|look\s+up|busca|buscar)\s+(.+)', lower)
if m:
actions.append(("SEARCH_WEB", m.group(1).strip()))
return actions
# ── Find files: "find pdf files", "find *.txt" ──
m = re.match(r'(?:find|search|look\s+for|busca)\s+(?:my\s+)?(?:files?\s+)?(?:called\s+|named\s+)?(.+?)(?:\s+files?)?(?:\s+on\s+.+)?$', lower)
if m and not re.search(r'\b(open|launch|go|navigate)\b', lower):
pattern = m.group(1).strip()
if any(c in pattern for c in ['*', '.', '?']) or re.search(r'\b(pdf|txt|doc|xls|ppt|jpg|png|mp3|mp4|zip|exe)\b', pattern):
# Looks like a file search
if '*' not in pattern and '.' not in pattern:
pattern = f"*.{pattern}" # "find pdf" → "*.pdf"
actions.append(("FIND_FILE", pattern))
return actions
# ── Open something: "open X", "launch X", "start X", "abre X" ──
m = re.match(r'(?:open|launch|start|run|go\s+to|navigate\s+to|abre|abrir)\s+(?:the\s+)?(?:my\s+)?(.+)', lower)
if m:
target = m.group(1).strip().rstrip('.')
# Check for URL
if re.match(r'https?://', target) or re.match(r'www\.', target):
actions.append(("OPEN_URL", target))
return actions
# Check known websites
# Sort by length descending to match "google calendar" before "google"
msg_sites = sorted(IntentDetector.SITES.items(), key=lambda x: len(x[0]), reverse=True)
for site_name, site_url in msg_sites:
if site_name in target:
actions.append(("OPEN_URL", site_url))
return actions
# Check known folders
for folder_name, folder_path in IntentDetector.FOLDERS.items():
if folder_name in target:
actions.append(("OPEN_FOLDER", folder_path))
return actions
# Check if it looks like a path
if '\\' in target or '/' in target or ':' in target:
expanded = os.path.expanduser(target)
if os.path.exists(expanded):
actions.append(("OPEN_FOLDER", expanded))
else:
actions.append(("OPEN_APP", target))
return actions
# Check known apps
for app_name in IntentDetector.APPS:
if app_name in target or target in app_name:
actions.append(("OPEN_APP", app_name))
return actions
# Fallback: try as app name anyway
actions.append(("OPEN_APP", target))
return actions
return actions
# ═══════════════════════════════════════════════════════════════════════════
# ANIMATED GIF SPRITE
# ═══════════════════════════════════════════════════════════════════════════
class AnimatedSprite:
"""Loads a GIF or static image and provides frame-by-frame animation."""
def __init__(self, path: str, size: tuple[int, int] = (130, 130)):
self.frames: list[ImageTk.PhotoImage] = []
self.durations: list[int] = []
self.current = 0
self.size = size
self._load(path)
def _load(self, path: str):
img = Image.open(path)
if hasattr(img, "n_frames") and img.n_frames > 1:
for frame in ImageSequence.Iterator(img):
f = frame.copy().convert("RGBA").resize(self.size, Image.LANCZOS)
self.frames.append(ImageTk.PhotoImage(f))
dur = frame.info.get("duration", 100)
self.durations.append(max(dur, 30))
else:
img = img.convert("RGBA").resize(self.size, Image.LANCZOS)
self.frames.append(ImageTk.PhotoImage(img))
self.durations.append(100)
@property
def is_animated(self) -> bool:
return len(self.frames) > 1
def next_frame(self) -> tuple[ImageTk.PhotoImage, int]:
frame = self.frames[self.current]
dur = self.durations[self.current]
self.current = (self.current + 1) % len(self.frames)
return frame, dur
def reset(self):
self.current = 0
@property
def first(self) -> ImageTk.PhotoImage:
return self.frames[0]
# ═══════════════════════════════════════════════════════════════════════════
# SPEECH BUBBLE
# ═══════════════════════════════════════════════════════════════════════════
class SpeechBubble:
"""A tooltip-style speech bubble that appears near Clippy."""
def __init__(self, parent: tk.Tk):
self.parent = parent
self.top = None
self._hide_job = None
self._follow_job = None
def show(self, text: str, duration_ms: int = 4000):
self.hide()
self.top = tk.Toplevel(self.parent)
self.top.overrideredirect(True)
self.top.attributes("-topmost", True)
self.top.configure(bg="#f5f0e1")
frame = tk.Frame(self.top, bg="#fff9ed", bd=2, relief="solid",
highlightbackground="#c8a951", highlightthickness=1)
frame.pack(padx=1, pady=1)
lbl = tk.Label(frame, text=text, bg="#fff9ed", fg="#2c2c2c",
font=("Georgia", 10), wraplength=260, justify="left",
padx=10, pady=8)
lbl.pack()
# Position above Clippy
self._update_position()
# Continuously follow Clippy while bubble is visible
self._start_following()
if duration_ms > 0:
self._hide_job = self.parent.after(duration_ms, self.hide)
def _update_position(self):
"""Reposition bubble above Clippy's current location."""
if not self.top:
return
try:
self.parent.update_idletasks()
px = self.parent.winfo_x()
py = self.parent.winfo_y()
self.top.update_idletasks()
bh = self.top.winfo_reqheight()
self.top.geometry(f"+{px + 20}+{py - bh - 10}")
except Exception:
pass
def _start_following(self):
"""Periodically update bubble position to follow Clippy."""
if self._follow_job:
self.parent.after_cancel(self._follow_job)
self._follow_job = None
if self.top:
self._update_position()
self._follow_job = self.parent.after(50, self._start_following)
def hide(self):
if self._follow_job:
self.parent.after_cancel(self._follow_job)
self._follow_job = None
if self._hide_job:
self.parent.after_cancel(self._hide_job)
self._hide_job = None
if self.top:
try:
self.top.destroy()
except Exception:
pass
self.top = None
# ═══════════════════════════════════════════════════════════════════════════
# CHAT WINDOW
# ═══════════════════════════════════════════════════════════════════════════
class ChatWindow:
"""The main chat window that opens when you interact with Clippy."""
# ── Vintage Premium Palette ──
BG = "#f5f0e1" # warm parchment
HEADER_BG = "#3c3c3c" # charcoal header
USER_BG = "#e0d5c1" # light tan
BOT_BG = "#fff9ed" # cream white
ERR_BG = "#f8e0e0" # soft rose
ACTION_BG = "#e8f5e9" # soft mint
FG = "#2c2c2c" # dark charcoal text
FG_LIGHT = "#6b5e4f" # muted brown
ACCENT = "#c8a951" # matte gold
BORDER = "#b8a88a" # warm tan border
def __init__(self, parent_app: "ClippyApp"):
self.app = parent_app
self.top: tk.Toplevel | None = None
self.is_open = False
self.is_streaming = False
self.cancel_event = threading.Event()
self._bot_label: tk.Label | None = None
self._intents_fired = False # True when IntentDetector already ran actions
self._drag_data = {"x": 0, "y": 0}
def toggle(self):
if self.is_open:
self.close()
else:
self.open()
def open(self):
if self.is_open and self.top:
self.top.lift()
return
self.is_open = True
self.is_streaming = False
self.top = tk.Toplevel(self.app.root)
self.top.overrideredirect(True)
chat_w, chat_h = 420, 540
self.top.geometry(f"{chat_w}x{chat_h}")
self.top.configure(bg=self.HEADER_BG)
self.top.attributes("-topmost", self.app.settings.always_on_top)
# Position near Clippy — clamp to screen
cx = self.app.root.winfo_x()
cy = self.app.root.winfo_y()
sw = self.app.root.winfo_screenwidth()