"""Standalone Early Proof Live Voice Server (OpenAI Realtime GA API).
This is an isolated spike script that does NOT alter or mutate any core application code.
Features:
1. Native Persian Accent & Pronunciation Prompting.
2. Dynamic Voice Switcher (Shimmer, Coral, Verse, Ballad, Echo, Onyx, etc.).
3. Accurate Whisper Persian Transcription (forced language='fa').
4. Robust Turn State Machine (No orphan bubbles, strict chronological order).
5. Native 24kHz Audio Capture without resampling phase distortion.
6. WebSocket Endpoint at `ws://localhost:1320/api/v1/voice/stream`
7. Interactive Web UI at `http://localhost:1320/`
Usage:
.venv\\Scripts\\python scripts/live_voice_server.py
"""
import asyncio
import base64
import json
import os
import sys
import uuid
from typing import Optional
# Ensure UTF-8 output on Windows consoles to prevent cp1256 charmap encoding errors
if sys.stdout and hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
from dotenv import load_dotenv
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
import uvicorn
import websockets
# Load environment variables from .env
load_dotenv(".env")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or os.getenv("API_KEY", "")
OPENAI_REALTIME_MODEL = os.getenv("OPENAI_REALTIME_MODEL", "gpt-realtime-mini")
OPENAI_PROXY = os.getenv("OPENAI_PROXY") or os.getenv("HTTPS_PROXY") or os.getenv("HTTP_PROXY") or None
app = FastAPI(title="Live Voice Early Proof Server")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
HTML_UI = """
دستیار صوتی اسناد سازمانی (OpenAI Realtime)
دستیار صوتی اسناد فنی و سازمانی (OpenAI Realtime)
مکالمه زنده صوتی دوطرفه با پیادهسازی متنی دقیق زبان فارسی
آماده برای شروع
🤖 هوش مصنوعی
سلام و درود! دکمه میکروفون را بزنید و به فارسی صحبت کنید، یا سوال خود را در کادر زیر بنویسید.
"""
@app.get("/", response_class=HTMLResponse)
@app.get("/voice-test", response_class=HTMLResponse)
async def serve_test_ui():
"""Serve standalone test interface for in-browser microphone and voice testing."""
return HTMLResponse(content=HTML_UI)
@app.websocket("/api/v1/voice/stream")
@app.websocket("/api/v1/voice/sessions/{session_id}/stream")
async def voice_stream_endpoint(client_ws: WebSocket, session_id: Optional[str] = None):
"""Bidirectional WebSocket bridge connecting client to OpenAI Realtime API."""
await client_ws.accept()
if not OPENAI_API_KEY:
await client_ws.send_json({
"type": "error",
"error": {
"code": "MISSING_API_KEY",
"message": "OPENAI_API_KEY is not configured in .env",
}
})
await client_ws.close()
return
session_uuid = session_id or str(uuid.uuid4())
chosen_voice = client_ws.query_params.get("voice", "shimmer")
openai_url = f"wss://api.openai.com/v1/realtime?model={OPENAI_REALTIME_MODEL}"
headers = {
"Authorization": f"Bearer {OPENAI_API_KEY}",
}
print(f"[*] Client connected ({session_uuid}) with voice: {chosen_voice}. Connecting to OpenAI Realtime: {OPENAI_REALTIME_MODEL}...")
try:
connect_kwargs = {
"additional_headers": headers,
"open_timeout": 15,
"ping_interval": 20,
"ping_timeout": 20,
}
if OPENAI_PROXY:
connect_kwargs["proxy"] = OPENAI_PROXY
async with websockets.connect(openai_url, **connect_kwargs) as openai_ws:
print("[+] Successfully connected to OpenAI Realtime WebSocket!")
# 1. Send session setup to OpenAI (Persian speech + Strict Persian Whisper STT)
session_setup = {
"type": "session.update",
"session": {
"type": "realtime",
"instructions": (
"شما یک گوینده و کارشناس رسمی بومی زبان فارسی (Native Persian Speaker) با لهجه اصیل و شیوای تهرانی هستید. "
"بسیار روان، گرم، خوشبیان، رسا و با لحن کاملاً طبیعی زبان فارسی صحبت کنید. "
"از هرگونه لهجه خارجی، لحن ماشینی، تلفظ انگلیسی یا عربی بهشدت خودداری کنید. "
"کلمات و افعال فارسی را دقیقاً همانند یک گوینده مجرب رادیو یا کارشناس محترم ایرانی شمرده ادا کنید. "
"هنگامی که کاربر سوالی درباره مقررات، اسناد، بخشنامهها یا ساعات کاری پرسید، حتماً از ابزار search_knowledge برای بازیابی دقیق شواهد استفاده کنید. "
"پاسخهای صوتی را کوتاه، خلاصه، رسا و کاملاً متناسب با گفتگوی صوتی بیان کنید."
),
"audio": {
"input": {
"format": {"type": "audio/pcm", "rate": 24000},
"transcription": {
"model": "whisper-1",
"language": "fa"
},
"turn_detection": {
"type": "server_vad",
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
}
},
"output": {
"format": {"type": "audio/pcm", "rate": 24000},
"voice": chosen_voice,
"speed": 0.98
}
},
"tools": [
{
"type": "function",
"name": "search_knowledge",
"description": "جستجوی مستندات، آییننامهها، و بخشنامههای سازمانی بر اساس پرسش کاربر",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "عبارت یا موضوع مورد جستجو به زبان فارسی"
},
"context": {
"type": "string",
"description": "زمینه و سابقه مکالمه قبلی (اختیاری)"
}
},
"required": ["query"]
}
}
],
"tool_choice": "auto"
}
}
await openai_ws.send(json.dumps(session_setup))
# Notify client that session is ready
await client_ws.send_json({
"type": "session_ready",
"session_id": session_uuid,
"input_audio": {"encoding": "pcm_s16le", "sample_rate": 24000, "channels": 1},
"output_audio": {"encoding": "pcm_s16le", "sample_rate": 24000, "channels": 1}
})
# Task A: Client -> OpenAI
async def forward_client_to_openai():
try:
while True:
msg = await client_ws.receive()
if msg.get("type") == "websocket.disconnect":
break
if "bytes" in msg and msg["bytes"]:
b64_audio = base64.b64encode(msg["bytes"]).decode("ascii")
await openai_ws.send(json.dumps({
"type": "input_audio_buffer.append",
"audio": b64_audio
}))
elif "text" in msg and msg["text"]:
try:
payload = json.loads(msg["text"])
mtype = payload.get("type")
if mtype == "user_text_message":
await openai_ws.send(json.dumps({
"type": "conversation.item.create",
"item": {
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": payload.get("text", "")}]
}
}))
await openai_ws.send(json.dumps({"type": "response.create"}))
elif mtype == "update_voice":
new_v = payload.get("voice", "shimmer")
print(f"[*] Switching voice to: {new_v}")
await openai_ws.send(json.dumps({
"type": "session.update",
"session": {
"type": "realtime",
"audio": {
"output": {
"voice": new_v
}
}
}
}))
else:
await openai_ws.send(json.dumps(payload))
except Exception:
pass
except Exception:
pass
# Task B: OpenAI -> Client
async def forward_openai_to_client():
active_response = False
is_interrupted = False
try:
async for raw_event in openai_ws:
event = json.loads(raw_event)
etype = event.get("type", "")
# Track response lifecycle
if etype == "response.created":
active_response = True
is_interrupted = False
elif etype in ("response.done", "response.cancelled"):
active_response = False
# 0. User Speech Started -> IMMEDIATE BARGE-IN
if etype == "input_audio_buffer.speech_started":
if active_response:
print("[*] User interrupted AI speech! Sending response.cancel to OpenAI...")
try:
await openai_ws.send(json.dumps({"type": "response.cancel"}))
except Exception as cancel_err:
print(f"[Cancel Error]: {cancel_err}")
active_response = False
is_interrupted = True
# Instantly instruct client to kill all audio playback
await client_ws.send_json({
"type": "turn_interrupted"
})
await client_ws.send_json({
"type": "user_speech_started"
})
# 1. Model Audio Delta (discard if interrupted)
elif etype in ("response.output_audio.delta", "response.audio.delta") and "delta" in event:
if not is_interrupted:
audio_bytes = base64.b64decode(event["delta"])
await client_ws.send_bytes(audio_bytes)
# 2. Model Transcript Delta (discard if interrupted)
elif etype in ("response.output_audio_transcript.delta", "response.audio_transcript.delta") and "delta" in event:
if not is_interrupted:
await client_ws.send_json({
"type": "transcript",
"role": "assistant",
"text": event["delta"],
"status": "partial"
})
# 3. Model Transcript Completed (discard if interrupted)
elif etype in ("response.output_audio_transcript.done", "response.audio_transcript.done") and "transcript" in event:
if not is_interrupted:
await client_ws.send_json({
"type": "transcript",
"role": "assistant",
"text": event["transcript"],
"status": "completed"
})
# 4. User Voice Transcription (Whisper)
elif etype == "conversation.item.input_audio_transcription.completed":
transcript_text = event.get("transcript", "")
print(f"[User Voice Transcript]: {transcript_text}")
await client_ws.send_json({
"type": "transcript",
"role": "user",
"text": transcript_text,
"status": "completed"
})
elif etype == "conversation.item.input_audio_transcription.failed":
err_info = event.get("error", {})
print(f"[User Voice Transcription Failed]: {err_info}")
await client_ws.send_json({
"type": "transcript",
"role": "user",
"text": "",
"status": "failed"
})
elif ("input_audio_transcription" in etype) and "transcript" in event:
print(f"[User Voice Transcript]: {event['transcript']}")
await client_ws.send_json({
"type": "transcript",
"role": "user",
"text": event["transcript"],
"status": "completed"
})
# 5. Interruption / Barge-in
elif etype == "input_audio_buffer.speech_stopped":
pass
# 6. Tool Call: search_knowledge
elif etype == "response.function_call_arguments.done":
call_id = event.get("call_id")
tool_name = event.get("name")
args_str = event.get("arguments", "{}")
print(f"[Tool Call] {tool_name} with args: {args_str}")
if tool_name == "search_knowledge":
try:
args = json.loads(args_str)
query = args.get("query", "")
context = args.get("context", "")
evidence_sources = [
{
"source_ref": "S1",
"title": "بخشنامه ساعات کاری تابستان",
"text": f"در پاسخ به «{query}»: بر اساس بخشنامه رسمی، ساعات کاری پرسنل از ساعت ۶:۰۰ صبح تا ۱۳:۰۰ میباشد. موارد استثناء شامل واحدهای شیفتی، تأسیسات و حراست است.",
"location": {"page": 1, "section": "ماده ۳"}
}
]
await client_ws.send_json({
"type": "sources",
"tool_call_id": call_id,
"sources": evidence_sources
})
await openai_ws.send(json.dumps({
"type": "conversation.item.create",
"item": {
"type": "function_call_output",
"call_id": call_id,
"output": json.dumps({
"status": "ok",
"evidence": evidence_sources[0]["text"]
}, ensure_ascii=False)
}
}))
await openai_ws.send(json.dumps({
"type": "response.create"
}))
except Exception as tool_err:
print(f"[Tool Error]: {tool_err}")
elif etype == "error":
print(f"[OpenAI Error]: {event.get('error')}")
await client_ws.send_json({
"type": "error",
"error": event.get("error", {})
})
except Exception:
pass
task_client = asyncio.create_task(forward_client_to_openai())
task_openai = asyncio.create_task(forward_openai_to_client())
done, pending = await asyncio.wait(
[task_client, task_openai],
return_when=asyncio.FIRST_COMPLETED
)
for p in pending:
p.cancel()
except Exception as e:
print(f"[Connection Error]: {e}")
try:
await client_ws.send_json({
"type": "error",
"error": {
"code": "PROVIDER_CONNECTION_FAILED",
"message": str(e)
}
})
except Exception:
pass
if __name__ == "__main__":
port = int(os.getenv("PORT", "1320"))
print("\n" + "="*60)
print(" 🚀 Live Voice Early Proof Server Starting...")
print(f" 🌐 Interactive Browser Test UI: http://localhost:{port}/")
print(f" 🔌 WebSocket Endpoint for UI: ws://localhost:{port}/api/v1/voice/stream")
print("="*60 + "\n")
uvicorn.run(app, host="0.0.0.0", port=port)