-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathREALTIMEAPI.py
More file actions
466 lines (389 loc) · 17.3 KB
/
REALTIMEAPI.py
File metadata and controls
466 lines (389 loc) · 17.3 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
# import asyncio
# import websockets
# import pyaudio
# import numpy as np
# import base64
# import json
# import queue
# import threading
# import os
# from dotenv import load_dotenv
# load_dotenv()
# API_KEY = os.getenv('OPEN_AI')
# # WebSocket URL and header information
# WS_URL = "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01"
# HEADERS = {
# "Authorization": "Bearer " + API_KEY,
# "OpenAI-Beta": "realtime=v1"
# }
# # Initialize queues
# audio_send_queue = queue.Queue()
# audio_receive_queue = queue.Queue()
# conversation_history_id_queue = queue.Queue()
# # Function to convert Base64 to PCM16
# def base64_to_pcm16(base64_audio):
# return base64.b64decode(base64_audio)
# # Async function to send audio from queue
# async def send_audio_from_queue(websocket):
# while True:
# audio_data = await asyncio.get_event_loop().run_in_executor(None, audio_send_queue.get)
# if audio_data is None:
# continue
# base64_audio = base64.b64encode(audio_data).decode("utf-8")
# audio_event = {
# "type": "input_audio_buffer.append",
# "audio": base64_audio
# }
# await websocket.send(json.dumps(audio_event))
# await asyncio.sleep(0)
# # Function to read audio from mic and put it into the queue
# def read_audio_to_queue(stream, CHUNK):
# while True:
# try:
# audio_data = stream.read(CHUNK, exception_on_overflow=False)
# audio_send_queue.put(audio_data)
# except Exception as e:
# print(f"Audio reading error: {e}")
# break
# # Async function to receive audio from server and put it into the queue
# async def receive_audio_to_queue(websocket):
# print("assistant: ", end="", flush=True)
# while True:
# response = await websocket.recv()
# if response:
# response_data = json.loads(response)
# if "type" in response_data and response_data["type"] == "conversation.item.created":
# conversation_history_id_queue.put(response_data['item']['id'])
# if conversation_history_id_queue.qsize() >= 5:
# item_id = conversation_history_id_queue.get()
# delete_event = {
# "type": "conversation.item.delete",
# "item_id": item_id
# }
# await websocket.send(json.dumps(delete_event))
# print(f"Deleted conversation_history_id: {item_id}.")
# if "type" in response_data and response_data["type"] == "response.audio_transcript.delta":
# print(response_data["delta"], end="", flush=True)
# elif "type" in response_data and response_data["type"] == "response.audio_transcript.done":
# print("\nassistant: ", end="", flush=True)
# elif "type" in response_data and response_data["type"] == "conversation.item.input_audio_transcription.completed":
# print("\n↪︎by user messages: ", response_data["transcript"])
# elif "type" in response_data and response_data["type"] == "rate_limits.updated":
# print(f"Rate limits: {response_data['rate_limits'][0]['remaining']} requests remaining.")
# elif "type" in response_data and response_data["type"] == "response.audio.delta":
# base64_audio_response = response_data["delta"]
# if base64_audio_response:
# pcm16_audio = base64_to_pcm16(base64_audio_response)
# audio_receive_queue.put(pcm16_audio)
# await asyncio.sleep(0)
# # Function to play audio from the queue
# def play_audio_from_queue(output_stream):
# while True:
# pcm16_audio = audio_receive_queue.get()
# if pcm16_audio:
# output_stream.write(pcm16_audio)
# # Async function for streaming audio and receiving responses
# async def stream_audio_and_receive_response():
# # WebSocketに接続
# async with websockets.connect(WS_URL, extra_headers=HEADERS) as websocket:
# print("WebSocket")
# update_request = {
# "type": "session.update",
# "session": {
# "modalities": ["audio", "text"],
# "instructions": "Please respond in English with a British accent.",
# "voice": "nova",
# "turn_detection": {
# "type": "server_vad",
# "threshold": 0.5,
# },
# "input_audio_transcription": {
# "model": "whisper-1"
# }
# }
# }
# await websocket.send(json.dumps(update_request))
# # PyAudio setup
# INPUT_CHUNK = 2400
# OUTPUT_CHUNK = 2400
# FORMAT = pyaudio.paInt16
# CHANNELS = 1
# INPUT_RATE = 24000
# OUTPUT_RATE = 24000
# p = pyaudio.PyAudio()
# # Initialize microphone stream
# stream = p.open(format=FORMAT, channels=CHANNELS, rate=INPUT_RATE, input=True, frames_per_buffer=INPUT_CHUNK)
# # Initialize output stream for server responses
# output_stream = p.open(format=FORMAT, channels=CHANNELS, rate=OUTPUT_RATE, output=True, frames_per_buffer=OUTPUT_CHUNK)
# threading.Thread(target=read_audio_to_queue, args=(stream, INPUT_CHUNK), daemon=True).start()
# threading.Thread(target=play_audio_from_queue, args=(output_stream,), daemon=True).start()
# try:
# send_task = asyncio.create_task(send_audio_from_queue(websocket))
# receive_task = asyncio.create_task(receive_audio_to_queue(websocket))
# await asyncio.gather(send_task, receive_task)
# except KeyboardInterrupt:
# print("Exiting...")
# finally:
# stream.stop_stream()
# stream.close()
# output_stream.stop_stream()
# output_stream.close()
# p.terminate()
# if __name__ == "__main__":
# asyncio.run(stream_audio_and_receive_response())
import asyncio
import websockets
import pyaudio
import base64
import json
import queue
import threading
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('OPEN_AI')
# WebSocket URL and header information
WS_URL = "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01"
HEADERS = {
"Authorization": "Bearer " + API_KEY,
"OpenAI-Beta": "realtime=v1"
}
# Initialize queues
audio_send_queue = queue.Queue()
audio_receive_queue = queue.Queue()
conversation_history_id_queue = queue.Queue()
interrupt_event = threading.Event() # Event to signal audio interruption
is_playing = threading.Event() # Event to signal if audio is currently playing
# Function to convert Base64 to PCM16
def base64_to_pcm16(base64_audio):
return base64.b64decode(base64_audio)
# Async function to send audio from queue
async def send_audio_from_queue(websocket):
while True:
audio_data = await asyncio.get_event_loop().run_in_executor(None, audio_send_queue.get)
if audio_data is None:
continue
base64_audio = base64.b64encode(audio_data).decode("utf-8")
audio_event = {
"type": "input_audio_buffer.append",
"audio": base64_audio
}
await websocket.send(json.dumps(audio_event))
await asyncio.sleep(0)
# Function to read audio from mic and put it into the queue
def read_audio_to_queue(stream, CHUNK):
while True:
try:
audio_data = stream.read(CHUNK, exception_on_overflow=False)
audio_send_queue.put(audio_data)
except Exception as e:
print(f"Audio reading error: {e}")
break
# Async function to receive audio from server and put it into the queue
async def receive_audio_to_queue(websocket):
print("assistant: ", end="", flush=True)
while True:
response = await websocket.recv()
if response:
response_data = json.loads(response)
if "type" in response_data and response_data["type"] == "conversation.item.created":
conversation_history_id_queue.put(response_data['item']['id'])
if conversation_history_id_queue.qsize() >= 5:
item_id = conversation_history_id_queue.get()
delete_event = {
"type": "conversation.item.delete",
"item_id": item_id
}
await websocket.send(json.dumps(delete_event))
print(f"Deleted conversation_history_id: {item_id}.")
if "type" in response_data and response_data["type"] == "response.audio_transcript.delta":
print(response_data["delta"], end="", flush=True)
elif "type" in response_data and response_data["type"] == "response.audio_transcript.done":
print("\nassistant: ", end="", flush=True)
elif "type" in response_data and response_data["type"] == "conversation.item.input_audio_transcription.completed":
print("\n↪︎by user messages: ", response_data["transcript"])
interrupt_event.set() # Signal that there was a cut-in
elif "type" in response_data and response_data["type"] == "rate_limits.updated":
print(f"Rate limits: {response_data['rate_limits'][0]['remaining']} requests remaining.")
elif "type" in response_data and response_data["type"] == "response.audio.delta":
base64_audio_response = response_data["delta"]
if base64_audio_response:
pcm16_audio = base64_to_pcm16(base64_audio_response)
audio_receive_queue.put(pcm16_audio)
await asyncio.sleep(0)
# Function to play audio from the queue
def play_audio_from_queue(output_stream):
while True:
pcm16_audio = audio_receive_queue.get()
if pcm16_audio:
is_playing.set() # Indicate that audio is playing
output_stream.write(pcm16_audio)
if interrupt_event.is_set(): # Check for interruption
interrupt_event.clear() # Reset the interrupt event
is_playing.clear() # Reset playing status
break # Exit after interruption
# Async function for streaming audio and receiving responses
async def stream_audio_and_receive_response():
async with websockets.connect(WS_URL, extra_headers=HEADERS) as websocket:
print("WebSocket connected.")
update_request = {
"type": "session.update",
"session": {
"modalities": ["audio", "text"],
"instructions": "Please respond in English with a British accent.",
"voice": "nova",
"turn_detection": {
"type": "server_vad",
"threshold": 0.5,
},
"input_audio_transcription": {
"model": "whisper-1"
}
}
}
await websocket.send(json.dumps(update_request))
# PyAudio setup
INPUT_CHUNK = 2400
OUTPUT_CHUNK = 2400
FORMAT = pyaudio.paInt16
CHANNELS = 1
INPUT_RATE = 24000
OUTPUT_RATE = 24000
p = pyaudio.PyAudio()
# Initialize microphone stream
stream = p.open(format=FORMAT, channels=CHANNELS, rate=INPUT_RATE, input=True, frames_per_buffer=INPUT_CHUNK)
# Initialize output stream for server responses
output_stream = p.open(format=FORMAT, channels=CHANNELS, rate=OUTPUT_RATE, output=True, frames_per_buffer=OUTPUT_CHUNK)
threading.Thread(target=read_audio_to_queue, args=(stream, INPUT_CHUNK), daemon=True).start()
threading.Thread(target=play_audio_from_queue, args=(output_stream,), daemon=True).start()
try:
send_task = asyncio.create_task(send_audio_from_queue(websocket))
receive_task = asyncio.create_task(receive_audio_to_queue(websocket))
await asyncio.gather(send_task, receive_task)
except KeyboardInterrupt:
print("Exiting...")
finally:
stream.stop_stream()
stream.close()
output_stream.stop_stream()
output_stream.close()
p.terminate()
if __name__ == "__main__":
asyncio.run(stream_audio_and_receive_response())
# import asyncio
# import websockets
# import pyaudio
# import base64
# import json
# import queue
# import threading
# import os
# from dotenv import load_dotenv
# load_dotenv()
# # Load environment variable for the OpenAI API key
# API_KEY = os.getenv('OPEN_AI')
# # WebSocket URL and header information
# WS_URL = "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01"
# HEADERS = {
# "Authorization": "Bearer " + API_KEY,
# "OpenAI-Beta": "realtime=v1"
# }
# # Initialize queues
# audio_send_queue = queue.Queue()
# audio_receive_queue = queue.Queue()
# # Function to convert Base64 to PCM16
# def base64_to_pcm16(base64_audio):
# return base64.b64decode(base64_audio)
# # Async function to send audio from queue
# async def send_audio_from_queue(websocket):
# while True:
# audio_data = await asyncio.get_event_loop().run_in_executor(None, audio_send_queue.get)
# if audio_data is None:
# continue
# base64_audio = base64.b64encode(audio_data).decode("utf-8")
# audio_event = {
# "type": "input_audio_buffer.append",
# "audio": base64_audio
# }
# await websocket.send(json.dumps(audio_event))
# await asyncio.sleep(0)
# # Function to read audio from mic and put it into the queue
# def read_audio_to_queue(stream, CHUNK):
# while True:
# try:
# audio_data = stream.read(CHUNK, exception_on_overflow=False)
# audio_send_queue.put(audio_data)
# except Exception as e:
# print(f"Audio reading error: {e}")
# break
# # Async function to receive audio from server and put it into the queue
# async def receive_audio_to_queue(websocket):
# print("assistant: ", end="", flush=True)
# while True:
# response = await websocket.recv()
# if response:
# response_data = json.loads(response)
# if "type" in response_data and response_data["type"] == "response.audio_transcript.delta":
# print(response_data["delta"], end="", flush=True)
# elif "type" in response_data and response_data["type"] == "response.audio_transcript.done":
# print("\nassistant: ", end="", flush=True)
# elif "type" in response_data and response_data["type"] == "conversation.item.input_audio_transcription.completed":
# print("\n↪︎by user messages: ", response_data["transcript"])
# if "type" in response_data and response_data["type"] == "response.audio.delta":
# base64_audio_response = response_data["delta"]
# if base64_audio_response:
# pcm16_audio = base64_to_pcm16(base64_audio_response)
# audio_receive_queue.put(pcm16_audio)
# await asyncio.sleep(0)
# # Function to play audio from the queue
# def play_audio_from_queue(output_stream):
# while True:
# pcm16_audio = audio_receive_queue.get()
# if pcm16_audio:
# output_stream.write(pcm16_audio)
# # Async function for streaming audio and receiving responses
# async def stream_audio_and_receive_response():
# async with websockets.connect(WS_URL, extra_headers=HEADERS) as websocket:
# print("WebSocket connected.")
# update_request = {
# "type": "session.update",
# "session": {
# "modalities": ["audio", "text"],
# "instructions": "Please respond in English with a British accent.",
# "voice": "nova",
# "turn_detection": {
# "type": "server_vad",
# "threshold": 0.5,
# },
# "input_audio_transcription": {
# "model": "whisper-1"
# }
# }
# }
# await websocket.send(json.dumps(update_request))
# # PyAudio setup
# INPUT_CHUNK = 2400
# OUTPUT_CHUNK = 2400
# FORMAT = pyaudio.paInt16
# CHANNELS = 1
# INPUT_RATE = 24000
# OUTPUT_RATE = 24000
# p = pyaudio.PyAudio()
# stream = p.open(format=FORMAT, channels=CHANNELS, rate=INPUT_RATE, input=True, frames_per_buffer=INPUT_CHUNK)
# output_stream = p.open(format=FORMAT, channels=CHANNELS, rate=OUTPUT_RATE, output=True, frames_per_buffer=OUTPUT_CHUNK)
# threading.Thread(target=read_audio_to_queue, args=(stream, INPUT_CHUNK), daemon=True).start()
# threading.Thread(target=play_audio_from_queue, args=(output_stream,), daemon=True).start()
# try:
# send_task = asyncio.create_task(send_audio_from_queue(websocket))
# receive_task = asyncio.create_task(receive_audio_to_queue(websocket))
# await asyncio.gather(send_task, receive_task)
# except KeyboardInterrupt:
# print("Exiting...")
# finally:
# stream.stop_stream()
# stream.close()
# output_stream.stop_stream()
# output_stream.close()
# p.terminate()
# if __name__ == "__main__":
# asyncio.run(stream_audio_and_receive_response())