Files
rag-technical-docs-assistant/scripts/live_voice_server.py
T
amirhosein mazaheri 8ebdefb7f8 chore(voice): add standalone OpenAI Realtime proof
Preserve the Persian voice browser proof, audio relay, transcription, and interruption flow. Knowledge responses remain illustrative placeholders pending real backend integration.
2026-10-08 12:59:00 +03:30

1173 lines
49 KiB
Python

"""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 = """<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>دستیار صوتی اسناد سازمانی (OpenAI Realtime)</title>
<style>
:root {
--bg: #0b0f19;
--surface: #111827;
--surface-border: #1f2937;
--primary: #4f46e5;
--primary-light: #6366f1;
--primary-glow: rgba(99, 102, 241, 0.4);
--text: #f9fafb;
--text-dim: #9ca3af;
--user-bubble: #1e3a8a;
--user-border: #2563eb;
--ai-bubble: #1f2937;
--ai-border: #374151;
--accent: #10b981;
--danger: #ef4444;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: system-ui, -apple-system, 'Segoe UI', Tahoma, Arial, sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
header {
padding: 0.9rem 1.75rem;
background: var(--surface);
border-bottom: 1px solid var(--surface-border);
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 1rem;
}
.title-group h1 { font-size: 1.15rem; font-weight: 700; color: #fff; }
.title-group p { font-size: 0.78rem; color: var(--text-dim); margin-top: 2px; }
.header-controls {
display: flex;
align-items: center;
gap: 1rem;
}
.voice-picker {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.85rem;
color: var(--text-dim);
}
.voice-picker select {
background: rgba(255,255,255,0.06);
border: 1px solid var(--surface-border);
color: #fff;
padding: 0.4rem 0.8rem;
border-radius: 8px;
font-size: 0.82rem;
outline: none;
font-family: inherit;
cursor: pointer;
}
.voice-picker select:focus { border-color: var(--primary-light); }
.status-badge {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.35rem 0.85rem;
border-radius: 9999px;
font-size: 0.82rem;
background: rgba(255,255,255,0.05);
border: 1px solid var(--surface-border);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--danger);
}
.status-dot.connected { background: var(--accent); box-shadow: 0 0 8px var(--accent); }
.status-dot.connecting { background: #f59e0b; }
.status-dot.listening { background: #38bdf8; box-shadow: 0 0 10px #38bdf8; animation: pulseDot 1s infinite; }
@keyframes pulseDot { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
main {
flex: 1;
display: grid;
grid-template-columns: 1fr 340px;
gap: 1.5rem;
padding: 1.25rem 1.75rem;
max-width: 1400px;
width: 100%;
margin: 0 auto;
}
@media (max-width: 900px) {
main { grid-template-columns: 1fr; }
}
.chat-section {
display: flex;
flex-direction: column;
background: var(--surface);
border: 1px solid var(--surface-border);
border-radius: 16px;
overflow: hidden;
height: calc(100vh - 120px);
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 1.25rem 1.5rem;
display: flex;
flex-direction: column;
gap: 1.1rem;
}
.message-row {
display: flex;
width: 100%;
}
.message-row.user-row {
justify-content: flex-start; /* Right side in RTL */
}
.message-row.ai-row {
justify-content: flex-end; /* Left side in RTL */
}
.message-bubble {
max-width: 82%;
padding: 0.85rem 1.15rem;
border-radius: 14px;
line-height: 1.65;
font-size: 0.92rem;
animation: fadeIn 0.2s ease;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
@keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
.user-msg {
background: var(--user-bubble);
border: 1px solid var(--user-border);
border-top-right-radius: 3px;
color: #eff6ff;
}
.user-msg.pending {
border-style: dashed;
background: rgba(30, 58, 138, 0.6);
color: #93c5fd;
}
.ai-msg {
background: var(--ai-bubble);
border: 1px solid var(--ai-border);
border-top-left-radius: 3px;
color: #f3f4f6;
}
.msg-meta {
font-size: 0.72rem;
color: var(--text-dim);
margin-bottom: 0.35rem;
display: flex;
align-items: center;
gap: 0.35rem;
font-weight: 600;
}
.user-msg .msg-meta { color: #93c5fd; }
.ai-msg .msg-meta { color: #818cf8; }
.controls-bar {
padding: 0.9rem 1.25rem;
border-top: 1px solid var(--surface-border);
display: flex;
flex-direction: column;
gap: 0.65rem;
background: rgba(11, 15, 25, 0.7);
}
.quick-prompts {
display: flex;
gap: 0.5rem;
overflow-x: auto;
padding-bottom: 0.25rem;
}
.prompt-chip {
background: rgba(255,255,255,0.06);
border: 1px solid var(--surface-border);
color: var(--text-dim);
padding: 0.3rem 0.75rem;
border-radius: 20px;
font-size: 0.78rem;
cursor: pointer;
white-space: nowrap;
transition: all 0.2s;
}
.prompt-chip:hover {
background: rgba(99, 102, 241, 0.2);
color: var(--text);
border-color: var(--primary-light);
}
.action-row {
display: flex;
align-items: center;
gap: 0.85rem;
}
.text-input-wrap {
flex: 1;
display: flex;
gap: 0.5rem;
}
.text-input {
flex: 1;
background: rgba(255,255,255,0.05);
border: 1px solid var(--surface-border);
border-radius: 8px;
padding: 0.65rem 1rem;
color: #fff;
outline: none;
font-family: inherit;
font-size: 0.88rem;
}
.text-input:focus { border-color: var(--primary-light); }
.send-btn {
background: rgba(255,255,255,0.1);
border: 1px solid var(--surface-border);
color: #fff;
padding: 0 1.15rem;
border-radius: 8px;
cursor: pointer;
font-size: 0.85rem;
}
.send-btn:hover { background: var(--primary-light); }
.mic-btn {
width: 54px;
height: 54px;
border-radius: 50%;
border: none;
cursor: pointer;
background: var(--primary);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.45rem;
box-shadow: 0 0 15px var(--primary-glow);
transition: all 0.2s ease;
flex-shrink: 0;
}
.mic-btn:hover { transform: scale(1.05); }
.mic-btn.active {
background: var(--danger);
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.6); }
70% { box-shadow: 0 0 0 16px rgba(239, 68, 68, 0); }
100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
}
.sources-sidebar {
background: var(--surface);
border: 1px solid var(--surface-border);
border-radius: 16px;
padding: 1.25rem;
height: calc(100vh - 120px);
overflow-y: auto;
}
.sources-sidebar h2 { font-size: 0.95rem; margin-bottom: 1rem; color: #e5e7eb; }
.source-card {
background: rgba(255,255,255,0.03);
border: 1px solid var(--surface-border);
border-radius: 10px;
padding: 0.85rem;
margin-bottom: 0.75rem;
font-size: 0.85rem;
}
.source-card h3 { font-size: 0.88rem; color: #818cf8; margin-bottom: 0.35rem; }
.source-card p { color: var(--text-dim); line-height: 1.4; font-size: 0.82rem; }
.source-loc { font-size: 0.74rem; color: #38bdf8; margin-top: 0.4rem; font-weight: 600; }
</style>
</head>
<body>
<header>
<div class="title-group">
<h1>دستیار صوتی اسناد فنی و سازمانی (OpenAI Realtime)</h1>
<p>مکالمه زنده صوتی دوطرفه با پیاده‌سازی متنی دقیق زبان فارسی</p>
</div>
<div class="header-controls">
<div class="voice-picker">
<label for="voiceSelect">گوینده:</label>
<select id="voiceSelect" onchange="onVoiceChange()">
<option value="shimmer" selected>Shimmer (زنانه - روان و طبیعی)</option>
<option value="coral">Coral (زنانه - رسا و شیوا)</option>
<option value="verse">Verse (مردانه - پویا و رادیویی)</option>
<option value="ballad">Ballad (مردانه - صمیمی و آرام)</option>
<option value="sage">Sage (زنانه - ملایم)</option>
<option value="echo">Echo (مردانه - پرطنین)</option>
<option value="onyx">Onyx (مردانه - بم و جدی)</option>
<option value="alloy">Alloy (خنثی)</option>
</select>
</div>
<div class="status-badge">
<span class="status-dot" id="statusDot"></span>
<span id="statusText">آماده برای شروع</span>
</div>
</div>
</header>
<main>
<div class="chat-section">
<div class="chat-messages" id="chatMessages">
<div class="message-row ai-row">
<div class="message-bubble ai-msg">
<div class="msg-meta">🤖 هوش مصنوعی</div>
سلام و درود! دکمه میکروفون را بزنید و به فارسی صحبت کنید، یا سوال خود را در کادر زیر بنویسید.
</div>
</div>
</div>
<div class="controls-bar">
<div class="quick-prompts">
<button class="prompt-chip" onclick="sendQuickText('سلام، خودتو کوتاه معرفی کن.')">👋 معرفی کوتاه</button>
<button class="prompt-chip" onclick="sendQuickText('ساعات کاری شرکت در فصل تابستان چطوره و چه استثنائاتی داره؟')">📋 پرسش از بخشنامه ساعات کاری</button>
<button class="prompt-chip" onclick="sendQuickText('یک ضرب‌المثل شیرین فارسی بگو.')">🗣 تست لحن و بیان فارسی</button>
</div>
<div class="action-row">
<button class="mic-btn" id="micBtn" title="شروع / توقف مکالمه صوتی">🎤</button>
<div class="text-input-wrap">
<input type="text" id="textInput" class="text-input" placeholder="یا اینجا سوالی بنویسید و ارسال کنید..." onkeydown="if(event.key==='Enter') sendTextMessage()">
<button class="send-btn" onclick="sendTextMessage()">ارسال</button>
</div>
</div>
</div>
</div>
<aside class="sources-sidebar">
<h2>مدارک و شواهد استنادشده (Sources)</h2>
<div id="sourcesContainer">
<p style="color: var(--text-dim); font-size: 0.85rem;">هنوز استنادی ثبت نشده است.</p>
</div>
</aside>
</main>
<script>
const statusDot = document.getElementById('statusDot');
const statusText = document.getElementById('statusText');
const micBtn = document.getElementById('micBtn');
const chatMessages = document.getElementById('chatMessages');
const sourcesContainer = document.getElementById('sourcesContainer');
const textInput = document.getElementById('textInput');
const voiceSelect = document.getElementById('voiceSelect');
let ws = null;
let audioContext = null;
let mediaStream = null;
let scriptProcessor = null;
let isConnected = false;
let nextPlayTime = 0;
let activeAudioSources = []; // Tracks currently queued/playing audio buffers for instant interruption
// Robust Turn Architecture: Pair each user speech turn with its corresponding AI response
let currentTurn = null;
function setStatus(text, dotClass) {
statusText.innerText = text;
statusDot.className = 'status-dot ' + (dotClass || '');
}
function stopAllAudio() {
nextPlayTime = 0;
while (activeAudioSources.length > 0) {
const src = activeAudioSources.pop();
try {
src.stop(0);
src.disconnect();
} catch (e) {}
}
}
function createOrGetTurn() {
if (!currentTurn) {
currentTurn = {
id: Date.now(),
userRow: null,
userBubble: null,
userTextSpan: null,
userFinalized: false,
aiRow: null,
aiBubble: null,
aiTextSpan: null,
aiFinalized: false
};
}
return currentTurn;
}
// Triggered when user begins speaking (VAD speech_started)
function onUserSpeechStart() {
// Cut off any currently scheduled AI audio immediately
stopAllAudio();
// If an unfinalized turn already exists with a pending bubble, do not create duplicate
if (currentTurn && !currentTurn.userFinalized && currentTurn.userRow) {
return;
}
// If a previous turn had a pending bubble that never received text, remove it
if (currentTurn && !currentTurn.userFinalized && currentTurn.userRow) {
currentTurn.userRow.remove();
}
// Start a new turn
currentTurn = {
id: Date.now(),
userRow: null,
userBubble: null,
userTextSpan: null,
userFinalized: false,
aiRow: null,
aiBubble: null,
aiTextSpan: null,
aiFinalized: false
};
const row = document.createElement('div');
row.className = 'message-row user-row';
const bubble = document.createElement('div');
bubble.className = 'message-bubble user-msg pending';
bubble.innerHTML = `<div class="msg-meta">👤 شما</div><span class="bubble-text">🎙️ در حال شنیدن و پردازش...</span>`;
row.appendChild(bubble);
chatMessages.appendChild(row);
chatMessages.scrollTop = chatMessages.scrollHeight;
currentTurn.userRow = row;
currentTurn.userBubble = bubble;
currentTurn.userTextSpan = bubble.querySelector('.bubble-text');
}
// Triggered when Whisper transcription arrives for user speech
function onUserTranscriptReceived(text, status) {
const clean = (text || '').trim();
// If transcription failed or was empty background noise
if (!clean || status === 'failed') {
if (currentTurn && currentTurn.userRow && !currentTurn.userFinalized) {
currentTurn.userRow.remove();
currentTurn.userRow = null;
currentTurn.userBubble = null;
currentTurn.userTextSpan = null;
}
return;
}
const turn = createOrGetTurn();
if (turn.userRow) {
// Update existing pending bubble in place
turn.userBubble.classList.remove('pending');
turn.userTextSpan.innerText = clean;
turn.userFinalized = true;
} else {
// User bubble doesn't exist yet (e.g. text message or late event)
const row = document.createElement('div');
row.className = 'message-row user-row';
const bubble = document.createElement('div');
bubble.className = 'message-bubble user-msg';
bubble.innerHTML = `<div class="msg-meta">👤 شما</div><span class="bubble-text">${clean}</span>`;
row.appendChild(bubble);
// STRICT ORDERING: If AI bubble already exists for this turn, put User bubble BEFORE it
if (turn.aiRow && turn.aiRow.parentNode) {
chatMessages.insertBefore(row, turn.aiRow);
} else {
chatMessages.appendChild(row);
}
turn.userRow = row;
turn.userBubble = bubble;
turn.userTextSpan = bubble.querySelector('.bubble-text');
turn.userFinalized = true;
}
// If AI is already finished, this turn is completely done
if (turn.aiFinalized) {
currentTurn = null;
}
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Triggered when AI streams or finishes response text
function onAiTranscriptReceived(text, isDone) {
const turn = createOrGetTurn();
if (!turn.aiRow) {
const row = document.createElement('div');
row.className = 'message-row ai-row';
const bubble = document.createElement('div');
bubble.className = 'message-bubble ai-msg';
bubble.innerHTML = `<div class="msg-meta">🤖 هوش مصنوعی</div><span class="bubble-text"></span>`;
row.appendChild(bubble);
// STRICT ORDERING: Always append AI row after the User row if User row exists
if (turn.userRow && turn.userRow.nextSibling) {
chatMessages.insertBefore(row, turn.userRow.nextSibling);
} else {
chatMessages.appendChild(row);
}
turn.aiRow = row;
turn.aiBubble = bubble;
turn.aiTextSpan = bubble.querySelector('.bubble-text');
}
if (isDone) {
turn.aiTextSpan.innerText = text;
turn.aiFinalized = true;
// If user text is already finalized, finish the turn!
if (turn.userFinalized) {
currentTurn = null;
}
} else {
turn.aiTextSpan.innerText += text;
}
chatMessages.scrollTop = chatMessages.scrollHeight;
}
function updateSources(sources) {
sourcesContainer.innerHTML = '';
if (!sources || sources.length === 0) {
sourcesContainer.innerHTML = '<p style="color: var(--text-dim); font-size: 0.85rem;">بدون استناد مستقیم.</p>';
return;
}
sources.forEach(src => {
const card = document.createElement('div');
card.className = 'source-card';
card.innerHTML = `
<h3>${src.title || 'سند سازمانی'}</h3>
<p>${src.text || ''}</p>
<div class="source-loc">موقعیت: صفحه ${src.location?.page || 1} - ${src.location?.section || 'متن بخشنامه'}</div>
`;
sourcesContainer.appendChild(card);
});
}
async function ensureAudioContext() {
if (!audioContext) {
try {
audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 24000 });
} catch (e) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
console.log("AudioContext active at sampleRate:", audioContext.sampleRate);
}
if (audioContext.state === 'suspended') {
await audioContext.resume();
}
}
function playAudioChunk(arrayBuffer) {
if (!audioContext) return;
const int16 = new Int16Array(arrayBuffer);
const float32 = new Float32Array(int16.length);
for (let i = 0; i < int16.length; i++) {
float32[i] = int16[i] / 32768.0;
}
const buffer = audioContext.createBuffer(1, float32.length, 24000);
buffer.getChannelData(0).set(float32);
const source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
const now = audioContext.currentTime;
if (nextPlayTime < now) {
nextPlayTime = now;
}
source.start(nextPlayTime);
nextPlayTime += buffer.duration;
source.onended = () => {
const idx = activeAudioSources.indexOf(source);
if (idx !== -1) {
activeAudioSources.splice(idx, 1);
}
};
activeAudioSources.push(source);
}
// High quality window-averaging downsampler to guarantee 24000Hz PCM
function downsampleTo24k(buffer, inRate) {
if (inRate === 24000) return buffer;
const ratio = inRate / 24000;
const newLen = Math.round(buffer.length / ratio);
const result = new Float32Array(newLen);
let offsetBuffer = 0;
for (let i = 0; i < newLen; i++) {
const nextOffset = Math.round((i + 1) * ratio);
let sum = 0, count = 0;
for (let j = offsetBuffer; j < nextOffset && j < buffer.length; j++) {
sum += buffer[j];
count++;
}
result[i] = count > 0 ? (sum / count) : buffer[offsetBuffer];
offsetBuffer = nextOffset;
}
return result;
}
async function ensureConnection() {
if (isConnected && ws && ws.readyState === WebSocket.OPEN) return true;
return new Promise((resolve, reject) => {
setStatus('در حال اتصال به سرور...', 'connecting');
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const chosenVoice = voiceSelect.value || 'shimmer';
const wsUrl = `${protocol}//${window.location.host}/api/v1/voice/stream?voice=${chosenVoice}`;
ws = new WebSocket(wsUrl);
ws.binaryType = 'arraybuffer';
ws.onopen = async () => {
await ensureAudioContext();
setStatus('متصل شد (آماده)', 'connected');
isConnected = true;
resolve(true);
};
ws.onmessage = (event) => {
if (typeof event.data === 'string') {
const msg = JSON.parse(event.data);
if (msg.type === 'user_speech_started' || msg.type === 'turn_interrupted') {
stopAllAudio();
setStatus('شنیدن صدای شما...', 'listening');
onUserSpeechStart();
}
else if (msg.type === 'transcript') {
if (msg.role === 'user') {
onUserTranscriptReceived(msg.text, msg.status);
setStatus('در حال پاسخ...', 'connecting');
} else if (msg.role === 'assistant') {
if (msg.status === 'partial') {
onAiTranscriptReceived(msg.text, false);
} else {
onAiTranscriptReceived(msg.text, true);
setStatus('آماده (در حال گفتگو)', 'connected');
}
}
} else if (msg.type === 'sources') {
updateSources(msg.sources);
} else if (msg.type === 'error') {
alert('خطای ارائه‌دهنده: ' + (msg.error?.message || JSON.stringify(msg.error)));
}
} else if (event.data instanceof ArrayBuffer) {
playAudioChunk(event.data);
}
};
ws.onclose = () => {
stopSession();
};
ws.onerror = (err) => {
console.error(err);
stopSession();
reject(err);
};
});
}
async function initMicrophone() {
await ensureAudioContext();
mediaStream = await navigator.mediaDevices.getUserMedia({
audio: {
channelCount: 1,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
});
const source = audioContext.createMediaStreamSource(mediaStream);
scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1);
scriptProcessor.onaudioprocess = (e) => {
if (!isConnected || !ws || ws.readyState !== WebSocket.OPEN) return;
const inputData = e.inputBuffer.getChannelData(0);
const resampled = downsampleTo24k(inputData, audioContext.sampleRate);
const pcm16 = new Int16Array(resampled.length);
for (let i = 0; i < resampled.length; i++) {
let s = Math.max(-1, Math.min(1, resampled[i]));
pcm16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
}
ws.send(pcm16.buffer);
};
source.connect(scriptProcessor);
// Connect through a mute gain node (volume = 0) to avoid mic leaking into speakers
const muteGain = audioContext.createGain();
muteGain.gain.value = 0;
scriptProcessor.connect(muteGain);
muteGain.connect(audioContext.destination);
}
function stopMicrophone() {
micBtn.classList.remove('active');
if (mediaStream) { mediaStream.getTracks().forEach(t => t.stop()); mediaStream = null; }
if (scriptProcessor) { scriptProcessor.disconnect(); scriptProcessor = null; }
}
function stopSession() {
isConnected = false;
stopMicrophone();
stopAllAudio();
setStatus('قطع ارتباط', '');
if (ws) { ws.close(); ws = null; }
currentTurn = null;
}
async function toggleMic() {
if (mediaStream) {
stopMicrophone();
setStatus('میکروفون غیرفعال - وب‌سوکت باز', 'connected');
} else {
try {
await ensureConnection();
await initMicrophone();
micBtn.classList.add('active');
setStatus('میکروفون فعال (آماده شنیدن)', 'connected');
} catch (e) {
alert('خطا در دسترسی به میکروفون یا اتصال: ' + e.message);
}
}
}
async function sendTextMessage() {
const text = textInput.value.trim();
if (!text) return;
textInput.value = '';
await sendQuickText(text);
}
async function sendQuickText(text) {
await ensureConnection();
currentTurn = null; // Fresh turn for explicit message
onUserTranscriptReceived(text, 'completed');
ws.send(JSON.stringify({
type: 'user_text_message',
text: text
}));
}
function onVoiceChange() {
const chosen = voiceSelect.value;
if (isConnected && ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'update_voice',
voice: chosen
}));
}
}
micBtn.onclick = toggleMic;
</script>
</body>
</html>
"""
@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)