Repository navigation
Expand file tree
/
Copy pathemo_v6.py
More file actions
1660 lines (1412 loc) · 66.9 KB
/
Copy pathemo_v6.py
File metadata and controls
1660 lines (1412 loc) · 66.9 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
#!/usr/bin/env python3
"""
emo_v6.py - Reachy Mini Advanced Emotion Controller with Edge-TTS
A comprehensive emotion controller for Reachy Mini robot featuring:
1. Edge-TTS Integration: Microsoft Azure voices with emotional parameters
2. Advanced Emotion Analysis: Multi-language emotion detection with intensity levels
3. Combined Action Sequences: Synchronized head, antenna, eye, and body movements
4. Lip-Sync System: Dynamic antenna/eye movements during speech
5. Recorded Moves Library: Integration with Pollen Robotics dance moves
6. Ollama Chat Interface: Interactive conversation with emotional responses
7. Command-Line Testing: Multiple test modes for TTS, actions, and chat
Features sophisticated combined movements including:
- Nod with blink synchronization
- Shake with body yaw and eye movements
- Antenna wiggle with blinking
- Complex emotion sequences (excited, sad, curious, etc.)
- Individual component testing
Command-line usage:
- --chat: Interactive chat mode
- --test-tts: Test Edge-TTS functionality
- --test-actions: Test robot action sequences
- --debug: Enable detailed logging
"""
import sys
import time
import json
import threading
import numpy as np
from typing import Dict, List, Tuple, Optional
def _create_head_pose(*args, **kwargs):
from reachy_mini.utils import create_head_pose as _chp
return _chp(*args, **kwargs)
def check_runtime_dependencies(require_reachy: bool = False) -> bool:
"""Check that optional runtime deps are importable."""
missing = []
try:
import requests # noqa: F401
except Exception:
missing.append("requests")
if require_reachy:
try:
import reachy_mini # noqa: F401
except Exception:
missing.append("reachy-mini")
if missing:
print(f"❌ Missing runtime dependencies: {', '.join(missing)}")
print(" Install: pip install -r requirements.txt")
if "reachy-mini" in missing:
print(" For robot: pip install 'reachy-mini[mujoco]'")
return False
return True
# Emotion mapping and presets (copied from ReachyClaw for richer expressions)
_EMOTION_CATEGORY_MAP: Dict[str, str] = {
# positive
"amazed1": "positive",
"cheerful1": "positive",
"dance1": "positive",
"dance2": "positive",
"dance3": "positive",
"enthusiastic1": "positive",
"enthusiastic2": "positive",
"grateful1": "positive",
"helpful1": "positive",
"helpful2": "positive",
"laughing1": "positive",
"laughing2": "positive",
"loving1": "positive",
"proud1": "positive",
"proud2": "positive",
"proud3": "positive",
"relief1": "positive",
"relief2": "positive",
"success1": "positive",
"success2": "positive",
"welcoming1": "positive",
"welcoming2": "positive",
"yes1": "positive",
"understanding2": "positive",
"electric1": "positive",
# negative
"anxiety1": "negative",
"boredom1": "negative",
"boredom2": "negative",
"contempt1": "negative",
"displeased1": "negative",
"displeased2": "negative",
"downcast1": "negative",
"disgusted1": "negative",
"dying1": "negative",
"exhausted1": "negative",
"fear1": "negative",
"frustrated1": "negative",
"furious1": "negative",
"go_away1": "negative",
"impatient1": "negative",
"impatient2": "negative",
"irritated1": "negative",
"irritated2": "negative",
"lonely1": "negative",
"no1": "negative",
"no_sad1": "negative",
"rage1": "negative",
"sad1": "negative",
"sad2": "negative",
"scared1": "negative",
"tired1": "negative",
"reprimand1": "negative",
"reprimand2": "negative",
"reprimand3": "negative",
"calming1": "negative",
"yes_sad1": "negative",
"resigned1": "negative",
# question
"confused1": "question",
"curious1": "question",
"incomprehensible2": "question",
"inquiring1": "question",
"inquiring2": "question",
"inquiring3": "question",
"lost1": "question",
"thoughtful1": "question",
"thoughtful2": "question",
"uncertain1": "question",
"uncomfortable1": "question",
# activity
"no_excited1": "activity",
"serenity1": "activity",
# neutral
"attentive1": "neutral",
"attentive2": "neutral",
"come1": "neutral",
"indifferent1": "neutral",
"understanding1": "neutral",
"oops1": "neutral",
"oops2": "neutral",
"shy1": "neutral",
"sleep1": "neutral",
"proud1": "neutral",
"surprised1": "neutral",
"surprised2": "neutral",
}
_GENTLE_EMOTIONS = {
"attentive1", "attentive2", "understanding1", "understanding2",
"shy1", "come1", "indifferent1",
"grateful1", "helpful1", "helpful2", "relief1", "relief2",
"yes1", "welcoming1",
"thoughtful1", "thoughtful2", "curious1", "inquiring1",
"serenity1", "calming1",
}
_BIG_EMOTIONS = {
"dance1", "dance2", "dance3",
"enthusiastic1", "enthusiastic2",
"laughing1", "laughing2",
"proud1", "proud2", "proud3",
"amazed1", "electric1",
"furious1", "rage1",
}
_CARTOON_EMOTIONS = {
"enthusiastic1", "enthusiastic2", "dance1", "dance2", "dance3",
"cheerful1", "laughing1", "laughing2", "electric1", "success1",
"success2", "proud3", "no_excited1", "amazed1", "surprised1",
"surprised2", "scared1", "furious1", "rage1",
}
_WELCOME_EMOTIONS = ["welcoming1", "welcoming2", "enthusiastic2", "cheerful1"]
_FAREWELL_EMOTIONS = ["grateful1", "loving1", "welcoming2"]
class EdgeTTSEngine:
"""Edge-TTS engine with emotional voice selection"""
def __init__(self, default_voice: str = "en-US-JennyNeural", sample_rate: int = 22050):
self.default_voice = default_voice
self.sample_rate = sample_rate
self.debug = True # Force debug on for clarity
print(f"🎙️ EdgeTTSEngine initialized")
print(f" - Using voice: {default_voice}")
print(f" - Sample rate: {sample_rate}Hz")
# Cute cartoon voices that work!
#self.emotion_voices = {
# 'positive': "en-US-AnaNeural", # CARTOON - Cute, adorable ✨
# 'negative': "zh-CN-XiaoyiNeural", # CARTOON - Lively, cute Chinese
# 'question': "en-US-AnaNeural", # CARTOON - Cute, adorable
# 'activity': "zh-CN-XiaoyiNeural", # CARTOON - Lively, cute Chinese
# 'neutral': "en-US-AnaNeural", # CARTOON - Cute, adorable
#}
# Emotional voice mapping
self.emotion_voices = {
'positive': "en-US-JennyNeural", # Friendly, cheerful
'negative': "en-US-BrianNeural", # Softer, compassionate
'question': "en-US-BrianNeural", # Curious, thoughtful
'activity': "en-US-JennyNeural", # Energetic, lively
'neutral': default_voice, # Default Chinese
}
# Cute voice parameters with higher pitch for childlike sound
self.voice_params = {
'positive': {'rate': '+5%', 'pitch': '+4Hz', 'style': 'general'},
'negative': {'rate': '+0%', 'pitch': '+2Hz', 'style': 'general'},
'question': {'rate': '+8%', 'pitch': '+6Hz', 'style': 'general'},
'activity': {'rate': '+12%', 'pitch': '+8Hz', 'style': 'general'},
'neutral': {'rate': '+3%', 'pitch': '+3Hz', 'style': 'general'},
}
def _has_chinese(self, text: str) -> bool:
"""Detect presence of CJK Unified Ideographs (basic Chinese range)."""
if not text:
return False
for ch in text:
if '\u4e00' <= ch <= '\u9fff':
return True
return False
async def _speak_async(self, text: str, voice: str, rate: str = "+0%", pitch: str = "+0Hz", style: str = "general") -> Tuple:
"""Synthesize speech to a temporary WAV file with voice parameters, read it and return (audio, samplerate).
This avoids guessing the raw stream format and preserves the correct sample rate
so playback via sounddevice does not introduce noise.
"""
try:
import tempfile
import os
import numpy as np
import edge_tts
import soundfile as sf
# Save to a temporary WAV file using edge-tts's save helper
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp:
tmp_path = tmp.name
# Prefer default voice for Chinese text to avoid mismatched voice failures
prefer_default = self._has_chinese(text)
if prefer_default:
voice = self.default_voice
# Create communicate with voice parameters
communicate = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch)
if style != "general":
# Add style parameter if supported
try:
communicate = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch, style=style)
except:
# Fallback if style not supported
communicate = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch)
# Attempt to save; on failure, retry with default voice unless text is Chinese
try:
try:
await communicate.save(tmp_path)
except Exception as save_exc:
if self.debug and not prefer_default:
print(f"⚠️ Edge-TTS save error: {save_exc}")
if voice != self.default_voice and not prefer_default:
if self.debug and not prefer_default:
print("⚠️ Retrying synthesis with default voice...")
time.sleep(0.5)
try:
communicate = edge_tts.Communicate(text, self.default_voice, rate=rate, pitch=pitch)
await communicate.save(tmp_path)
except Exception as save_exc2:
if self.debug and not prefer_default:
print(f"⚠️ Retry with default voice failed: {save_exc2}")
raise save_exc2
else:
raise save_exc
except Exception:
# Ensure temp file cleaned
try:
if os.path.exists(tmp_path):
os.remove(tmp_path)
except Exception:
pass
raise
# If file is empty, retry with default voice (but suppress warnings for Chinese text)
try:
if os.path.getsize(tmp_path) == 0:
if voice != self.default_voice and not prefer_default:
if self.debug:
print("⚠️ Edge-TTS produced empty file; retrying with default voice...")
try:
communicate = edge_tts.Communicate(text, self.default_voice)
await communicate.save(tmp_path)
except Exception as e2:
if self.debug:
print(f"⚠️ Retry with default voice failed: {e2}")
except OSError:
# File might not exist yet; continue to read and let sf raise
pass
# Read the WAV file using soundfile to get correct dtype and samplerate
data, sr = sf.read(tmp_path, dtype='float32')
# Ensure mono or stereo shape is acceptable for sounddevice
if data.ndim == 1:
audio = data
else:
# sounddevice handles stereo arrays; keep as-is
audio = data
# Clean up temporary file
try:
os.remove(tmp_path)
except Exception:
pass
return audio, sr
except Exception as e:
if self.debug:
print(f"Edge-TTS synthesis error: {e}")
return np.array([], dtype=np.float32), 0
def speak_with_emotion(self, text: str, emotion: str = 'neutral'):
"""Speak text with emotional voice and parameters"""
if not text.strip():
return
import asyncio
voice = self.emotion_voices.get(emotion, self.default_voice)
params = self.voice_params.get(emotion, self.voice_params['neutral'])
try:
audio_data, sr = asyncio.run(self._speak_async(
text, voice,
rate=params['rate'],
pitch=params['pitch'],
style=params['style']
))
if sr and audio_data.size:
import sounddevice as sd
sd.play(audio_data, samplerate=sr)
sd.wait()
else:
if self.debug:
print("⚠️ No audio produced by Edge-TTS")
raise RuntimeError("No audio produced")
except Exception as e:
print(f"⚠️ Edge-TTS error: {e}")
self._fallback_tts(text, emotion)
async def speak_with_emotion_async(self, text: str, emotion: str = 'neutral'):
"""Async version of speak_with_emotion (works within existing event loop)"""
if not text.strip():
return
import asyncio
voice = self.emotion_voices.get(emotion, self.default_voice)
params = self.voice_params.get(emotion, self.voice_params['neutral'])
try:
audio_data, sr = await self._speak_async(
text, voice,
rate=params['rate'],
pitch=params['pitch'],
style=params['style']
)
if sr and audio_data.size:
import sounddevice as sd
# Play with the correct samplerate returned by the file
# Use asyncio.to_thread to run blocking sounddevice.play/wait in thread
await asyncio.to_thread(lambda: (sd.play(audio_data, samplerate=sr), sd.wait()))
else:
if self.debug:
print("⚠️ No audio produced by Edge-TTS (async)")
raise RuntimeError("No audio produced")
except Exception as e:
print(f"⚠️ Edge-TTS async error: {e}")
# Fallback to sync version for compatibility
self._fallback_tts(text, emotion)
def _fallback_tts(self, text: str, emotion: str):
"""Fallback if Edge-TTS fails"""
import subprocess
import platform
system = platform.system()
if system == "Darwin":
try:
subprocess.run(['say', text], check=True)
print("✅ Using macOS 'say' as fallback")
except:
pass
elif system == "Windows":
try:
import pyttsx3
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
print("✅ Using pyttsx3 as fallback")
except:
pass
class LipSyncControllerV5:
"""Lip-sync using your antenna/eye control approach"""
def __init__(self, reachy, debug: bool = False):
self.reachy = reachy
self.is_speaking = False
self.sync_thread = None
self.debug = debug
if debug:
print("✅ LipSyncControllerV5 initialized (handles antenna/eye movements)")
def start_lip_sync(self, text: str, emotion_level: float = 0.5):
"""Start lip-sync with your approach"""
self.is_speaking = True
def lip_sync_animation():
while self.is_speaking:
try:
# Check if robot head exists
if hasattr(self.reachy, 'head'):
self.reachy.head.r_antenna.goal_position = emotion_level * 0.8
self.reachy.head.l_antenna.goal_position = emotion_level * 0.8
self.reachy.head.r_eye.goal_position = 1 - (emotion_level * 0.3)
self.reachy.head.l_eye.goal_position = 1 - (emotion_level * 0.3)
except Exception as e:
print(f"⚠️ Lip-sync error (robot may not support): {e}")
break
time.sleep(0.1)
# Return to neutral (with error handling)
try:
if hasattr(self.reachy, 'head'):
self.reachy.head.r_antenna.goal_position = 0
self.reachy.head.l_antenna.goal_position = 0
self.reachy.head.r_eye.goal_position = 0.5
self.reachy.head.l_eye.goal_position = 0.5
except:
pass
self.sync_thread = threading.Thread(target=lip_sync_animation, daemon=True)
self.sync_thread.start()
def stop_lip_sync(self):
"""Stop lip-sync"""
self.is_speaking = False
if self.sync_thread:
self.sync_thread.join(timeout=0.5)
class EmotionControllerV6:
"""Emotion controller with enhanced continuous actions and combined movements"""
def __init__(self, reachy, debug: bool = False, gentle_mode: bool = True, voice: str = "zh-CN-XiaoxiaoNeural"):
from reachy_mini.motion.recorded_move import RecordedMoves
self.reachy = reachy
self.debug = debug
self.gentle_mode = gentle_mode
self.is_speaking_action = False
# TTS and lip-sync
self.tts_engine = EdgeTTSEngine(default_voice=voice)
self.lip_sync = LipSyncControllerV5(reachy, debug=self.debug)
# Load both libraries for richer motions
self.emotions_lib = RecordedMoves("pollen-robotics/reachy-mini-emotions-library")
self.dances_lib = RecordedMoves("pollen-robotics/reachy-mini-dances-library")
self._categorize_recorded_moves()
self.simple_actions = {
'nod': self._simple_nod,
'shake': self._simple_shake,
'look_curious': self._simple_look_curious,
'look_sad': self._simple_look_sad,
'excited_wiggle': self._simple_excited_wiggle,
'thoughtful_tilt': self._simple_thoughtful_tilt,
}
def _categorize_recorded_moves(self):
"""Build emotion_to_moves from both emotions and dances libraries."""
self.emotion_to_moves = {
'positive': [],
'negative': [],
'question': [],
'activity': [],
'neutral': [],
}
# 1. Emotions library — use hardcoded map, fall back to keyword scan
for move_name in self.emotions_lib.list_moves():
category = _EMOTION_CATEGORY_MAP.get(move_name)
if category is None:
category = self._keyword_category(move_name, self.emotions_lib)
self.emotion_to_moves[category].append(('emotions', move_name))
if self.debug:
print(f"🎭 emotions/{move_name} → {category}")
# 2. Dances library — keyword scan
for move_name in self.dances_lib.list_moves():
category = self._keyword_category(move_name, self.dances_lib)
self.emotion_to_moves[category].append(('dances', move_name))
if self.debug:
print(f"🕺 dances/{move_name} → {category}")
def _keyword_category(self, move_name: str, lib) -> str:
"""Fallback keyword-based categorisation using move description."""
try:
move = lib.get(move_name)
desc = (move.description or "").lower()
except Exception:
desc = move_name.lower()
scores = {
'positive': sum(1 for w in [
'happy', 'joy', 'love', 'excited', 'great', 'awesome',
'good', 'thanks', 'celebrate', 'dance', 'cheer', 'proud',
] if w in desc),
'negative': sum(1 for w in [
'sad', 'angry', 'sorry', 'disappoint', 'bad', 'wrong',
'hate', 'fear', 'bored', 'frustrat', 'rage', 'tired',
] if w in desc),
'question': sum(1 for w in [
'what', 'why', 'how', 'when', 'curious', 'wonder',
'think', 'question', 'unsure', 'confused',
] if w in desc),
'activity': sum(1 for w in [
'dance', 'move', 'action', 'play', 'energy', 'wiggle',
] if w in desc),
}
best = max(scores, key=scores.get)
return best if scores[best] > 0 else 'neutral'
def analyze_emotion(self, text: str) -> Tuple[str, str, float]:
"""Analyze emotion with your level calculation"""
text_lower = text.lower()
emotion_level = min(len(text) / 200, 1.0)
positive_words = ['开心', '快乐', '高兴', '喜欢', '爱', '谢谢', '感谢', '好', '棒', '完美', 'excited', 'happy', 'joy', 'love', 'thanks', 'good', 'great', 'awesome']
negative_words = ['伤心', '难过', '悲伤', '生气', '失望', '抱歉', '对不起', '不好', '坏', 'sad', 'angry', 'sorry', 'disappointed', 'bad', 'wrong', 'hate']
question_words = ['吗', '?', '?', '为什么', '怎么', '如何', 'what', 'why', 'how', 'when']
activity_words = ['跳舞', '舞蹈', '运动', '活动', '动起来', 'dance', 'move', 'action', 'play']
pos_count = sum(1 for word in positive_words if word in text_lower)
neg_count = sum(1 for word in negative_words if word in text_lower)
ques_count = sum(1 for word in question_words if word in text_lower)
act_count = sum(1 for word in activity_words if word in text_lower)
emoji_pos = ['😊', '😄', '😍', '👍', '🥰', '😎', '🎉', '❤️', '😂', '🤗']
emoji_neg = ['😢', '😭', '😡', '👎', '😔', '😞', '😤', '💔']
emoji_ques = ['🤔', '❓', '⁉️', '💭', '🧐', '🔍']
emoji_act = ['💃', '🕺', '🎵', '🎶', '⚽', '🏀', '🎮']
pos_count += sum(1 for emoji in emoji_pos if emoji in text)
neg_count += sum(1 for emoji in emoji_neg if emoji in text)
ques_count += sum(1 for emoji in emoji_ques if emoji in text)
act_count += sum(1 for emoji in emoji_act if emoji in text)
scores = {
'positive': pos_count,
'negative': neg_count,
'question': ques_count,
'activity': act_count
}
emotion_type = max(scores, key=scores.get)
total_score = sum(scores.values())
if total_score >= 3:
intensity = 'high'
elif total_score >= 1:
intensity = 'medium'
else:
intensity = 'low'
if emotion_type == 'positive':
emotion_level *= 1.2
elif emotion_type == 'negative':
emotion_level *= 0.8
return emotion_type, intensity, emotion_level
def _get_move(self, lib_tag: str, move_name: str):
"""Return a Move object from the correct library."""
lib = self.emotions_lib if lib_tag == 'emotions' else self.dances_lib
return lib.get(move_name)
def execute_recorded_move(self, move, initial_goto_duration: float = 1.0):
"""Execute a recorded move. `move` can be (lib_tag, move_name) or a move_name string."""
if isinstance(move, tuple) and len(move) == 2:
lib_tag, move_name = move
if self.debug:
print(f"🎬 Playing {lib_tag}/{move_name}")
mv = self._get_move(lib_tag, move_name)
else:
move_name = move
if self.debug:
print(f"🎬 Playing recorded move: {move_name}")
# Try dances library first, fall back to emotions
try:
mv = self.dances_lib.get(move_name)
except Exception:
mv = self.emotions_lib.get(move_name)
self.reachy.play_move(mv, initial_goto_duration=initial_goto_duration)
def _filter_gentle_emotions(self, available_moves):
"""Filter to only gentle emotions if gentle_mode is enabled."""
if not getattr(self, 'gentle_mode', False):
return available_moves
gentle_moves = [(lib, name) for lib, name in available_moves if name in _GENTLE_EMOTIONS]
if not gentle_moves:
return available_moves
return gentle_moves
def execute_emotion_move(self, emotion_type: str, intensity: str = 'medium'):
"""Execute a recorded move based on emotion category."""
available = self.emotion_to_moves.get(emotion_type, [])
if not available:
available = self.emotion_to_moves['neutral']
# Filter to gentle emotions if in gentle mode
available = self._filter_gentle_emotions(available)
import random
if intensity == 'high' and len(available) > 1:
lib_tag, move_name = available[-1]
elif intensity == 'low' and len(available) > 1:
lib_tag, move_name = available[0]
else:
lib_tag, move_name = random.choice(available)
duration_map = {'high': 0.8, 'medium': 1.0, 'low': 1.2}
if getattr(self, 'gentle_mode', False):
duration_map = {'high': 1.0, 'medium': 1.3, 'low': 1.5}
self.execute_recorded_move((lib_tag, move_name), duration_map.get(intensity, 1.0))
def _continuous_emotion_action(self, emotion_type: str, intensity: str):
"""Execute continuous emotion actions during speaking."""
available = self.emotion_to_moves.get(emotion_type, [])
# Filter to gentle emotions if in gentle mode
available = self._filter_gentle_emotions(available)
if available:
import random
while self.is_speaking_action:
lib_tag, move_name = random.choice(available)
duration_map = {'high': 0.8, 'medium': 1.0, 'low': 1.2}
if getattr(self, 'gentle_mode', False):
duration_map = {'high': 1.0, 'medium': 1.3, 'low': 1.5}
try:
self.execute_recorded_move((lib_tag, move_name), duration_map.get(intensity, 1.0))
except Exception as e:
if self.debug:
print(f"⚠️ Move error ({lib_tag}/{move_name}): {e}")
time.sleep(0.5)
else:
self._continuous_simple_action(emotion_type, intensity)
def _execute_simple_action(self, emotion_type: str, intensity: str):
duration_map = {'high': 1.5, 'medium': 2.0, 'low': 2.5}
duration = duration_map.get(intensity, 2.0)
if emotion_type == 'positive':
self.simple_actions['nod'](duration)
elif emotion_type == 'negative':
self.simple_actions['look_sad'](duration)
elif emotion_type == 'question':
self.simple_actions['look_curious'](duration)
elif emotion_type == 'activity':
self.simple_actions['excited_wiggle'](duration)
else:
self.simple_actions['nod'](duration)
def _continuous_simple_action(self, emotion_type: str, intensity: str):
"""Execute continuous simple actions during speaking with variety and combined movements"""
pause_map = {'high': 1.0, 'medium': 1.5, 'low': 2.0}
pause = pause_map.get(intensity, 1.5)
# Enhanced action sequences with combined head/antennas + blink + body yaw
combined_action_sequences = {
'positive': [
self._combined_nod_blink,
self._combined_shake_blink_yaw,
self._combined_wiggle_blink,
self._combined_happy_tilt_blink_yaw,
self._combined_excited_sequence
],
'negative': [
self._combined_sad_blink,
self._combined_thoughtful_blink_yaw,
self._combined_slow_sequence,
self._combined_negative_gesture
],
'question': [
self._combined_curious_blink,
self._combined_thoughtful_blink_yaw,
self._combined_question_sequence,
self._combined_nod_blink
],
'activity': [
self._combined_wiggle_blink,
self._combined_shake_blink_yaw,
self._combined_activity_sequence,
self._combined_happy_tilt_blink_yaw
],
'neutral': [
self._combined_nod_blink,
self._combined_thoughtful_blink_yaw,
self._combined_neutral_sequence,
self._combined_curious_blink
]
}
actions = combined_action_sequences.get(emotion_type, [self._combined_nod_blink])
action_index = 0
while self.is_speaking_action:
actions[action_index % len(actions)]()
action_index += 1
time.sleep(pause)
def speak_with_expression(self, text: str, emotion: str = 'neutral', intensity: str = 'medium', emotion_level: float = 0.5):
"""Speak with Edge-TTS and your lip-sync"""
if not text.strip():
return
if self.debug:
print(f"🗣️ Speaking with {emotion} emotion (level: {emotion_level:.2f})")
word_count = len(text.split())
estimated_duration = max(1.0, word_count / 2.5)
self.lip_sync.start_lip_sync(text, emotion_level)
self.is_speaking_action = True
action_thread = threading.Thread(
target=self._continuous_emotion_action,
args=(emotion, intensity),
daemon=True
)
action_thread.start()
self.tts_engine.speak_with_emotion(text, emotion)
self.is_speaking_action = False
self.lip_sync.stop_lip_sync()
async def speak_with_expression_async(self, text: str, emotion: str = 'neutral', intensity: str = 'medium', emotion_level: float = 0.5):
"""Async version: Speak with Edge-TTS and your lip-sync"""
if not text.strip():
return
if self.debug:
print(f"🗣️ Async speaking with {emotion} emotion (level: {emotion_level:.2f})")
self.lip_sync.start_lip_sync(text, emotion_level)
self.is_speaking_action = True
action_thread = threading.Thread(
target=self._continuous_emotion_action,
args=(emotion, intensity),
daemon=True
)
action_thread.start()
# Use async TTS without creating new event loop
await self.tts_engine.speak_with_emotion_async(text, emotion)
self.is_speaking_action = False
self.lip_sync.stop_lip_sync()
async def speak_with_expression_parallel(self, text: str, emotion: str = 'neutral', intensity: str = 'medium', emotion_level: float = 0.5):
"""Parallel version: Start robot emotions immediately, run TTS concurrently"""
if not text.strip():
return
import asyncio
if self.debug:
print(f"🤖 PARALLEL: Starting robot emotions immediately for {emotion} (level: {emotion_level:.2f})")
# Start lip sync immediately
self.lip_sync.start_lip_sync(text, emotion_level)
# Start continuous robot emotions in background thread (immediately)
self.is_speaking_action = True
action_thread = threading.Thread(
target=self._continuous_emotion_action,
args=(emotion, intensity),
daemon=True
)
action_thread.start()
# Execute recorded move first (before TTS starts) for immediate visual feedback
try:
available_moves = self.emotion_to_moves.get(emotion, [])
if available_moves:
import random
move_name = random.choice(available_moves)
duration_map = {'high': 0.8, 'medium': 1.0, 'low': 1.2}
self.execute_recorded_move(move_name, duration_map.get(intensity, 1.0))
except Exception as e:
if self.debug:
print(f"⚠️ Quick move execution error: {e}")
# Start TTS async task
tts_task = asyncio.create_task(
self.tts_engine.speak_with_emotion_async(text, emotion)
)
# While TTS is playing, continue robot emotions
try:
# Wait for TTS to complete
await tts_task
except Exception as e:
print(f"⚠️ TTS async error in parallel mode: {e}")
# Stop after TTS finishes
self.is_speaking_action = False
self.lip_sync.stop_lip_sync()
# Final emotion movement after TTS
try:
if available_moves:
import random
move_name = random.choice(available_moves)
self.execute_recorded_move(move_name, 0.8) # Quick final movement
except Exception:
pass
def _simple_nod(self, duration: float = 2.0):
amplitude = 0.6
cycles = int(duration * 2)
for _ in range(cycles):
self.reachy.goto_target(head=_create_head_pose(pitch=20*amplitude, degrees=True), duration=0.25)
time.sleep(0.1)
self.reachy.goto_target(head=_create_head_pose(pitch=-10*amplitude, degrees=True), duration=0.25)
time.sleep(0.1)
self.reachy.goto_target(head=_create_head_pose(), duration=0.5)
def _simple_nod_once(self):
"""Single nod cycle"""
try:
amplitude = 0.6
self.reachy.goto_target(head=_create_head_pose(pitch=20*amplitude, degrees=True), duration=0.25)
time.sleep(0.1)
self.reachy.goto_target(head=_create_head_pose(pitch=-10*amplitude, degrees=True), duration=0.25)
time.sleep(0.1)
self.reachy.goto_target(head=_create_head_pose(), duration=0.5)
except Exception as e:
print(f"⚠️ Nod action not supported: {e}")
def _simple_look_sad_once(self):
"""Single sad look"""
try:
self.reachy.goto_target(head=_create_head_pose(pitch=30, degrees=True), duration=0.5)
time.sleep(0.5)
self.reachy.goto_target(head=_create_head_pose(), duration=0.5)
except Exception as e:
print(f"⚠️ Sad look action not supported: {e}")
def _simple_look_curious_once(self):
"""Single curious look"""
try:
amplitude = 0.8
self.reachy.goto_target(head=_create_head_pose(yaw=25*amplitude, pitch=10*amplitude, degrees=True), duration=0.5)
time.sleep(0.5)
self.reachy.goto_target(head=_create_head_pose(yaw=-25*amplitude, pitch=10*amplitude, degrees=True), duration=0.5)
time.sleep(0.5)
self.reachy.goto_target(head=_create_head_pose(), duration=0.5)
except Exception as e:
print(f"⚠️ Curious look action not supported: {e}")
def _simple_excited_wiggle_once(self):
"""Single excited wiggle"""
try:
left_val = 0.7
right_val = -0.7
self.reachy.goto_target(antennas=[left_val, right_val], duration=0.15)
time.sleep(0.1)
left_val = -0.7
right_val = 0.7
self.reachy.goto_target(antennas=[left_val, right_val], duration=0.15)
time.sleep(0.1)
self.reachy.goto_target(antennas=[0, 0], duration=0.3)
except Exception as e:
print(f"⚠️ Excited wiggle action not supported: {e}")
def _simple_shake_once(self):
"""Single shake cycle"""
try:
amplitude = 0.7
self.reachy.goto_target(head=_create_head_pose(yaw=30*amplitude, degrees=True), duration=0.3)
time.sleep(0.1)
self.reachy.goto_target(head=_create_head_pose(yaw=-30*amplitude, degrees=True), duration=0.3)
time.sleep(0.1)
self.reachy.goto_target(head=_create_head_pose(), duration=0.5)
except Exception as e:
print(f"⚠️ Shake action not supported: {e}")
def _simple_thoughtful_tilt_once(self):
"""Single thoughtful tilt"""
try:
amplitude = 0.6
self.reachy.goto_target(head=_create_head_pose(roll=15*amplitude, degrees=True), duration=0.4)
time.sleep(0.4)
self.reachy.goto_target(head=_create_head_pose(roll=-15*amplitude, degrees=True), duration=0.4)
time.sleep(0.4)
self.reachy.goto_target(head=_create_head_pose(), duration=0.5)
except Exception as e:
print(f"⚠️ Thoughtful tilt action not supported: {e}")
def _simple_blink_once(self):
"""Single blink"""
try:
# Simulate blink by closing and opening eyes
if hasattr(self.reachy, 'head'):
self.reachy.head.r_eye.goal_position = 0.1
self.reachy.head.l_eye.goal_position = 0.1
time.sleep(0.2)
self.reachy.head.r_eye.goal_position = 0.5
self.reachy.head.l_eye.goal_position = 0.5
time.sleep(0.1)
except Exception as e:
print(f"⚠️ Blink action not supported: {e}")
def _simple_happy_tilt_once(self):
"""Single happy head tilt"""
try:
# Happy tilt - slight backward tilt with positive yaw
self.reachy.goto_target(head=_create_head_pose(pitch=-15, yaw=10, degrees=True), duration=0.4)
time.sleep(0.4)
self.reachy.goto_target(head=_create_head_pose(), duration=0.4)
except Exception as e:
print(f"⚠️ Happy tilt action not supported: {e}")
def _simple_slow_shake_once(self):
"""Single slow shake"""
try:
amplitude = 0.5
self.reachy.goto_target(head=_create_head_pose(yaw=20*amplitude, degrees=True), duration=0.5)
time.sleep(0.3)
self.reachy.goto_target(head=_create_head_pose(yaw=-20*amplitude, degrees=True), duration=0.5)
time.sleep(0.3)
self.reachy.goto_target(head=_create_head_pose(), duration=0.5)
except Exception as e:
print(f"⚠️ Slow shake action not supported: {e}")
# Combined action methods with synchronized blinking and body yaw
def _combined_nod_blink(self):
"""Combined nod with blink"""
try:
# Start blink
if hasattr(self.reachy, 'head'):
self.reachy.head.r_eye.goal_position = 0.1
self.reachy.head.l_eye.goal_position = 0.1
# Nod movement
amplitude = 0.6
self.reachy.goto_target(head=_create_head_pose(pitch=20*amplitude, degrees=True), duration=0.25)
time.sleep(0.1)
# Finish blink during nod
if hasattr(self.reachy, 'head'):
self.reachy.head.r_eye.goal_position = 0.5
self.reachy.head.l_eye.goal_position = 0.5
self.reachy.goto_target(head=_create_head_pose(pitch=-10*amplitude, degrees=True), duration=0.25)
time.sleep(0.1)
self.reachy.goto_target(head=_create_head_pose(), duration=0.5)
except Exception as e:
print(f"⚠️ Combined nod-blink action not supported: {e}")
def _combined_shake_blink_yaw(self):
"""Combined shake with blink and body yaw"""
try:
# Start blink and body yaw
if hasattr(self.reachy, 'head'):
self.reachy.head.r_eye.goal_position = 0.1
self.reachy.head.l_eye.goal_position = 0.1
self.reachy.set_target_body_yaw(np.deg2rad(15))
# Shake movement
amplitude = 0.7
self.reachy.goto_target(head=_create_head_pose(yaw=30*amplitude, degrees=True), duration=0.3)
time.sleep(0.1)
# Mid blink
if hasattr(self.reachy, 'head'):
self.reachy.head.r_eye.goal_position = 0.5
self.reachy.head.l_eye.goal_position = 0.5