|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from collections.abc import Coroutine |
| 5 | +from typing import Any, Callable |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import numpy.typing as npt |
| 9 | +import sounddevice as sd |
| 10 | +from textual import events |
| 11 | +from textual.app import App, ComposeResult |
| 12 | +from textual.containers import Container, Horizontal |
| 13 | +from textual.reactive import reactive |
| 14 | +from textual.widgets import RichLog, Static |
| 15 | +from typing_extensions import override |
| 16 | + |
| 17 | +CHUNK_LENGTH_S = 0.05 # 50ms |
| 18 | +SAMPLE_RATE = 24000 |
| 19 | +FORMAT = np.int16 |
| 20 | +CHANNELS = 1 |
| 21 | + |
| 22 | + |
| 23 | +class Header(Static): |
| 24 | + """A header widget.""" |
| 25 | + |
| 26 | + @override |
| 27 | + def render(self) -> str: |
| 28 | + return "Realtime Demo" |
| 29 | + |
| 30 | + |
| 31 | +class AudioStatusIndicator(Static): |
| 32 | + """A widget that shows the current audio recording status.""" |
| 33 | + |
| 34 | + is_recording = reactive(False) |
| 35 | + |
| 36 | + @override |
| 37 | + def render(self) -> str: |
| 38 | + status = ( |
| 39 | + "🔴 Conversation started." |
| 40 | + if self.is_recording |
| 41 | + else "⚪ Press SPACE to start the conversation (q to quit)" |
| 42 | + ) |
| 43 | + return status |
| 44 | + |
| 45 | + |
| 46 | +class AppUI(App[None]): |
| 47 | + CSS = """ |
| 48 | + Screen { |
| 49 | + background: #1a1b26; /* Dark blue-grey background */ |
| 50 | + } |
| 51 | +
|
| 52 | + Container { |
| 53 | + border: double rgb(91, 164, 91); |
| 54 | + } |
| 55 | +
|
| 56 | + #input-container { |
| 57 | + height: 5; /* Explicit height for input container */ |
| 58 | + margin: 1 1; |
| 59 | + padding: 1 2; |
| 60 | + } |
| 61 | +
|
| 62 | + #bottom-pane { |
| 63 | + width: 100%; |
| 64 | + height: 82%; /* Reduced to make room for session display */ |
| 65 | + border: round rgb(205, 133, 63); |
| 66 | + } |
| 67 | +
|
| 68 | + #status-indicator { |
| 69 | + height: 3; |
| 70 | + content-align: center middle; |
| 71 | + background: #2a2b36; |
| 72 | + border: solid rgb(91, 164, 91); |
| 73 | + margin: 1 1; |
| 74 | + } |
| 75 | +
|
| 76 | + #session-display { |
| 77 | + height: 3; |
| 78 | + content-align: center middle; |
| 79 | + background: #2a2b36; |
| 80 | + border: solid rgb(91, 164, 91); |
| 81 | + margin: 1 1; |
| 82 | + } |
| 83 | +
|
| 84 | + #transcripts { |
| 85 | + width: 50%; |
| 86 | + height: 100%; |
| 87 | + border-right: solid rgb(91, 164, 91); |
| 88 | + } |
| 89 | +
|
| 90 | + #transcripts-header { |
| 91 | + height: 2; |
| 92 | + background: #2a2b36; |
| 93 | + content-align: center middle; |
| 94 | + border-bottom: solid rgb(91, 164, 91); |
| 95 | + } |
| 96 | +
|
| 97 | + #transcripts-content { |
| 98 | + height: 100%; |
| 99 | + } |
| 100 | +
|
| 101 | + #event-log { |
| 102 | + width: 50%; |
| 103 | + height: 100%; |
| 104 | + } |
| 105 | +
|
| 106 | + #event-log-header { |
| 107 | + height: 2; |
| 108 | + background: #2a2b36; |
| 109 | + content-align: center middle; |
| 110 | + border-bottom: solid rgb(91, 164, 91); |
| 111 | + } |
| 112 | +
|
| 113 | + #event-log-content { |
| 114 | + height: 100%; |
| 115 | + } |
| 116 | +
|
| 117 | + Static { |
| 118 | + color: white; |
| 119 | + } |
| 120 | + """ |
| 121 | + |
| 122 | + should_send_audio: asyncio.Event |
| 123 | + connected: asyncio.Event |
| 124 | + last_audio_item_id: str | None |
| 125 | + audio_callback: Callable[[bytes], Coroutine[Any, Any, None]] | None |
| 126 | + |
| 127 | + def __init__(self) -> None: |
| 128 | + super().__init__() |
| 129 | + self.audio_player = sd.OutputStream( |
| 130 | + samplerate=SAMPLE_RATE, |
| 131 | + channels=CHANNELS, |
| 132 | + dtype=FORMAT, |
| 133 | + ) |
| 134 | + self.should_send_audio = asyncio.Event() |
| 135 | + self.connected = asyncio.Event() |
| 136 | + self.audio_callback = None |
| 137 | + |
| 138 | + @override |
| 139 | + def compose(self) -> ComposeResult: |
| 140 | + """Create child widgets for the app.""" |
| 141 | + with Container(): |
| 142 | + yield Header(id="session-display") |
| 143 | + yield AudioStatusIndicator(id="status-indicator") |
| 144 | + with Container(id="bottom-pane"): |
| 145 | + with Horizontal(): |
| 146 | + with Container(id="transcripts"): |
| 147 | + yield Static("Conversation transcript", id="transcripts-header") |
| 148 | + yield RichLog( |
| 149 | + id="transcripts-content", wrap=True, highlight=True, markup=True |
| 150 | + ) |
| 151 | + with Container(id="event-log"): |
| 152 | + yield Static("Raw event log", id="event-log-header") |
| 153 | + yield RichLog( |
| 154 | + id="event-log-content", wrap=True, highlight=True, markup=True |
| 155 | + ) |
| 156 | + |
| 157 | + def set_is_connected(self, is_connected: bool) -> None: |
| 158 | + self.connected.set() if is_connected else self.connected.clear() |
| 159 | + |
| 160 | + def set_audio_callback(self, callback: Callable[[bytes], Coroutine[Any, Any, None]]) -> None: |
| 161 | + """Set a callback function to be called when audio is recorded.""" |
| 162 | + self.audio_callback = callback |
| 163 | + |
| 164 | + # High-level methods for UI operations |
| 165 | + def set_header_text(self, text: str) -> None: |
| 166 | + """Update the header text.""" |
| 167 | + header = self.query_one("#session-display", Header) |
| 168 | + header.update(text) |
| 169 | + |
| 170 | + def set_recording_status(self, is_recording: bool) -> None: |
| 171 | + """Set the recording status indicator.""" |
| 172 | + status_indicator = self.query_one(AudioStatusIndicator) |
| 173 | + status_indicator.is_recording = is_recording |
| 174 | + |
| 175 | + def log_message(self, message: str) -> None: |
| 176 | + """Add a message to the event log.""" |
| 177 | + try: |
| 178 | + log_pane = self.query_one("#event-log-content", RichLog) |
| 179 | + log_pane.write(message) |
| 180 | + except Exception: |
| 181 | + # Handle the case where the widget might not be available |
| 182 | + pass |
| 183 | + |
| 184 | + def add_transcript(self, message: str) -> None: |
| 185 | + """Add a transcript message to the transcripts panel.""" |
| 186 | + try: |
| 187 | + transcript_pane = self.query_one("#transcripts-content", RichLog) |
| 188 | + transcript_pane.write(message) |
| 189 | + except Exception: |
| 190 | + # Handle the case where the widget might not be available |
| 191 | + pass |
| 192 | + |
| 193 | + def play_audio(self, audio_data: npt.NDArray[np.int16]) -> None: |
| 194 | + """Play audio data through the audio player.""" |
| 195 | + try: |
| 196 | + self.audio_player.write(audio_data) |
| 197 | + except Exception as e: |
| 198 | + self.log_message(f"Audio play error: {e}") |
| 199 | + |
| 200 | + async def on_mount(self) -> None: |
| 201 | + """Set up audio player and start the audio capture worker.""" |
| 202 | + self.audio_player.start() |
| 203 | + self.run_worker(self.capture_audio()) |
| 204 | + |
| 205 | + async def capture_audio(self) -> None: |
| 206 | + """Capture audio from the microphone and send to the session.""" |
| 207 | + # Wait for connection to be established |
| 208 | + await self.connected.wait() |
| 209 | + |
| 210 | + # Set up audio input stream |
| 211 | + stream = sd.InputStream( |
| 212 | + channels=CHANNELS, |
| 213 | + samplerate=SAMPLE_RATE, |
| 214 | + dtype=FORMAT, |
| 215 | + ) |
| 216 | + |
| 217 | + try: |
| 218 | + # Wait for user to press spacebar to start |
| 219 | + await self.should_send_audio.wait() |
| 220 | + |
| 221 | + stream.start() |
| 222 | + self.set_recording_status(True) |
| 223 | + self.log_message("Recording started - speak to the agent") |
| 224 | + |
| 225 | + # Buffer size in samples |
| 226 | + read_size = int(SAMPLE_RATE * CHUNK_LENGTH_S) |
| 227 | + |
| 228 | + while True: |
| 229 | + # Check if there's enough data to read |
| 230 | + if stream.read_available < read_size: |
| 231 | + await asyncio.sleep(0.01) # Small sleep to avoid CPU hogging |
| 232 | + continue |
| 233 | + |
| 234 | + # Read audio data |
| 235 | + data, _ = stream.read(read_size) |
| 236 | + |
| 237 | + # Convert numpy array to bytes |
| 238 | + audio_bytes = data.tobytes() |
| 239 | + |
| 240 | + # Call audio callback if set |
| 241 | + if self.audio_callback: |
| 242 | + try: |
| 243 | + await self.audio_callback(audio_bytes) |
| 244 | + except Exception as e: |
| 245 | + self.log_message(f"Audio callback error: {e}") |
| 246 | + |
| 247 | + # Yield control back to event loop |
| 248 | + await asyncio.sleep(0) |
| 249 | + |
| 250 | + except Exception as e: |
| 251 | + self.log_message(f"Audio capture error: {e}") |
| 252 | + finally: |
| 253 | + if stream.active: |
| 254 | + stream.stop() |
| 255 | + stream.close() |
| 256 | + |
| 257 | + async def on_key(self, event: events.Key) -> None: |
| 258 | + """Handle key press events.""" |
| 259 | + # add the keypress to the log |
| 260 | + self.log_message(f"Key pressed: {event.key}") |
| 261 | + |
| 262 | + if event.key == "q": |
| 263 | + self.audio_player.stop() |
| 264 | + self.audio_player.close() |
| 265 | + self.exit() |
| 266 | + return |
| 267 | + |
| 268 | + if event.key == "space": # Spacebar |
| 269 | + if not self.should_send_audio.is_set(): |
| 270 | + self.should_send_audio.set() |
| 271 | + self.set_recording_status(True) |
0 commit comments