-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathpush_to_talk_app.py
executable file
·281 lines (227 loc) · 8.92 KB
/
push_to_talk_app.py
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
#!/usr/bin/env uv run
####################################################################
# Sample TUI app with a push to talk interface to the Realtime API #
# If you have `uv` installed and the `OPENAI_API_KEY` #
# environment variable set, you can run this example with just #
# #
# `./examples/realtime/push_to_talk_app.py` #
####################################################################
#
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "textual",
# "numpy",
# "pyaudio",
# "pydub",
# "sounddevice",
# "openai[realtime]",
# ]
#
# [tool.uv.sources]
# openai = { path = "../../", editable = true }
# ///
from __future__ import annotations
import base64
import asyncio
from typing import Any, cast
from typing_extensions import override
from textual import events
from audio_util import CHANNELS, SAMPLE_RATE, AudioPlayerAsync
from textual.app import App, ComposeResult
from textual.widgets import Button, Static, RichLog
from textual.reactive import reactive
from textual.containers import Container
from openai import AsyncOpenAI
from openai.types.beta.realtime.session import Session
from openai.resources.beta.realtime.realtime import AsyncRealtimeConnection
class SessionDisplay(Static):
"""A widget that shows the current session ID."""
session_id = reactive("")
@override
def render(self) -> str:
return f"Session ID: {self.session_id}" if self.session_id else "Connecting..."
class AudioStatusIndicator(Static):
"""A widget that shows the current audio recording status."""
is_recording = reactive(False)
@override
def render(self) -> str:
status = (
"🔴 Recording... (Press K to stop)" if self.is_recording else "⚪ Press K to start recording (Q to quit)"
)
return status
class RealtimeApp(App[None]):
CSS = """
Screen {
background: #1a1b26; /* Dark blue-grey background */
}
Container {
border: double rgb(91, 164, 91);
}
Horizontal {
width: 100%;
}
#input-container {
height: 5; /* Explicit height for input container */
margin: 1 1;
padding: 1 2;
}
Input {
width: 80%;
height: 3; /* Explicit height for input */
}
Button {
width: 20%;
height: 3; /* Explicit height for button */
}
#bottom-pane {
width: 100%;
height: 82%; /* Reduced to make room for session display */
border: round rgb(205, 133, 63);
content-align: center middle;
}
#status-indicator {
height: 3;
content-align: center middle;
background: #2a2b36;
border: solid rgb(91, 164, 91);
margin: 1 1;
}
#session-display {
height: 3;
content-align: center middle;
background: #2a2b36;
border: solid rgb(91, 164, 91);
margin: 1 1;
}
Static {
color: white;
}
"""
client: AsyncOpenAI
should_send_audio: asyncio.Event
audio_player: AudioPlayerAsync
last_audio_item_id: str | None
connection: AsyncRealtimeConnection | None
session: Session | None
connected: asyncio.Event
def __init__(self) -> None:
super().__init__()
self.connection = None
self.session = None
self.client = AsyncOpenAI()
self.audio_player = AudioPlayerAsync()
self.last_audio_item_id = None
self.should_send_audio = asyncio.Event()
self.connected = asyncio.Event()
@override
def compose(self) -> ComposeResult:
"""Create child widgets for the app."""
with Container():
yield SessionDisplay(id="session-display")
yield AudioStatusIndicator(id="status-indicator")
yield RichLog(id="bottom-pane", wrap=True, highlight=True, markup=True)
async def on_mount(self) -> None:
self.run_worker(self.handle_realtime_connection())
self.run_worker(self.send_mic_audio())
async def handle_realtime_connection(self) -> None:
async with self.client.beta.realtime.connect(model="gpt-4o-realtime-preview") as conn:
self.connection = conn
self.connected.set()
# note: this is the default and can be omitted
# if you want to manually handle VAD yourself, then set `'turn_detection': None`
await conn.session.update(session={"turn_detection": {"type": "server_vad"}})
acc_items: dict[str, Any] = {}
async for event in conn:
if event.type == "session.created":
self.session = event.session
session_display = self.query_one(SessionDisplay)
assert event.session.id is not None
session_display.session_id = event.session.id
continue
if event.type == "session.updated":
self.session = event.session
continue
if event.type == "response.audio.delta":
if event.item_id != self.last_audio_item_id:
self.audio_player.reset_frame_count()
self.last_audio_item_id = event.item_id
bytes_data = base64.b64decode(event.delta)
self.audio_player.add_data(bytes_data)
continue
if event.type == "response.audio_transcript.delta":
try:
text = acc_items[event.item_id]
except KeyError:
acc_items[event.item_id] = event.delta
else:
acc_items[event.item_id] = text + event.delta
# Clear and update the entire content because RichLog otherwise treats each delta as a new line
bottom_pane = self.query_one("#bottom-pane", RichLog)
bottom_pane.clear()
bottom_pane.write(acc_items[event.item_id])
continue
async def _get_connection(self) -> AsyncRealtimeConnection:
await self.connected.wait()
assert self.connection is not None
return self.connection
async def send_mic_audio(self) -> None:
import sounddevice as sd # type: ignore
sent_audio = False
device_info = sd.query_devices()
print(device_info)
read_size = int(SAMPLE_RATE * 0.02)
stream = sd.InputStream(
channels=CHANNELS,
samplerate=SAMPLE_RATE,
dtype="int16",
)
stream.start()
status_indicator = self.query_one(AudioStatusIndicator)
try:
while True:
if stream.read_available < read_size:
await asyncio.sleep(0)
continue
await self.should_send_audio.wait()
status_indicator.is_recording = True
data, _ = stream.read(read_size)
connection = await self._get_connection()
if not sent_audio:
asyncio.create_task(connection.send({"type": "response.cancel"}))
sent_audio = True
await connection.input_audio_buffer.append(audio=base64.b64encode(cast(Any, data)).decode("utf-8"))
await asyncio.sleep(0)
except KeyboardInterrupt:
pass
finally:
stream.stop()
stream.close()
async def on_key(self, event: events.Key) -> None:
"""Handle key press events."""
if event.key == "enter":
self.query_one(Button).press()
return
if event.key == "q":
self.exit()
return
if event.key == "k":
status_indicator = self.query_one(AudioStatusIndicator)
if status_indicator.is_recording:
self.should_send_audio.clear()
status_indicator.is_recording = False
if self.session and self.session.turn_detection is None:
# The default in the API is that the model will automatically detect when the user has
# stopped talking and then start responding itself.
#
# However if we're in manual `turn_detection` mode then we need to
# manually tell the model to commit the audio buffer and start responding.
conn = await self._get_connection()
await conn.input_audio_buffer.commit()
await conn.response.create()
else:
self.should_send_audio.set()
status_indicator.is_recording = True
if __name__ == "__main__":
app = RealtimeApp()
app.run()