File size: 8,504 Bytes
506256a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Witz-Bot β€” Reachy Mini Joke Bot

SchlΓ€ft per Default. Wacht bei GerΓ€uschen auf, gΓ€hnt, streckt sich,
schaut sich um, erzΓ€hlt einen deutschen Witz und lacht β€” dann schlΓ€ft er wieder.

Voraussetzungen (einmalig installieren):
    pip install edge-tts miniaudio
"""

import asyncio
import time
import random

import miniaudio
import numpy as np
import edge_tts

from reachy_mini import ReachyMini
from reachy_mini.utils import create_head_pose

try:
    from reachy_mini.motion.recorded_move import RecordedMoves
    _emotions = RecordedMoves("pollen-robotics/reachy-mini-emotions-library")
except Exception:
    _emotions = None

# ── Konfiguration ─────────────────────────────────────────────────────────────

TTS_VOICE      = "de-DE-KatjaNeural"   # Deutsche Stimme (Microsoft Neural TTS)
AUDIO_RATE     = 16_000                 # Hz β€” Roboter-Lautsprecher-Samplerate
WAKE_THRESHOLD = 4                      # Aufeinanderfolgende Erkennungen zum Aufwachen
POLL_INTERVAL  = 0.15                   # Sekunden zwischen Mikrofon-Polls

# Antennen-Positionen in Radiant [rechts, links]
ANT_NORMAL = [-0.1745,  0.1745]   # β‰ˆ Β±10Β°, Standardposition
ANT_DROOP  = [-2.2,     2.2   ]   # β‰ˆ Β±126Β°, hΓ€ngend (mΓΌde)
ANT_ALERT  = [-0.4,     0.4   ]   # β‰ˆ Β±23Β°, aufmerksam

JOKES: list[tuple[str, str]] = [
    ("Warum kΓΆnnen Geister so schlecht lΓΌgen?",
     "Weil man durch sie hindurchsehen kann!"),
    ("Wie nennt man einen Bumerang, der nicht zurΓΌckkommt?",
     "Einen Stock!"),
    ("Was macht ein Pirat am Computer?",
     "Er drΓΌckt die Enter-Taste!"),
    ("Warum gehen Skelette nicht in den Krieg?",
     "Weil sie keinen Mumm haben!"),
    ("Warum ist die Sechs so traurig?",
     "Weil Sieben Acht Neun!"),
    ("Wie heißt der Bruder von Robocop?",
     "Robocup!"),
    ("Was sagt ein Vampir, wenn er telefoniert?",
     "Auf Wieder-beißen! Γ„h … ich meine: Auf WiederhΓΆren!"),
    ("Was ist der Unterschied zwischen einem Snowboarder und einem Schachspieler?",
     "Einer macht das Brett β€” der andere brettert!"),
    ("Warum macht ein Besen so gute Arbeit?",
     "Er ist eben gut im Kehren!"),
    ("Was sagt ein Hai, wenn er gegen etwas stâßt?",
     "Haihai!"),
    ("Was ist groß, grün und geht rauf und runter?",
     "Ein Kaktus im Fahrstuhl!"),
    ("Treffen sich zwei JΓ€ger. Beide tot.",
     "Nein, Spaß β€” das ist kein Witz, das ist TragΓΆdie!"),
]


# ── TTS ───────────────────────────────────────────────────────────────────────

async def _fetch_mp3(text: str) -> bytes:
    chunks: list[bytes] = []
    async for chunk in edge_tts.Communicate(text, TTS_VOICE).stream():
        if chunk["type"] == "audio":
            chunks.append(chunk["data"])
    return b"".join(chunks)


def synth(text: str) -> np.ndarray:
    """Text β†’ float32-Array (N, 1) bei AUDIO_RATE Hz fΓΌr den Roboter-Lautsprecher."""
    mp3_bytes = asyncio.run(_fetch_mp3(text))
    decoded = miniaudio.decode(
        mp3_bytes,
        nchannels=1,
        sample_rate=AUDIO_RATE,
        output_format=miniaudio.SampleFormat.FLOAT32,
    )
    samples = np.frombuffer(decoded.samples, dtype=np.float32).copy()
    return samples.reshape(-1, 1)


def play(mini: ReachyMini, samples: np.ndarray) -> None:
    """Audio zum Roboter-Lautsprecher schicken und auf Ende warten."""
    mini.media.push_audio_sample(samples)
    time.sleep(len(samples) / AUDIO_RATE + 0.3)


# ── Gestiken ──────────────────────────────────────────────────────────────────

def do_yawn(mini: ReachyMini) -> None:
    """GΓ€hnen: Kopf lehnt zurΓΌck, Antennen hΓ€ngen schlaff, kehrt zurΓΌck."""
    # Mund auf β€” Kopf nach hinten kippen
    mini.goto_target(
        create_head_pose(pitch=-22, degrees=True),
        antennas=ANT_DROOP,
        duration=1.5,
    )
    time.sleep(2.0)
    # Aufrecht
    mini.goto_target(create_head_pose(), antennas=ANT_NORMAL, duration=1.0)
    time.sleep(1.1)


def do_stretch(mini: ReachyMini) -> None:
    """Strecken: KΓΆrper dreht sich links und rechts (Hals/WirbelsΓ€ule lockern)."""
    mini.goto_target(create_head_pose(), body_yaw=np.deg2rad(40), duration=1.5)
    time.sleep(1.6)
    mini.goto_target(create_head_pose(), body_yaw=np.deg2rad(-40), duration=2.0)
    time.sleep(2.1)
    mini.goto_target(create_head_pose(), body_yaw=0.0, duration=1.0)
    time.sleep(1.1)


def look_around(mini: ReachyMini) -> None:
    """Schaut sich neugierig um: links β†’ rechts β†’ Mitte."""
    mini.goto_target(
        create_head_pose(yaw=50, degrees=True),
        antennas=ANT_ALERT,
        duration=0.8,
    )
    time.sleep(1.0)
    mini.goto_target(create_head_pose(yaw=-50, degrees=True), duration=1.2)
    time.sleep(1.3)
    mini.goto_target(create_head_pose(), antennas=ANT_NORMAL, duration=0.6)
    time.sleep(0.7)


def do_laugh(mini: ReachyMini) -> None:
    """Lachen: Emotions-Library wenn verfΓΌgbar, sonst schnelles Kopfnicken."""
    if _emotions is not None:
        try:
            mini.play_move(_emotions.get("happy"), initial_goto_duration=0.4)
            return
        except Exception:
            pass

    # Fallback: Kopfnicken + Antennen-Wackeln
    for i in range(7):
        pitch = 20 if i % 2 == 0 else -5
        ant   = ANT_ALERT if i % 2 == 0 else ANT_NORMAL
        mini.goto_target(
            create_head_pose(pitch=pitch, degrees=True),
            antennas=ant,
            duration=0.18,
        )
        time.sleep(0.2)
    mini.goto_target(create_head_pose(), antennas=ANT_NORMAL, duration=0.5)
    time.sleep(0.6)


# ── Schlaferkennung ───────────────────────────────────────────────────────────

def wait_for_sound(mini: ReachyMini) -> None:
    """Blockiert, bis Sprache/GerΓ€usch zuverlΓ€ssig erkannt wird."""
    print("  Warte auf GerΓ€usch …", end="", flush=True)
    consecutive = 0
    while consecutive < WAKE_THRESHOLD:
        _, is_speech = mini.media.get_DoA()
        if is_speech:
            consecutive += 1
        else:
            consecutive = max(0, consecutive - 1)
        time.sleep(POLL_INTERVAL)
    print(" GerΓ€usch erkannt!")


# ── Hauptschleife ─────────────────────────────────────────────────────────────

def main() -> None:
    print("Witz-Bot startet …")
    print("  Synthetisiere Witze (benΓΆtigt Internet) …")

    jokes_audio: list[tuple[np.ndarray, np.ndarray]] = []
    for i, (setup, punchline) in enumerate(JOKES, 1):
        print(f"    [{i}/{len(JOKES)}] {setup[:50]}…")
        jokes_audio.append((synth(setup), synth(punchline)))

    print(f"  {len(jokes_audio)} Witze bereit. Verbinde mit Roboter …")

    with ReachyMini(media_backend="default") as mini:
        mini.media.start_recording()
        mini.media.start_playing()
        print("  Verbunden! DrΓΌcke Strg+C zum Beenden.\n")

        try:
            while True:
                print("Schlafen …")
                mini.goto_sleep()

                wait_for_sound(mini)

                mini.wake_up()

                do_yawn(mini)
                do_stretch(mini)
                look_around(mini)

                idx = random.randrange(len(JOKES))
                setup_text, punchline_text = JOKES[idx]
                setup_audio, punchline_audio = jokes_audio[idx]

                print(f"\nWitz #{idx + 1}: {setup_text}")
                play(mini, setup_audio)

                time.sleep(1.5)  # dramatische Pause

                print(f"          β†’ {punchline_text}\n")
                play(mini, punchline_audio)

                time.sleep(0.5)
                do_laugh(mini)
                time.sleep(1.0)

        except KeyboardInterrupt:
            print("\nBeende Witz-Bot …")
            mini.goto_sleep()
        finally:
            mini.media.stop_recording()
            mini.media.stop_playing()
            print("TschΓΌss!")


if __name__ == "__main__":
    main()