Repository navigation
Expand file tree
/
Copy pathspeaker.py
More file actions
398 lines (333 loc) · 13.4 KB
/
Copy pathspeaker.py
File metadata and controls
398 lines (333 loc) · 13.4 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
"""
Speaker module for Stonic voice assistant
Handles text-to-speech functionality
"""
import os
import time
import threading
import logging
import pyttsx3
import tempfile
import queue
from config import TTS_SETTINGS, USER_NAME
# Configure logging
logger = logging.getLogger("Stonic.Speaker")
class Speaker:
"""Class to handle text-to-speech functionality"""
def __init__(self):
"""Initialize the text-to-speech engine with optimal settings"""
# Load settings from config
self.rate = TTS_SETTINGS.get("rate", 150)
self.volume = TTS_SETTINGS.get("volume", 1.0)
self.voice_id = TTS_SETTINGS.get("voice_id", None)
self.split_long_responses = TTS_SETTINGS.get("split_long_responses", True)
self.response_chunk_size = TTS_SETTINGS.get("response_chunk_size", 100)
self.use_gtts_fallback = TTS_SETTINGS.get("use_gtts_fallback", False)
# Initialize pyttsx3 engine
self.engine = self._create_engine()
# Add speech queue for interruptible speech
self.speech_queue = queue.Queue()
self.current_speech = None
self.speaking = False
self.stop_current = False
# Start speech queue processor thread
self.speech_thread = threading.Thread(target=self._process_speech_queue)
self.speech_thread.daemon = True
self.speech_thread.start()
logger.info(f"Speaker initialized with rate={self.rate}, volume={self.volume}")
def _create_engine(self):
"""Create and configure a pyttsx3 engine instance"""
engine = pyttsx3.init()
# Configure engine properties
engine.setProperty('rate', self.rate)
engine.setProperty('volume', self.volume)
# Set preferred voice
if self.voice_id:
engine.setProperty('voice', self.voice_id)
else:
# Try to find a good voice
voices = engine.getProperty('voices')
preferred_voice = None
# Look for a natural-sounding male voice
for voice in voices:
voice_name = voice.name.lower()
# Look for high-quality voices first
if any(name in voice_name for name in ["david", "mark", "james", "tom"]):
preferred_voice = voice.id
logger.info(f"Selected premium male voice: {voice.name}")
break
# If no premium voice found, check other english voices
if not preferred_voice and voices:
for voice in voices:
if "en" in voice.id.lower():
preferred_voice = voice.id
logger.info(f"Selected English voice: {voice.name}")
break
# If still no voice, use first available
if not preferred_voice and voices:
preferred_voice = voices[0].id
logger.info(f"Using default voice: {voices[0].name}")
# Set the voice if found
if preferred_voice:
engine.setProperty('voice', preferred_voice)
return engine
def get_available_voices(self):
"""Get a list of available voices"""
voices = []
for voice in self.engine.getProperty('voices'):
voices.append({
'id': voice.id,
'name': voice.name,
'languages': voice.languages
})
return voices
def speak(self, text, interrupt=False):
"""
Convert text to speech
Args:
text (str): Text to convert to speech
interrupt (bool): Whether to interrupt current speech
"""
if not text:
logger.warning("Empty text provided to speak function")
return
logger.info(f"Speaking: {text}")
# Handle speech interruption
if interrupt and self.speaking:
self.stop_current = True
while self.speaking:
time.sleep(0.1)
self.speech_queue = queue.Queue() # Clear queue
# Process text if needed (e.g., adding personalization)
processed_text = self._process_text(text)
# Add to speech queue
self.speech_queue.put(processed_text)
def _process_text(self, text):
"""
Process text before speaking (add personalization, etc.)
Args:
text (str): Original text
Returns:
str: Processed text
"""
# Replace placeholders with actual values if needed
if "{name}" in text.lower():
text = text.replace("{name}", USER_NAME)
return text
def _process_speech_queue(self):
"""Process the speech queue in a separate thread"""
while True:
try:
# Get next text to speak
if not self.speech_queue.empty():
text = self.speech_queue.get()
self.speaking = True
self.stop_current = False
self.current_speech = text
# Check if we should split long responses
if self.split_long_responses and len(text) > self.response_chunk_size:
# Split text into sentences
sentences = text.split('.')
first_part = sentences[0] + '.'
remaining = '.'.join(sentences[1:])
# Speak first part
self._speak_text(first_part)
if remaining and not self.stop_current:
# Speak remaining text if not interrupted
self._speak_text(remaining)
else:
# Speak entire text
self._speak_text(text)
self.speaking = False
self.current_speech = None
self.speech_queue.task_done()
else:
# No speech queued
time.sleep(0.1)
except Exception as e:
logger.error(f"Error in speech queue processing: {e}")
self.speaking = False
time.sleep(0.5)
def _speak_text(self, text):
"""
Internal method to speak text with pyttsx3 or gTTS fallback
Args:
text (str): Text to speak
"""
if not text or text.strip() == "":
return
try:
# Try with pyttsx3 first
self.engine.say(text)
self.engine.runAndWait()
except Exception as e:
logger.error(f"Error with pyttsx3: {e}")
# Try to recreate engine if there was an error
try:
logger.info("Recreating pyttsx3 engine")
self.engine = self._create_engine()
self.engine.say(text)
self.engine.runAndWait()
except Exception as e2:
logger.error(f"Error with recreated engine: {e2}")
# Try gTTS as fallback if enabled
if self.use_gtts_fallback:
self._speak_with_gtts(text)
def _speak_with_gtts(self, text):
"""
Fallback method to use gTTS for speech
Args:
text (str): Text to speak
"""
try:
from gtts import gTTS
from playsound import playsound
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as temp_file:
temp_path = temp_file.name
# Generate speech
tts = gTTS(text=text, lang='en', slow=False)
tts.save(temp_path)
# Play speech
playsound(temp_path)
# Clean up temporary file
try:
os.remove(temp_path)
except Exception as e:
logger.warning(f"Could not remove temporary file: {e}")
except Exception as e:
logger.error(f"Error with gTTS fallback: {e}")
def stop(self):
"""Stop all speech immediately"""
if self.speaking:
self.stop_current = True
try:
self.engine.stop()
except:
pass
# Clear queue
while not self.speech_queue.empty():
try:
self.speech_queue.get_nowait()
self.speech_queue.task_done()
except:
pass
def change_voice(self, voice_id):
"""
Change the voice used for speech
Args:
voice_id (str): ID of the voice to use
"""
try:
self.voice_id = voice_id
self.engine.setProperty('voice', voice_id)
logger.info(f"Changed voice to: {voice_id}")
return True
except Exception as e:
logger.error(f"Error changing voice: {e}")
return False
def change_rate(self, rate):
"""
Change the speech rate
Args:
rate (int): New speech rate (words per minute)
"""
try:
self.rate = rate
self.engine.setProperty('rate', rate)
logger.info(f"Changed speech rate to: {rate}")
return True
except Exception as e:
logger.error(f"Error changing speech rate: {e}")
return False
def change_volume(self, volume):
"""
Change the speech volume
Args:
volume (float): New volume level (0.0 to 1.0)
"""
try:
self.volume = max(0.0, min(1.0, volume)) # Clamp between 0 and 1
self.engine.setProperty('volume', self.volume)
logger.info(f"Changed speech volume to: {self.volume}")
return True
except Exception as e:
logger.error(f"Error changing speech volume: {e}")
return False
# Utility methods for common phrases
def say_greeting(self):
"""Speak a greeting"""
current_hour = time.localtime().tm_hour
if 5 <= current_hour < 12:
greeting = f"Good morning, {USER_NAME}. How can I assist you today?"
elif 12 <= current_hour < 17:
greeting = f"Good afternoon, {USER_NAME}. How can I assist you today?"
elif 17 <= current_hour < 22:
greeting = f"Good evening, {USER_NAME}. How can I assist you today?"
else:
greeting = f"Hello {USER_NAME}. You're up late. How can I assist you?"
self.speak(greeting)
def say_farewell(self):
"""Speak a farewell message"""
farewells = [
f"Goodbye, {USER_NAME}. Have a great day!",
f"See you later, {USER_NAME}.",
f"Until next time, {USER_NAME}.",
f"Shutting down now. Let me know if you need anything else, {USER_NAME}."
]
import random
self.speak(random.choice(farewells))
def say_confirmation(self, action):
"""Speak a confirmation of an action"""
confirmations = [
f"I've {action} for you, {USER_NAME}.",
f"{action.capitalize()} completed, {USER_NAME}.",
f"Done! I've {action}.",
f"Task complete. I've {action} as requested."
]
import random
self.speak(random.choice(confirmations))
def say_error(self, error_type="general"):
"""Speak an error message"""
if error_type == "not_understood":
errors = [
f"I'm sorry, {USER_NAME}, I didn't understand that.",
f"Could you please rephrase that, {USER_NAME}?",
f"I didn't quite catch that. Can you try again?"
]
elif error_type == "cannot_perform":
errors = [
f"I'm sorry, {USER_NAME}, I can't perform that action right now.",
f"I'm unable to complete that task at the moment.",
f"I encountered a problem while trying to do that."
]
else:
errors = [
f"I'm sorry, {USER_NAME}, something went wrong.",
f"I encountered an error.",
f"There was a problem processing your request."
]
import random
self.speak(random.choice(errors))
# Helper function to initialize the speaker
def initialize_speaker():
"""Initialize and return the speaker"""
return Speaker()
# For testing this module independently
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
speaker = Speaker()
# Test different types of speech
speaker.speak("This is a test of the Stonic text-to-speech system.")
time.sleep(2)
# Test interruption
speaker.speak("This is a very long sentence that should be interrupted before it finishes.")
time.sleep(1)
speaker.speak("Interrupting previous speech!", interrupt=True)
time.sleep(2)
# Test utility methods
speaker.say_greeting()
time.sleep(3)
speaker.say_confirmation("opened your email")
time.sleep(2)
speaker.say_farewell()