-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpush_to_talk_app.py
More file actions
428 lines (350 loc) · 14.5 KB
/
push_to_talk_app.py
File metadata and controls
428 lines (350 loc) · 14.5 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
#!/usr/bin/env uv run
"""
按键说话 (Push-to-Talk) Realtime API 终端应用
这是一个使用 Textual 框架构建的终端用户界面 (TUI) 应用,
展示了如何使用 OpenAI Realtime API 进行语音交互。
运行要求:
- 安装 `uv` 包管理器
- 设置 `OPENAI_API_KEY` 环境变量
- Mac 系统需要: `brew install portaudio ffmpeg`
运行方式:
`./examples/realtime/push_to_talk_app.py`
使用说明:
- 按 K 键开始/停止录音
- 按 Q 键退出应用
依赖包:
- textual: 终端 UI 框架
- numpy: 数值计算
- pyaudio: 音频处理
- pydub: 音频转换
- sounddevice: 音频设备访问
- openai[realtime]: OpenAI SDK 及 Realtime 支持
"""
####################################################################
#
# /// 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
import json
from typing import Any, cast, Optional
from typing_extensions import override
from textual import events
from audio_utils 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
# 本地服务器配置
LOCAL_SERVER_URL = "ws://localhost:8000/v1/realtime"
USE_LOCAL_SERVER = True # 设置为 True 使用本地服务器,False 使用 OpenAI
# 根据配置选择导入方式
if USE_LOCAL_SERVER:
import websockets
from websockets.asyncio.client import ClientConnection
else:
from openai import AsyncOpenAI
from openai.types.realtime.session import Session
from openai.resources.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;
}
"""
should_send_audio: asyncio.Event
audio_player: AudioPlayerAsync
last_audio_item_id: str | None
connection: Any # WebSocket 连接或 OpenAI 连接
session: Any # 会话对象
connected: asyncio.Event
ws: Optional[ClientConnection] if USE_LOCAL_SERVER else None # type: ignore
def __init__(self) -> None:
super().__init__()
self.connection = None
self.session = None
self.ws = None
# 配置客户端
if not USE_LOCAL_SERVER:
from openai import AsyncOpenAI
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:
"""处理 Realtime 连接 - 支持本地服务器和 OpenAI"""
if USE_LOCAL_SERVER:
await self._handle_local_server_connection()
else:
await self._handle_openai_connection()
async def _handle_local_server_connection(self) -> None:
"""连接到本地服务器"""
try:
self.ws = await websockets.connect(LOCAL_SERVER_URL)
self.connection = self.ws
self.connected.set()
# 发送会话更新请求
await self.ws.send(json.dumps({
"type": "session.update",
"session": {
"turn_detection": {"type": "server_vad"},
"modalities": ["audio", "text"],
}
}))
acc_items: dict[str, Any] = {}
# 接收事件循环
async for message in self.ws:
try:
event = json.loads(message)
event_type = event.get("type", "")
if event_type == "session.created":
session_id = event.get("session", {}).get("id", "unknown")
session_display = self.query_one(SessionDisplay)
session_display.session_id = session_id
continue
if event_type == "session.updated":
continue
if event_type == "response.audio.delta":
item_id = event.get("item_id", "")
delta = event.get("delta", "")
if item_id != self.last_audio_item_id:
self.audio_player.reset_frame_count()
self.last_audio_item_id = item_id
if delta:
bytes_data = base64.b64decode(delta)
self.audio_player.add_data(bytes_data)
continue
if event_type == "response.audio_transcript.delta":
item_id = event.get("item_id", "")
delta = event.get("delta", "")
if item_id not in acc_items:
acc_items[item_id] = delta
else:
acc_items[item_id] = acc_items[item_id] + delta
bottom_pane = self.query_one("#bottom-pane", RichLog)
bottom_pane.clear()
bottom_pane.write(acc_items[item_id])
continue
# 处理其他事件类型
if event_type == "error":
error_msg = event.get("error", {}).get("message", "Unknown error")
bottom_pane = self.query_one("#bottom-pane", RichLog)
bottom_pane.write(f"[red]错误: {error_msg}[/red]")
continue
except json.JSONDecodeError:
continue
except Exception as e:
bottom_pane = self.query_one("#bottom-pane", RichLog)
bottom_pane.write(f"[red]连接错误: {e}[/red]")
async def _handle_openai_connection(self) -> None:
"""连接到 OpenAI Realtime API"""
async with self.client.realtime.connect(model="gpt-realtime") 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={
"audio": {
"input": {"turn_detection": {"type": "server_vad"}},
},
"model": "gpt-realtime",
"type": "realtime",
}
)
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.output_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.output_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) -> Any:
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 USE_LOCAL_SERVER:
# 本地服务器:直接发送 JSON 消息
if not sent_audio:
try:
await connection.send(json.dumps({"type": "response.cancel"}))
except:
pass
sent_audio = True
# 发送音频数据
audio_b64 = base64.b64encode(cast(Any, data)).decode("utf-8")
await connection.send(json.dumps({
"type": "input_audio_buffer.append",
"audio": audio_b64
}))
else:
# OpenAI SDK
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 USE_LOCAL_SERVER:
# 本地服务器:手动提交音频缓冲区
conn = await self._get_connection()
await conn.send(json.dumps({"type": "input_audio_buffer.commit"}))
await conn.send(json.dumps({"type": "response.create"}))
elif 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()