Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
3383 lines (2845 loc) · 131 KB
/
Copy pathmain.py
File metadata and controls
3383 lines (2845 loc) · 131 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
"""
Stonic - GUI-based Personal Voice Assistant
A JARVIS-inspired voice assistant with a modern user interface
"""
import os
import sys
import time
import threading
import datetime
import random
import logging
import webbrowser
import subprocess
import platform
import speech_recognition as sr
import pyttsx3
import json
import requests
import cohere
from urllib.parse import quote
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QTimer, QThread, pyqtSignal, QSize
from PyQt5.QtGui import QMovie, QIcon, QPixmap, QFont, QFontDatabase, QColor
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout,
QHBoxLayout, QWidget, QFrame, QScrollArea, QSizePolicy,
QSystemTrayIcon, QMenu, QAction, QTextEdit, QGraphicsDropShadowEffect, QLineEdit, QListWidget
)
# Import SoundDetector for clap detection
from listener import SoundDetector
# Import settings from config
from config import (
USER_NAME,
APPLICATIONS,
WEBSITES,
GREETING_RESPONSES,
UNKNOWN_COMMAND_RESPONSES,
FAREWELL_RESPONSES,
LOG_FILE,
LOG_LEVEL,
LANGUAGE_SETTINGS,
SPEECH_SETTINGS,
TTS_SETTINGS,
BILINGUAL_RESPONSES,
COHERE_API_KEY
)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("stonic.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("Stonic")
# Session management
SESSION_FILE = "session.json"
def save_session_state(logged_in=True):
"""Save session state to file"""
try:
session_data = {
"logged_in": logged_in,
"timestamp": datetime.datetime.now().isoformat(),
"user": "stonic"
}
with open(SESSION_FILE, "w") as f:
json.dump(session_data, f)
logger.info("Session state saved")
except Exception as e:
logger.error(f"Error saving session state: {e}")
def load_session_state():
"""Load session state from file"""
try:
if os.path.exists(SESSION_FILE):
with open(SESSION_FILE, "r") as f:
session_data = json.load(f)
# Check if session is still valid (optional: add expiration logic here)
return session_data.get("logged_in", False)
else:
return False
except Exception as e:
logger.error(f"Error loading session state: {e}")
return False
def clear_session_state():
"""Clear session state"""
try:
if os.path.exists(SESSION_FILE):
os.remove(SESSION_FILE)
logger.info("Session state cleared")
except Exception as e:
logger.error(f"Error clearing session state: {e}")
# User Configuration - Change to your name
USER_NAME = "Himanshu"
# Language settings
LANGUAGE_SETTINGS = {
"primary_language": "en-IN", # English (India)
"secondary_language": "hi-IN", # Hindi
"use_multilingual": True, # Enable multilingual support
}
# Bilingual responses
BILINGUAL_RESPONSES = {
"greeting": {
"en": [
"Hello, Stonic at your service.",
"Good day, Stonic is ready.",
"At your command, Stonic is listening.",
"Stonic activated and ready to assist you.",
],
"hi": [
"नमस्ते, स्टोनिक आपकी सेवा में है।",
"शुभ दिन, स्टोनिक तैयार है।",
"आपके आदेश पर स्टोनिक हाज़िर है।",
"स्टोनिक सक्रिय है और आपकी सहायता के लिए तैयार है।",
]
},
"unknown_command": {
"en": [
"I'm not sure I understand that command. Could you please try again?",
"I didn't catch that. Can you rephrase your request?",
"I'm still learning. Could you try a different command?",
"I'm unable to process that request. Please try something else.",
],
"hi": [
"मुझे यह आदेश समझ नहीं आया। क्या आप फिर से कोशिश कर सकते हैं?",
"मैं समझ नहीं पाया। क्या आप अपना अनुरोध दोहरा सकते हैं?",
"मैं अभी भी सीख रहा हूं। क्या आप कोई अलग आदेश दे सकते हैं?",
"मैं इस अनुरोध को प्रोसेस नहीं कर पा रहा हूं। कृपया कुछ और कोशिश करें।",
]
},
"farewell": {
"en": [
"Goodbye, Stonic signing off.",
"Until next time, Stonic will be here when you need me.",
"Powering down Stonic. Have a great day!",
"Stonic going to sleep mode. Call me when you need me.",
],
"hi": [
"अलविदा, स्टोनिक जा रहा है।",
"अगली बार तक, स्टोनिक यहीं रहेगा जब आपको मेरी ज़रूरत होगी।",
"स्टोनिक बंद हो रहा है। आपका दिन शुभ हो!",
"स्टोनिक स्लीप मोड में जा रहा है। जब ज़रूरत हो तो मुझे बुलाएं।",
]
}
}
# Combining old response lists with new bilingual structure for backward compatibility
GREETING_RESPONSES = BILINGUAL_RESPONSES["greeting"]["en"]
UNKNOWN_COMMAND_RESPONSES = BILINGUAL_RESPONSES["unknown_command"]["en"]
FAREWELL_RESPONSES = BILINGUAL_RESPONSES["farewell"]["en"]
# Application paths - Windows specific
APPLICATIONS = {
"chrome": r"C:\Program Files\Google\Chrome\Application\chrome.exe",
"edge": r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
"firefox": r"C:\Program Files\Mozilla Firefox\firefox.exe",
"vscode": r"C:\Users\{}\AppData\Local\Programs\Microsoft VS Code\Code.exe".format(os.getenv('USERNAME')),
"notepad": r"notepad.exe",
"explorer": r"explorer.exe",
}
# Website URLs
WEBSITES = {
"google": "https://www.google.com",
"youtube": "https://www.youtube.com",
"github": "https://www.github.com",
"gmail": "https://www.gmail.com",
"wikipedia": "https://www.wikipedia.org",
}
# Text-to-speech engine with edge-tts for realistic speech
class StonicTTS:
def __init__(self):
# Import edge-tts for enhanced speech
import edge_tts
import asyncio
import tempfile
import os
import pygame
from concurrent.futures import ThreadPoolExecutor
self.edge_tts = edge_tts
self.asyncio = asyncio
self.tempfile = tempfile
self.os = os
self.pygame = pygame
self.executor = ThreadPoolExecutor(max_workers=2)
# Initialize pygame mixer for audio playback
try:
self.pygame.mixer.init(frequency=16000, size=-16, channels=1)
logger.info("Pygame mixer initialized successfully")
except Exception as e:
logger.error(f"Error initializing pygame mixer: {e}")
# Load settings from config
self.voice = TTS_SETTINGS.get("voice_id", "en-US-GuyNeural")
# Speech settings
self.rate = TTS_SETTINGS.get("rate", "+0%")
self.volume = TTS_SETTINGS.get("volume", "+0%")
self.pitch = TTS_SETTINGS.get("pitch", "+0Hz")
# Store the current audio playing state
self.currently_playing = False
self.stop_current = False
# Add a lock to prevent multiple simultaneous speech
self.tts_lock = threading.Lock()
logger.info(f"Enhanced TTS engine initialized with edge-tts using voice: {self.voice}")
def is_hindi(self, text):
"""Check if text contains Hindi characters - used only for logging"""
# Unicode range for Hindi: 0900-097F
for char in text:
if '\u0900' <= char <= '\u097F':
return True
return False
def speak(self, text):
"""Convert text to speech using edge-tts"""
if not text or text.strip() == "":
return
logger.info(f"Speaking: {text}")
# Create separate thread for speech to avoid UI freezing
def speak_thread():
try:
# Stop any current speech
self.stop_speech()
# Use edge-tts to generate and play speech
self._use_edge_tts(text)
except Exception as e:
logger.error(f"Error in TTS thread: {e}")
# Fall back to pyttsx3
self._fallback_speak(text)
threading.Thread(target=speak_thread).start()
def _fallback_speak(self, text):
"""Fallback speech using pyttsx3 if edge-tts fails"""
try:
import pyttsx3
engine = pyttsx3.init()
engine.setProperty('rate', 145)
engine.setProperty('volume', 0.9)
engine.say(text)
engine.runAndWait()
except Exception as e:
logger.error(f"Fallback speech also failed: {e}")
# Print to console as last resort
print(f"SPEECH: {text}")
def _use_edge_tts(self, text):
"""Use edge-tts to generate and play speech"""
if not text or text.strip() == "":
return
# Run async code in a thread to avoid blocking
def run_async_tts():
# Create a new event loop for this thread
loop = self.asyncio.new_event_loop()
self.asyncio.set_event_loop(loop)
try:
# Generate speech with edge-tts
self.currently_playing = True
loop.run_until_complete(self._generate_and_play_speech(text))
except Exception as e:
logger.error(f"Edge TTS error: {e}")
finally:
self.currently_playing = False
loop.close()
# Run the async code in a separate thread
self.executor.submit(run_async_tts)
async def _generate_and_play_speech(self, text):
"""Generate speech with edge-tts and play it"""
# Create temp file for audio
temp_file = None
try:
# Get text-to-speech stream
communicate = self.edge_tts.Communicate(
text,
self.voice,
rate=self.rate,
volume=self.volume,
pitch=self.pitch
)
# Create a temporary file
with self.tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tf:
temp_file = tf.name
# Save audio to temp file
await communicate.save(temp_file)
# Check if we should stop
if self.stop_current:
self.stop_current = False
# Don't try to delete the file yet - we'll handle cleanup separately
return
# Play the audio using pygame
try:
if self.pygame.mixer.get_init(): # Make sure mixer is initialized
self.pygame.mixer.music.load(temp_file)
self.pygame.mixer.music.play()
# Wait for audio to finish playing
while self.pygame.mixer.music.get_busy():
# Check if we should stop
if self.stop_current:
self.pygame.mixer.music.stop()
self.stop_current = False
break
await self.asyncio.sleep(0.1)
else:
logger.error("Pygame mixer not initialized")
except Exception as playback_error:
logger.error(f"Error playing audio with pygame: {playback_error}")
except Exception as e:
logger.error(f"Error in speech generation: {e}")
# We don't try to delete the temp file here anymore
# The OS will handle cleanup of temp files automatically
# This avoids "file in use" errors
def stop_speech(self):
"""Stop any currently playing speech"""
if self.currently_playing:
self.stop_current = True
try:
if self.pygame.mixer.get_init() and self.pygame.mixer.music.get_busy():
self.pygame.mixer.music.stop()
except Exception as e:
logger.error(f"Error stopping speech: {e}")
def set_voice(self, voice_name):
"""Change the voice used for speech"""
self.voice = voice_name
logger.info(f"Changed voice to: {voice_name}")
return True
def set_speech_parameters(self, rate=None, volume=None, pitch=None):
"""Set speech parameters for edge-tts"""
if rate is not None:
# Format should be like "+0%", "+10%", "-10%"
self.rate = rate
if volume is not None:
# Format should be like "+0%", "+10%", "-10%"
self.volume = volume
if pitch is not None:
# Format should be like "+0Hz", "+10Hz", "-10Hz"
self.pitch = pitch
logger.info(f"Speech parameters updated: rate={self.rate}, volume={self.volume}, pitch={self.pitch}")
# Speech recognition
class StonicSTT(QThread):
text_recognized = pyqtSignal(str)
listening_started = pyqtSignal()
listening_ended = pyqtSignal()
def __init__(self):
super().__init__()
self.recognizer = sr.Recognizer()
# Load parameters from config file
self.energy_threshold = SPEECH_SETTINGS.get("energy_threshold", 1500) # Even lower for better sensitivity
self.dynamic_energy_threshold = SPEECH_SETTINGS.get("dynamic_energy_threshold", True)
self.dynamic_energy_adjustment_damping = SPEECH_SETTINGS.get("dynamic_energy_adjustment_damping", 0.10) # More responsive
self.dynamic_energy_adjustment_ratio = SPEECH_SETTINGS.get("dynamic_energy_adjustment_ratio", 2.0) # More sensitive
self.pause_threshold = SPEECH_SETTINGS.get("pause_threshold", 0.5) # Shorter pause detection
self.timeout = SPEECH_SETTINGS.get("timeout", 5) # Shorter timeout for faster response
self.phrase_time_limit = SPEECH_SETTINGS.get("phrase_time_limit", 5) # Shorter phrase limit for faster response
self.ambient_noise_adjustment_duration = SPEECH_SETTINGS.get("ambient_noise_adjustment_duration", 1.0) # Shorter adjustment
self.default_microphone_index = SPEECH_SETTINGS.get("default_microphone_index", None)
self.non_speaking_duration = SPEECH_SETTINGS.get("non_speaking_duration", 0.3) # Shorter for faster detection
self.operation_timeout = SPEECH_SETTINGS.get("operation_timeout", None)
self.retry_attempts = SPEECH_SETTINGS.get("retry_attempts", 2) # Fewer attempts for faster response
self.use_google_cloud = SPEECH_SETTINGS.get("use_google_cloud", False)
self.continuous_listening = SPEECH_SETTINGS.get("continuous_listening", True) # Always listen for commands
# Configure the recognizer
self.recognizer.energy_threshold = self.energy_threshold
self.recognizer.dynamic_energy_threshold = self.dynamic_energy_threshold
self.recognizer.dynamic_energy_adjustment_damping = self.dynamic_energy_adjustment_damping
self.recognizer.dynamic_energy_adjustment_ratio = self.dynamic_energy_adjustment_ratio
self.recognizer.pause_threshold = self.pause_threshold
self.recognizer.non_speaking_duration = self.non_speaking_duration
self.recognizer.operation_timeout = self.operation_timeout
self.is_listening = False
self.stop_requested = False
# Language settings
self.primary_language = LANGUAGE_SETTINGS["primary_language"]
self.secondary_language = LANGUAGE_SETTINGS["secondary_language"]
self.use_multilingual = LANGUAGE_SETTINGS["use_multilingual"]
logger.info(f"Speech recognition initialized with: energy_threshold={self.energy_threshold}, "
f"pause_threshold={self.pause_threshold}, timeout={self.timeout}")
def run(self):
"""Listen for speech and emit recognized text"""
self.is_listening = True
self.stop_requested = False
self.listening_started.emit()
try:
with sr.Microphone() as source:
logger.info("Listening for command...")
# Better ambient noise adjustment with configurable duration
self.recognizer.adjust_for_ambient_noise(source, duration=self.ambient_noise_adjustment_duration)
# Log the current threshold after adjustment
logger.info(f"Energy threshold adjusted to: {self.recognizer.energy_threshold}")
# Continuous listening loop
while not self.stop_requested:
# Try to get speech input
try:
# Listen with better parameters
logger.debug("Waiting for speech...")
audio = self.recognizer.listen(
source,
timeout=self.timeout,
phrase_time_limit=self.phrase_time_limit
)
# Process audio in a separate thread to keep listening
threading.Thread(target=self._process_audio, args=(audio,)).start()
# Adjust for ambient noise periodically to handle changing environments
if random.random() < 0.1: # 10% chance to readjust
self.recognizer.adjust_for_ambient_noise(source, duration=0.5)
except sr.WaitTimeoutError:
# No speech detected, continue listening
continue
except Exception as e:
logger.error(f"Error during speech recognition: {e}")
time.sleep(0.1) # Small delay to prevent CPU overuse on errors
# Small delay to prevent over-processing
time.sleep(0.05)
except Exception as e:
logger.error(f"Error in continuous listening: {e}")
self.is_listening = False
self.listening_ended.emit()
def _process_audio(self, audio):
"""Process audio data in a separate thread"""
recognized_text = ""
attempt = 0
max_attempts = self.retry_attempts
while not recognized_text and attempt < max_attempts:
attempt += 1
logger.info(f"Recognition attempt {attempt}/{max_attempts}")
try:
# Try Google Speech API with primary language (English-India)
try:
recognized_text = self.recognizer.recognize_google(
audio,
language=self.primary_language,
show_all=False # Only return the most likely result
)
logger.info(f"Recognized ({self.primary_language}): '{recognized_text}'")
break
except sr.UnknownValueError:
logger.info(f"Speech not recognized in {self.primary_language}")
# Try with US English
try:
recognized_text = self.recognizer.recognize_google(
audio,
language="en-US", # Fallback to standard English
show_all=False
)
logger.info(f"Recognized fallback (en-US): '{recognized_text}'")
break
except sr.UnknownValueError:
logger.info("Speech not recognized in fallback language")
# Try with Hindi if multilingual is enabled
if self.use_multilingual:
try:
recognized_text = self.recognizer.recognize_google(
audio,
language=self.secondary_language
)
logger.info(f"Recognized ({self.secondary_language}): '{recognized_text}'")
break
except sr.UnknownValueError:
logger.info(f"Speech not recognized in {self.secondary_language}")
except sr.RequestError as e:
logger.error(f"Could not request results from Google Speech service: {e}")
break
# If we recognized something, emit the signal
if recognized_text:
self.text_recognized.emit(recognized_text)
def stop(self):
"""Stop listening"""
self.stop_requested = True
logger.info("Stop listening requested")
def setup_microphone(self, device_index=None):
"""Set up the microphone with the specified device index"""
try:
# If no device index is provided, use the default from config
if device_index is None:
device_index = self.default_microphone_index
# List available microphones
mics = sr.Microphone.list_microphone_names()
logger.info(f"Available microphones: {mics}")
# If a specific device is selected, use it
if device_index is not None:
self.mic = sr.Microphone(device_index=device_index)
logger.info(f"Using microphone device at index {device_index}")
# Otherwise use default
else:
self.mic = sr.Microphone()
logger.info("Using default microphone")
except Exception as e:
logger.error(f"Error setting up microphone: {e}")
self.mic = sr.Microphone() # Fallback to default microphone
logger.info("Falling back to default microphone")
# Command processor
class CommandProcessor:
def __init__(self, tts_engine):
self.tts = tts_engine
# Keep track of open applications
self.open_applications = {} # Will store {app_name: process}
self.open_websites = set() # Will store names of open websites
# Initialize Cohere client
self.co = cohere.Client(COHERE_API_KEY)
# Track conversation context
self.conversation_history = []
self.last_response = None
# Track API usage for rate limiting
self.cohere_requests = 0
self.last_cohere_request = 0
self.cohere_rate_limit = 5 # requests per minute
# Improved Cohere prompt for more natural and informative responses
self.cohere_prompt = """
You are Stonic, a highly intelligent, friendly, and efficient personal AI assistant created by Himanshu. You have a warm, conversational personality that makes users feel like they're talking to a human friend.
Your personality traits:
- Friendly and approachable, but professional and confident
- Use natural, conversational language with varied sentence structures
- Show personality through your responses with appropriate enthusiasm
- Be empathetic and understanding of user needs
- Use appropriate humor when suitable
- Maintain a helpful and positive attitude
- Be concise yet thorough in your explanations
Your communication style:
- Use contractions (I'm, you're, that's) for natural flow
- Occasionally use casual expressions like "you know", "actually", "well"
- Add personality through phrases like "I think", "I believe", "in my opinion"
- Use appropriate emojis in text responses (but not in speech)
- Keep responses concise but engaging
- Vary your sentence length and structure for natural rhythm
- Use analogies and examples to explain complex concepts
Your knowledge capabilities:
- You have extensive knowledge about technology, science, history, arts, and general topics
- For programming questions, provide code examples when helpful
- For factual questions, provide clear, accurate information with context
- For opinion questions, offer balanced perspectives
- For how-to questions, provide step-by-step instructions
- Acknowledge when information might be outdated or uncertain
Your role:
- Answer questions clearly and conversationally
- Provide explanations in a simple, easy-to-understand manner
- Help with programming, homework, productivity, and general tasks
- If unsure about something, say so instead of making things up
- If a question requires real-time info, acknowledge your limitations
- Personalize responses based on previous interactions when possible
Always respond as Stonic, and do not mention you are powered by Cohere or any other AI system.
Example responses:
User: What's the weather like?
Stonic: I'd be happy to check the weather for you, but I'll need your permission to access that information. Would you like me to look it up?
User: Can you help me with my math homework?
Stonic: Of course! I'd be glad to help with your math homework. What specific problem are you working on? I'll do my best to explain it in a way that makes sense to you.
User: Tell me about quantum computing.
Stonic: Quantum computing is fascinating! Unlike classical computers that use bits (0s and 1s), quantum computers use quantum bits or "qubits" that can exist in multiple states simultaneously thanks to quantum mechanics principles like superposition and entanglement. This allows them to solve certain complex problems much faster than traditional computers. They're still in early development stages but show promise for fields like cryptography, drug discovery, and optimization problems. What specific aspect of quantum computing interests you most?
Begin helping Himanshu now.
"""
def _get_ollama_response(self, query):
"""Get response from Ollama Llama3 when Cohere is unavailable"""
try:
# Add conversation history to provide context
context = "\n".join(self.conversation_history[-3:]) if self.conversation_history else ""
# Construct the prompt with context
full_prompt = f"{self.cohere_prompt}\n\n"
if context:
full_prompt += f"Previous conversation:\n{context}\n\n"
full_prompt += f"User: {query}\nStonic:"
# Make request to Ollama API
response = requests.post(
'http://localhost:11434/api/generate',
json={
"model": "llama3", # Changed from llama2 to llama3
"prompt": full_prompt,
"stream": False,
"options": {
"temperature": 0.8,
"top_p": 0.9,
"max_tokens": 200
}
}
)
if response.status_code == 200:
response_text = response.json()['response'].strip()
# Update conversation history
self.conversation_history.append(f"User: {query}")
self.conversation_history.append(f"Stonic: {response_text}")
# Keep history manageable
if len(self.conversation_history) > 10:
self.conversation_history = self.conversation_history[-10:]
return response_text
else:
logger.error(f"Ollama API error: {response.status_code}")
return None
except Exception as e:
logger.error(f"Error getting Ollama response: {e}")
return None
def _get_cohere_response(self, query):
"""Get response from Cohere API with enhanced context and fallback to Ollama"""
try:
# Check rate limiting
current_time = time.time()
if current_time - self.last_cohere_request < 60: # Within last minute
self.cohere_requests += 1
if self.cohere_requests >= self.cohere_rate_limit:
logger.warning("Cohere rate limit reached, falling back to Ollama")
return self._get_ollama_response(query)
else:
# Reset counter for new minute
self.cohere_requests = 1
self.last_cohere_request = current_time
# Add conversation history to provide context
context = "\n".join(self.conversation_history[-3:]) if self.conversation_history else ""
# Construct the prompt with context
full_prompt = f"{self.cohere_prompt}\n\n"
if context:
full_prompt += f"Previous conversation:\n{context}\n\n"
full_prompt += f"User: {query}\nStonic:"
# Generate response using default model
response = self.co.generate(
prompt=full_prompt,
max_tokens=300,
temperature=0.7,
k=0,
p=0.9,
frequency_penalty=0.3,
presence_penalty=0.3,
stop_sequences=["User:", "\n\n"],
return_likelihoods='NONE'
)
response_text = response.generations[0].text.strip()
# Update conversation history
self.conversation_history.append(f"User: {query}")
self.conversation_history.append(f"Stonic: {response_text}")
# Keep history manageable
if len(self.conversation_history) > 10:
self.conversation_history = self.conversation_history[-10:]
return response_text
except Exception as e:
logger.error(f"Error getting Cohere response: {e}")
# Fall back to Ollama
logger.info("Falling back to Ollama for response")
return self._get_ollama_response(query)
def process_command(self, command):
"""Process voice command and execute appropriate action"""
if not command:
response = "I'm not quite sure I understand. Could you rephrase that?"
self.tts.speak(response)
return response
command = command.lower().strip()
response = None
# Log the command for debugging
logger.info(f"Processing command: {command}")
# Enhanced command categorization using more flexible pattern matching
command_type = self._categorize_command(command)
# Process based on command category
if command_type == "exit":
response = random.choice([
"Goodbye! It was great chatting with you. Have a wonderful day!",
"See you later! I'll be here when you need me.",
"Shutting down now. Feel free to call me when you need assistance again.",
"Goodbye! It's been a pleasure helping you today."
])
elif command_type == "time":
now = datetime.datetime.now()
time_str = now.strftime("%I:%M %p")
response = f"It's currently {time_str}. Time flies when you're having fun, doesn't it?"
elif command_type == "date":
now = datetime.datetime.now()
date_str = now.strftime("%A, %B %d, %Y")
response = f"Today is {date_str}. I hope you're having a great day!"
elif command_type == "close_app":
app_name = self._extract_target_name(command, "close")
if app_name:
response = self._close_application(app_name)
else:
response = "I'm sorry. I don't know what you want me to close. Please specify an application."
elif command_type == "close_website":
site_name = self._extract_website_name(command)
if site_name:
response = self._close_website(site_name)
else:
response = "I'm sorry. I don't know what website you want me to close. Please specify a website."
elif command_type == "youtube_search":
query = self._extract_search_query(command, ["youtube", "search", "for", "on", "find"])
if query:
response = self._youtube_search(query)
else:
response = "What would you like me to search for on YouTube?"
elif command_type == "google_search":
query = self._extract_search_query(command, ["google", "search", "for", "look up", "find"])
if query:
response = self._google_search(query)
else:
response = "What would you like me to search for?"
elif command_type == "open_app":
app_name = self._extract_target_name(command, "open")
if app_name:
response = self._open_application(app_name)
else:
response = "I'm sorry. I don't know what application you want me to open. Please specify an application."
elif command_type == "open_website":
site_name = self._extract_website_name(command)
if site_name:
for name, url in WEBSITES.items():
if name in site_name:
response = self._open_website(name, url)
break
if not response:
# Create search query for the website if not in known websites
search_query = f"{site_name}.com"
response = self._google_search(search_query)
else:
response = "I'm sorry. I don't know what website you want me to open. Please specify a website."
elif command_type == "system_status":
# Get random values for this demo
cpu = random.randint(5, 95)
memory = random.uniform(2.1, 8.5)
disk = random.randint(100, 500)
response = f"Let me check your system status... Your CPU is running at {cpu}%, you're using {memory:.1f} gigabytes of memory, and you have {disk} gigabytes of free disk space. Everything seems to be running smoothly!"
elif command_type == "weather":
response = "I'd be happy to check the weather for you, but I'll need your permission to access that information. Would you like me to look it up?"
elif command_type == "joke":
# English jokes only
english_jokes = [
"Why don't scientists trust atoms? Because they make up everything! 😄",
"Did you hear about the mathematician who's afraid of negative numbers? He'll stop at nothing to avoid them! 😂",
"Why was the computer cold? It left its Windows open! 🪟",
"How many programmers does it take to change a light bulb? None, that's a hardware problem! 💡",
"Why do programmers always mix up Halloween and Christmas? Because Oct 31 equals Dec 25! 🎃",
"I asked my dog what's two minus two. He said nothing. 🐶",
"What do you call a fake noodle? An impasta! 🍝",
"Why did the scarecrow win an award? Because he was outstanding in his field! 🌾",
"What's the best thing about Switzerland? I don't know, but the flag is a big plus! 🇨🇭",
"I told my wife she was drawing her eyebrows too high. She looked surprised! 😲"
]
response = random.choice(english_jokes)
elif command_type == "help":
response = "I'm here to help you with all sorts of tasks! I can open and close applications and websites, search Google and YouTube, tell you the time and date, share jokes, check your system status, answer questions about various topics, and much more. Just ask me what you need!"
elif command_type == "who":
response = "I'm Stonic, your friendly personal assistant! I was designed to help you with everyday tasks through voice commands. I can answer questions, open applications, search the web, tell jokes, and much more. I'm always learning and improving to serve you better. How can I assist you today?"
# No recognized command - try Cohere for general questions and conversation
else:
cohere_response = self._get_cohere_response(command)
if cohere_response:
response = cohere_response
else:
response = random.choice([
"I'm not quite sure I understand. Could you rephrase that?",
"Hmm, I didn't catch that. Mind trying again?",
"I'm still learning. Could you try asking that differently?",
"I'm not sure I follow. Could you explain that another way?"
])
# Speak response
if response:
logger.info(f"Speaking response: {response}")
self.tts.speak(response)
return response
def _categorize_command(self, command):
"""Categorize the command type for better processing"""
# Exit commands
if any(exit_cmd in command for exit_cmd in ["exit", "quit", "bye", "goodbye", "shutdown", "shut down"]):
return "exit"
# Time commands
elif any(time_cmd in command for time_cmd in ["what time", "current time", "time now", "tell me the time"]):
return "time"
# Date commands
elif any(date_cmd in command for date_cmd in ["what date", "current date", "date today", "tell me the date", "what day"]):
return "date"
# Close application
elif "close" in command and not any(site in command for site in WEBSITES.keys()):
return "close_app"
# Close website
elif "close" in command and any(site in command for site in WEBSITES.keys()):
return "close_website"
# YouTube search commands
elif any(youtube_cmd in command for youtube_cmd in [
"search on youtube", "youtube search", "search youtube",
"look up on youtube", "find on youtube", "youtube find"
]):
return "youtube_search"
# Google search command
elif "search" in command and "youtube" not in command:
return "google_search"
# Open application
elif "open" in command and not any(site in command for site in WEBSITES.keys()):
return "open_app"
# Open website
elif "open" in command or any(site in command for site in WEBSITES.keys()):
return "open_website"
# System status command
elif any(status_cmd in command for status_cmd in ["system status", "system info", "performance", "cpu usage"]):
return "system_status"
# Weather command
elif any(weather_cmd in command for weather_cmd in ["weather", "temperature", "forecast"]):
return "weather"
# Joke command
elif any(joke_cmd in command for joke_cmd in ["joke", "funny", "make me laugh"]):
return "joke"
# Help command
elif any(help_cmd in command for help_cmd in ["help", "commands", "what can you do"]):
return "help"
# Who are you
elif any(who_cmd in command for who_cmd in ["who are you", "your name", "introduce yourself"]):
return "who"
# General query - will be handled by Cohere
return "general_query"
def _extract_target_name(self, command, action_word):
"""Extract target name (app or website) from command"""
words = command.split()
if action_word in words:
idx = words.index(action_word)
if idx + 1 < len(words):
# Get everything after the action word
target = " ".join(words[idx + 1:])
# Clean up common words
for word in ["the", "app", "application", "website", "site", "page"]:
target = target.replace(f" {word} ", " ").replace(f" {word}", "")
return target.strip()
return None
def _extract_website_name(self, command):
"""Extract website name from command"""
# First check for known websites
for site in WEBSITES.keys():
if site in command:
return site
# Then try to extract from "open" command
if "open" in command:
return self._extract_target_name(command, "open")
return None
def _extract_search_query(self, command, keywords_to_remove):
"""Extract search query by removing keywords"""
query = command
# Remove all keywords
for keyword in keywords_to_remove:
query = query.replace(keyword, " ")
# Clean up the query
query = " ".join(query.split())
return query.strip()
def _open_application(self, app_name):
"""Open an application using keyboard automation"""
try:
# Import pyautogui for keyboard automation
import pyautogui
import time
# Press Windows key to open start menu
pyautogui.press('win')
time.sleep(0.5) # Wait for start menu
# Type the application name
pyautogui.write(app_name)
time.sleep(0.5) # Wait for search results
# Press enter to open the application
pyautogui.press('enter')
# Store the process for later closing
self.open_applications[app_name] = True
return f"Opening {app_name}."
except Exception as e:
logger.error(f"Error opening application: {e}")