Spaces:
Sleeping
Sleeping
# app.py | |
import gradio as gr | |
import os, time, re, json, base64, asyncio, threading, uuid, io | |
import numpy as np | |
import soundfile as sf | |
from pydub import AudioSegment | |
from openai import OpenAI | |
from websockets import connect | |
from dotenv import load_dotenv | |
# Load secrets | |
load_dotenv() | |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
ASSISTANT_ID = os.getenv("ASSISTANT_ID") | |
client = OpenAI(api_key=OPENAI_API_KEY) | |
HEADERS = {"Authorization": f"Bearer {OPENAI_API_KEY}", "OpenAI-Beta": "realtime=v1"} | |
WS_URI = "wss://api.openai.com/v1/realtime?intent=transcription" | |
connections = {} | |
# WebSocket Client | |
class WebSocketClient: | |
def __init__(self, uri, headers, client_id): | |
self.uri = uri | |
self.headers = headers | |
self.client_id = client_id | |
self.websocket = None | |
self.queue = asyncio.Queue(maxsize=10) | |
self.transcript = "" | |
self.loop = asyncio.new_event_loop() | |
async def connect(self): | |
try: | |
self.websocket = await connect(self.uri, additional_headers=self.headers) | |
with open("openai_transcription_settings.json", "r") as f: | |
await self.websocket.send(f.read()) | |
await asyncio.gather(self.receive_messages(), self.send_audio_chunks()) | |
except Exception as e: | |
print(f"🔴 WebSocket Connection Failed: {e}") | |
def run(self): | |
asyncio.set_event_loop(self.loop) | |
self.loop.run_until_complete(self.connect()) | |
def enqueue_audio_chunk(self, sr, arr): | |
if not self.queue.full(): | |
asyncio.run_coroutine_threadsafe(self.queue.put((sr, arr)), self.loop) | |
async def send_audio_chunks(self): | |
while True: | |
sr, arr = await self.queue.get() | |
if arr.ndim > 1: | |
arr = arr.mean(axis=1) | |
if np.max(np.abs(arr)) > 0: | |
arr = arr / np.max(np.abs(arr)) | |
int16 = (arr * 32767).astype(np.int16) | |
buf = io.BytesIO() | |
sf.write(buf, int16, sr, format='WAV', subtype='PCM_16') | |
audio = AudioSegment.from_file(buf, format="wav").set_frame_rate(24000) | |
out = io.BytesIO() | |
audio.export(out, format="wav") | |
out.seek(0) | |
await self.websocket.send(json.dumps({ | |
"type": "input_audio_buffer.append", | |
"audio": base64.b64encode(out.read()).decode() | |
})) | |
async def receive_messages(self): | |
async for msg in self.websocket: | |
data = json.loads(msg) | |
if data["type"] == "conversation.item.input_audio_transcription.delta": | |
self.transcript += data["delta"] | |
# WebSocket Connection Manager | |
def create_ws(): | |
cid = str(uuid.uuid4()) | |
client = WebSocketClient(WS_URI, HEADERS, cid) | |
threading.Thread(target=client.run, daemon=True).start() | |
connections[cid] = client | |
return cid | |
def send_audio(chunk, cid): | |
if not cid or cid not in connections: | |
return "Connecting..." | |
sr, arr = chunk | |
connections[cid].enqueue_audio_chunk(sr, arr) | |
return connections[cid].transcript.strip() | |
def clear_transcript_only(cid): | |
if cid in connections: | |
connections[cid].transcript = "" | |
return "" | |
def handle_chat(user_input, thread_id): | |
if not OPENAI_API_KEY or not ASSISTANT_ID: | |
return "❌ Missing secrets!", thread_id, "", None | |
try: | |
if thread_id is None: | |
thread = client.beta.threads.create() | |
thread_id = thread.id | |
client.beta.threads.messages.create(thread_id=thread_id, role="user", content=user_input) | |
run = client.beta.threads.runs.create(thread_id=thread_id, assistant_id=ASSISTANT_ID) | |
while True: | |
status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id) | |
if status.status == "completed": | |
break | |
time.sleep(1) | |
msgs = client.beta.threads.messages.list(thread_id=thread_id) | |
for msg in reversed(msgs.data): | |
if msg.role == "assistant": | |
content = msg.content[0].text.value | |
match = re.search( | |
r'https://raw\.githubusercontent\.com/AndrewLORTech/surgical-pathology-manual/main/[\w\-/]*\.png', | |
content | |
) | |
image_url = match.group(0) if match else None | |
response = f"### ❓ Question\n{user_input}\n\n---\n\n### 💡 Answer\n{content}" | |
return response, thread_id, image_url | |
return "No response from assistant.", thread_id, None | |
except Exception as e: | |
return f"❌ {e}", thread_id, None | |
def feed_transcript(transcript, thread_id, cid): | |
if not transcript.strip(): | |
return gr.update(), thread_id, None | |
if cid in connections: | |
connections[cid].transcript = "" | |
return handle_chat(transcript, thread_id,) | |
# ============ Gradio UI ============ | |
with gr.Blocks(theme=gr.themes.Soft()) as app: | |
gr.HTML(""" | |
<style> | |
body { | |
font-family: 'Inter', sans-serif; | |
background-color: #f9f9fb; | |
} | |
.big-btn { | |
font-size: 16px; | |
padding: 12px 20px; | |
border-radius: 12px; | |
width: 100%; | |
background-color: #4f46e5; | |
color: white; | |
border: none; | |
} | |
.voice-area { | |
padding-top: 16px; | |
margin-top: 16px; | |
border-top: 1px solid #ddd; | |
} | |
</style> | |
""") | |
thread_state = gr.State() | |
client_id = gr.State() | |
with gr.Row(equal_height=True): | |
with gr.Column(scale=1): | |
user_input = gr.Textbox(placeholder="Ask your question...", label="Prompt") | |
submit_btn = gr.Button("🚀 Ask", variant="primary") | |
result_md = gr.Markdown() | |
image_output = gr.Image(label="🖼️ Preview", type="filepath", show_download_button=False) | |
with gr.Column(elem_classes="voice-area"): | |
gr.Markdown("🎙️ Real-time Voice Input") | |
voice_input = gr.Audio(label="Tap to Speak", streaming=True, type="numpy") | |
transcript_box = gr.Textbox(label="Transcript", lines=2, interactive=False) | |
voice_submit_btn = gr.Button("Send Voice", elem_classes="big-btn") | |
clear_transcript_btn = gr.Button("🧹 Clear Transcript", elem_classes="big-btn") | |
with gr.Column(scale=1.4): | |
gr.Markdown("### ⏱️ Assistant Response") | |
result_area = gr.Markdown() | |
# Bindings | |
submit_btn.click(fn=handle_chat, | |
inputs=[user_input, thread_state], | |
outputs=[result_area, thread_state, image_output]) | |
voice_input.stream(fn=send_audio, | |
inputs=[voice_input, client_id], | |
outputs=transcript_box, | |
stream_every=0.5) | |
voice_submit_btn.click(fn=feed_transcript, | |
inputs=[transcript_box, thread_state, client_id], | |
outputs=[result_area, thread_state, image_output]) | |
clear_transcript_btn.click(fn=clear_transcript_only, | |
inputs=[client_id], | |
outputs=transcript_box) | |
app.load(fn=create_ws, outputs=[client_id]) | |
app.launch() | |