Accept /api/v1/live/sessions and /v1/live/sessions for reservations and streaming, plus the /v1/voice/sessions stream alias, for frontend development. Validation: Python AST parsing and git diff --check passed.
1172 lines
49 KiB
Python
1172 lines
49 KiB
Python
"""Universal Voice-to-Voice Mock Streaming Server.
|
||
|
||
Implements the exact Phase 0 -> Phase 1 -> Phase 2 -> Phase 3 Voice-to-Voice flow:
|
||
1. REST Setup:
|
||
- GET /api/v1/me -> csrf_token, user identity, sets rag_session cookie
|
||
- GET /api/v1/configuration -> capabilities.voice === true
|
||
- POST /api/v1/conversations -> creates voice conversation { id, mode: "voice" }
|
||
- POST /api/v1/voice/sessions -> creates voice session { session_id, stream_path, expires_at }
|
||
- POST /api/v1/voice/sessions/{id}/close -> closes session
|
||
2. WebSocket Stream:
|
||
- WSS /api/v1/voice/sessions/{id}/stream and /api/v1/voice/stream
|
||
- Emits session_ready: { input_audio: 16kHz PCM16, output_audio: 24kHz PCM16 }
|
||
- Accepts binary 16kHz PCM16 frames from client microphone
|
||
- Server VAD detects speech energy and turn completion
|
||
- Streams 24kHz PCM16 binary audio frames + JSON events (transcript, sources, turn_interrupted)
|
||
- Server-driven barge-in: detects user speech over assistant and emits turn_interrupted immediately.
|
||
3. Interactive In-Browser Reference Client at http://localhost:<port>/:
|
||
- Complete reference client executing the exact VoiceStreamService state machine:
|
||
IDLE -> STARTING -> LISTENING -> PROCESSING -> SPEAKING -> INTERRUPTED -> IDLE
|
||
- Visual audio orb and level meters.
|
||
|
||
Usage:
|
||
.venv\\Scripts\\python scripts/mock_stream_server.py
|
||
.venv\\Scripts\\python scripts/mock_stream_server.py --port 1322
|
||
"""
|
||
|
||
import argparse
|
||
import asyncio
|
||
from datetime import datetime, timezone, timedelta
|
||
import json
|
||
import math
|
||
import os
|
||
import struct
|
||
import sys
|
||
import uuid
|
||
from typing import Dict, List, Optional
|
||
|
||
# Ensure UTF-8 output on Windows consoles
|
||
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 fastapi import FastAPI, Request, Response, WebSocket, WebSocketDisconnect
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import HTMLResponse, JSONResponse
|
||
import uvicorn
|
||
|
||
app = FastAPI(
|
||
title="Universal Voice-to-Voice Mock Server",
|
||
description="Full implementation of RAG Phase 1 Voice-to-Voice streaming flow",
|
||
version="1.0.0"
|
||
)
|
||
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"],
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
# Simulated in-memory database
|
||
MOCK_USER = {
|
||
"id": "01000000-0000-4000-8000-000000000001",
|
||
"username": "demo.admin",
|
||
"email": "demo.admin@organization.local",
|
||
"role": "admin",
|
||
"organization_id": "02000000-0000-4000-8000-000000000001",
|
||
"is_enabled": True
|
||
}
|
||
|
||
CSRF_TOKEN = "mock-csrf-token-f8b1c4e2-9a3d-4c7b-b5e1-8f2a6d4c0e3b"
|
||
SESSIONS: Dict[str, dict] = {}
|
||
CONVERSATIONS: Dict[str, dict] = {}
|
||
|
||
PERSIAN_MOCK_TURNS = [
|
||
{
|
||
"user_transcript": "ساعات کاری شرکت در فصل تابستان به چه صورته؟",
|
||
"assistant_transcript": "سلام و درود. بر اساس بخشنامه رسمی سازمان، ساعات کاری اداری پرسنل در فصل تابستان از ساعت ۶:۰۰ صبح تا ۱۳:۰۰ بعدازظهر میباشد. واحدهای شیفتی، تأسیسات و حراست مطابق جدول شیفت خود فعالیت میکنند.",
|
||
"sources": [
|
||
{
|
||
"source_ref": "S1",
|
||
"document_id": "10000000-0000-4000-8000-000000000001",
|
||
"chunk_id": "30000000-0000-4000-8000-000000000001",
|
||
"title": "بخشنامه ساعات کاری تابستان",
|
||
"text": "ماده ۳: ساعات کاری کلیه پرسنل ستادی و اداری از ساعت ۶:۰۰ صبح لغایت ۱۳:۰۰ تعیین میگردد.",
|
||
"location": {"page": 1, "section": "ماده ۳"}
|
||
}
|
||
]
|
||
},
|
||
{
|
||
"user_transcript": "پرسنل شیفتی و حراست از چه ساعتی باید کارشون رو شروع کنند؟",
|
||
"assistant_transcript": "پرسنل شیفتی و نگهبانی حراست به صورت سه شیفت گردشکار دارند: شیفت صبح از ۷:۰۰ الی ۱۵:۰۰، شیفت عصر از ۱۵:۰۰ الی ۲۳:۰۰ و شیفت شب از ۲۳:۰۰ الی ۷:۰۰ صبح فردا انجام وظیفه مینمایند.",
|
||
"sources": [
|
||
{
|
||
"source_ref": "S2",
|
||
"document_id": "10000000-0000-4000-8000-000000000002",
|
||
"chunk_id": "30000000-0000-4000-8000-000000000002",
|
||
"title": "دستورالعمل نوبتکاری و شیفت حراست",
|
||
"text": "واحدهای نگهبانی و تأسیسات موظف به رعایت چرخه شیفتهای هشتساعته طبق جدول ماهانه میباشند.",
|
||
"location": {"page": 2, "section": "بند ۴"}
|
||
}
|
||
]
|
||
},
|
||
{
|
||
"user_transcript": "روند ثبت درخواست مرخصی استعلاجی چجوریه؟",
|
||
"assistant_transcript": "درخواست مرخصی استعلاجی از طریق پرتال منابع انسانی و با پیوست تصویر گواهی پزشک ثبت میشود. برای استعلاجیهای بیش از ۳ روز متوالی، تأییدیه کمیسیون پزشکی الزامی است.",
|
||
"sources": [
|
||
{
|
||
"source_ref": "S3",
|
||
"document_id": "10000000-0000-4000-8000-000000000003",
|
||
"chunk_id": "30000000-0000-4000-8000-000000000005",
|
||
"title": "آییننامه امور اداری و مرخصیها",
|
||
"text": "ثبت گواهی استعلاجی ظرف مدت ۴۸ ساعت الزامی است.",
|
||
"location": {"page": 5, "section": "ماده ۱۲"}
|
||
}
|
||
]
|
||
}
|
||
]
|
||
|
||
|
||
def generate_speech_pcm_frames(sample_rate: int = 24000, duration_seconds: float = 0.08, base_freq: float = 300.0) -> bytes:
|
||
"""Generate a realistic, soft synthetic speech formant PCM16 24kHz frame."""
|
||
num_samples = int(sample_rate * duration_seconds)
|
||
frame = bytearray()
|
||
for i in range(num_samples):
|
||
t = i / sample_rate
|
||
# Vocal formant harmonic combination
|
||
v1 = 0.4 * math.sin(2 * math.pi * base_freq * t)
|
||
v2 = 0.25 * math.sin(2 * math.pi * (base_freq * 1.8) * t)
|
||
v3 = 0.15 * math.sin(2 * math.pi * (base_freq * 2.6) * t)
|
||
env = math.sin(math.pi * (i / num_samples)) ** 0.5
|
||
val = int((v1 + v2 + v3) * env * 20000)
|
||
val = max(-32768, min(32767, val))
|
||
frame.extend(struct.pack("<h", val))
|
||
return bytes(frame)
|
||
|
||
|
||
def set_session_cookie(response: Response):
|
||
"""Ensure rag_session HttpOnly cookie is attached."""
|
||
response.set_cookie(
|
||
key="rag_session",
|
||
value="mock-rag-session-token-01000000-0000-4000-8000",
|
||
max_age=86400,
|
||
httponly=True,
|
||
samesite="lax",
|
||
secure=False,
|
||
path="/"
|
||
)
|
||
response.set_cookie(
|
||
key="csrf_token",
|
||
value=CSRF_TOKEN,
|
||
max_age=86400,
|
||
httponly=False,
|
||
samesite="lax",
|
||
path="/"
|
||
)
|
||
|
||
|
||
# ============================================================================
|
||
# Phase 1 REST Endpoints
|
||
# ============================================================================
|
||
|
||
@app.post("/api/v1/auth/login")
|
||
@app.post("/auth/login")
|
||
async def login(request: Request, response: Response):
|
||
"""Public login returning user + csrf_token and setting rag_session cookie."""
|
||
set_session_cookie(response)
|
||
now = datetime.now(timezone.utc)
|
||
return {
|
||
"user": MOCK_USER,
|
||
"csrf_token": CSRF_TOKEN,
|
||
"expires_at": (now + timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
}
|
||
|
||
|
||
@app.get("/api/v1/me")
|
||
@app.get("/me")
|
||
async def get_me(request: Request, response: Response):
|
||
"""GET /api/v1/me -> csrf_token, user identity (Phase 1, Step 2.1)."""
|
||
set_session_cookie(response)
|
||
now = datetime.now(timezone.utc)
|
||
return {
|
||
"user": MOCK_USER,
|
||
"csrf_token": CSRF_TOKEN,
|
||
"expires_at": (now + timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
}
|
||
|
||
|
||
@app.get("/api/v1/configuration")
|
||
@app.get("/configuration")
|
||
async def get_configuration(request: Request, response: Response):
|
||
"""GET /api/v1/configuration -> must have capabilities.voice === true (Phase 1, Step 2.2)."""
|
||
set_session_cookie(response)
|
||
return {
|
||
"revision": 1,
|
||
"assistant_name": "سامانه پاسخگوی صوتی اسناد و بخشنامهها",
|
||
"instruction": "پاسخگویی مستند و روان به زبان فارسی بر اساس مدارک معتبر سازمانی.",
|
||
"capabilities": {
|
||
"voice": True,
|
||
"text": True,
|
||
"captions": True,
|
||
"supported_upload_types": ["application/pdf", "text/markdown"],
|
||
"max_upload_bytes": 10485760
|
||
}
|
||
}
|
||
|
||
|
||
@app.post("/api/v1/conversations", status_code=201)
|
||
@app.post("/conversations", status_code=201)
|
||
async def create_conversation(request: Request, response: Response):
|
||
"""POST /api/v1/conversations -> body: { client_request_id, mode: "voice", title } -> id."""
|
||
set_session_cookie(response)
|
||
body = {}
|
||
try:
|
||
body = await request.json()
|
||
except Exception:
|
||
pass
|
||
|
||
conv_id = str(uuid.uuid4())
|
||
client_req_id = body.get("client_request_id", str(uuid.uuid4()))
|
||
mode = body.get("mode", "voice")
|
||
title = body.get("title", "مکالمه صوتی اسناد")
|
||
|
||
data = {
|
||
"id": conv_id,
|
||
"conversation_id": conv_id,
|
||
"client_request_id": client_req_id,
|
||
"mode": mode,
|
||
"title": title,
|
||
"status": "active",
|
||
"access_epoch": 1,
|
||
"created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
}
|
||
CONVERSATIONS[conv_id] = data
|
||
print(f"[REST] Created Conversation: {conv_id} (mode={mode})")
|
||
return data
|
||
|
||
|
||
@app.post("/api/v1/voice/sessions", status_code=201)
|
||
@app.post("/voice/sessions", status_code=201)
|
||
@app.post("/api/v1/live/sessions", status_code=201)
|
||
@app.post("/v1/live/sessions", status_code=201)
|
||
async def create_voice_session(request: Request, response: Response):
|
||
"""POST /api/v1/voice/sessions -> body: { conversation_id, client_request_id } -> session_id, stream_path."""
|
||
set_session_cookie(response)
|
||
body = {}
|
||
try:
|
||
body = await request.json()
|
||
except Exception:
|
||
pass
|
||
|
||
session_id = str(uuid.uuid4())
|
||
conv_id = body.get("conversation_id", str(uuid.uuid4()))
|
||
client_req_id = body.get("client_request_id", str(uuid.uuid4()))
|
||
|
||
now = datetime.now(timezone.utc)
|
||
expires_at = (now + timedelta(minutes=30)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
stream_path = f"/api/v1/voice/sessions/{session_id}/stream"
|
||
|
||
session_info = {
|
||
"session_id": session_id,
|
||
"conversation_id": conv_id,
|
||
"client_request_id": client_req_id,
|
||
"status": "connecting",
|
||
"stream_path": stream_path,
|
||
"expires_at": expires_at,
|
||
"poll_url": f"/api/v1/voice/sessions/{session_id}"
|
||
}
|
||
SESSIONS[session_id] = session_info
|
||
print(f"[REST] Created Voice Session V01: {session_id} -> stream_path: {stream_path}")
|
||
return session_info
|
||
|
||
|
||
@app.get("/api/v1/voice/sessions/{session_id}")
|
||
@app.get("/voice/sessions/{session_id}")
|
||
async def get_voice_session(session_id: str, response: Response):
|
||
"""V02: Poll state, diagnostics and recent retrieved sources."""
|
||
set_session_cookie(response)
|
||
session = SESSIONS.get(session_id) or {
|
||
"session_id": session_id,
|
||
"conversation_id": str(uuid.uuid4()),
|
||
"status": "connected",
|
||
"close_reason": None,
|
||
"expires_at": (datetime.now(timezone.utc) + timedelta(minutes=30)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
}
|
||
session["status"] = "connected"
|
||
session["recent_tool_results"] = [
|
||
{
|
||
"tool_call_id": f"call-{uuid.uuid4().hex[:6]}",
|
||
"status": "succeeded",
|
||
"created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||
"sources": PERSIAN_MOCK_TURNS[0]["sources"]
|
||
}
|
||
]
|
||
return session
|
||
|
||
|
||
@app.post("/api/v1/voice/sessions/{session_id}/close")
|
||
@app.post("/voice/sessions/{session_id}/close")
|
||
async def close_voice_session(session_id: str, response: Response):
|
||
"""Phase 3, Step 4: POST /api/v1/voice/sessions/{session_id}/close."""
|
||
set_session_cookie(response)
|
||
if session_id in SESSIONS:
|
||
SESSIONS[session_id]["status"] = "closed"
|
||
SESSIONS[session_id]["close_reason"] = "user_requested"
|
||
print(f"[REST] Closed Voice Session Phase 3: {session_id}")
|
||
return {
|
||
"session_id": session_id,
|
||
"status": "closed",
|
||
"close_reason": "user_requested"
|
||
}
|
||
|
||
|
||
# ============================================================================
|
||
# Phase 2 — Live Duplex WebSocket Loop
|
||
# ============================================================================
|
||
|
||
@app.websocket("/api/v1/voice/sessions/{session_id}/stream")
|
||
@app.websocket("/v1/voice/sessions/{session_id}/stream")
|
||
@app.websocket("/api/v1/live/sessions/{session_id}/stream")
|
||
@app.websocket("/v1/live/sessions/{session_id}/stream")
|
||
@app.websocket("/api/v1/voice/stream")
|
||
@app.websocket("/stream")
|
||
async def voice_stream_websocket(websocket: WebSocket, session_id: Optional[str] = None):
|
||
"""Phase 2: WebSocket duplex loop (16kHz PCM16 in, 24kHz PCM16 out + JSON events)."""
|
||
await websocket.accept()
|
||
sid = session_id or str(uuid.uuid4())
|
||
print(f"\n[WS CONNECTED] Session {sid} upgraded successfully")
|
||
|
||
# Step 3.2: Wait for server event: session_ready (16 kHz in / 24 kHz out / pcm_s16le / mono)
|
||
await websocket.send_json({
|
||
"type": "session_ready",
|
||
"session_id": sid,
|
||
"input_audio": {
|
||
"encoding": "pcm_s16le",
|
||
"sample_rate": 16000,
|
||
"channels": 1
|
||
},
|
||
"output_audio": {
|
||
"encoding": "pcm_s16le",
|
||
"sample_rate": 24000,
|
||
"channels": 1
|
||
}
|
||
})
|
||
print(f"[WS SENT] session_ready emitted (16kHz in / 24kHz out)")
|
||
|
||
turn_counter = 0
|
||
active_speaking_task: Optional[asyncio.Task] = None
|
||
user_speech_active = False
|
||
speech_frames_count = 0
|
||
silence_frames_count = 0
|
||
|
||
async def speak_assistant_turn(turn_idx: int):
|
||
"""Simulate assistant generating 24kHz PCM16 audio and streaming transcript words."""
|
||
try:
|
||
turn_data = PERSIAN_MOCK_TURNS[turn_idx % len(PERSIAN_MOCK_TURNS)]
|
||
turn_ref = f"live-turn-{turn_idx + 1}"
|
||
words = turn_data["assistant_transcript"].split(" ")
|
||
|
||
# 1. Emit sources event
|
||
if turn_data.get("sources"):
|
||
await websocket.send_json({
|
||
"type": "sources",
|
||
"turn_ref": turn_ref,
|
||
"tool_call_id": f"call-{uuid.uuid4().hex[:6]}",
|
||
"sources": turn_data["sources"]
|
||
})
|
||
await asyncio.sleep(0.05)
|
||
|
||
# 2. Stream words + 24kHz PCM audio frames
|
||
accumulated = ""
|
||
for w_i, word in enumerate(words):
|
||
accumulated += (word + " ")
|
||
|
||
# Partial transcript delta
|
||
await websocket.send_json({
|
||
"type": "transcript",
|
||
"turn_ref": turn_ref,
|
||
"role": "assistant",
|
||
"text": word + " ",
|
||
"status": "partial"
|
||
})
|
||
|
||
# Stream 24kHz audio frames
|
||
audio_frame = generate_speech_pcm_frames(
|
||
sample_rate=24000,
|
||
duration_seconds=0.08,
|
||
base_freq=240.0 + (w_i % 5) * 20.0
|
||
)
|
||
await websocket.send_bytes(audio_frame)
|
||
|
||
# Realistic conversational pace between words
|
||
await asyncio.sleep(0.08)
|
||
|
||
# 3. Final completed transcript
|
||
await websocket.send_json({
|
||
"type": "transcript",
|
||
"turn_ref": turn_ref,
|
||
"role": "assistant",
|
||
"text": accumulated.strip(),
|
||
"status": "completed"
|
||
})
|
||
print(f"[WS ASSISTANT TURN COMPLETED] {turn_ref}")
|
||
|
||
except asyncio.CancelledError:
|
||
# Server-driven barge-in
|
||
print(f"[WS BARGE-IN TRIGGERED] turn_interrupted sent to client!")
|
||
await websocket.send_json({
|
||
"type": "turn_interrupted",
|
||
"turn_ref": f"live-turn-{turn_idx + 1}",
|
||
"cancelled_tool_call_ids": []
|
||
})
|
||
raise
|
||
|
||
try:
|
||
while True:
|
||
message = await websocket.receive()
|
||
mtype = message.get("type")
|
||
|
||
if mtype == "websocket.disconnect":
|
||
break
|
||
|
||
# 1. Binary frames: 16 kHz PCM16 mono frames from client microphone
|
||
if "bytes" in message and message["bytes"]:
|
||
chunk = message["bytes"]
|
||
num_samples = len(chunk) // 2
|
||
|
||
if num_samples > 0:
|
||
samples = struct.unpack(f"<{num_samples}h", chunk[:num_samples*2])
|
||
# Calculate Root Mean Square energy for VAD
|
||
rms = math.sqrt(sum(s*s for s in samples) / num_samples)
|
||
|
||
# Simple energy threshold for speech detection
|
||
if rms > 300:
|
||
speech_frames_count += 1
|
||
silence_frames_count = 0
|
||
|
||
# If user spoke over assistant, trigger immediate barge-in!
|
||
if active_speaking_task and not active_speaking_task.done():
|
||
active_speaking_task.cancel()
|
||
active_speaking_task = None
|
||
|
||
if not user_speech_active and speech_frames_count >= 3:
|
||
user_speech_active = True
|
||
turn_ref = f"live-turn-{turn_counter + 1}"
|
||
# Emit partial user transcript
|
||
await websocket.send_json({
|
||
"type": "transcript",
|
||
"turn_ref": turn_ref,
|
||
"role": "user",
|
||
"text": "...",
|
||
"status": "partial"
|
||
})
|
||
else:
|
||
if user_speech_active:
|
||
silence_frames_count += 1
|
||
# Silence duration ~ 500ms (25 frames of 20ms) -> speech finished
|
||
if silence_frames_count >= 15:
|
||
user_speech_active = False
|
||
speech_frames_count = 0
|
||
silence_frames_count = 0
|
||
|
||
# Complete user transcript
|
||
turn_data = PERSIAN_MOCK_TURNS[turn_counter % len(PERSIAN_MOCK_TURNS)]
|
||
turn_ref = f"live-turn-{turn_counter + 1}"
|
||
await websocket.send_json({
|
||
"type": "transcript",
|
||
"turn_ref": turn_ref,
|
||
"role": "user",
|
||
"text": turn_data["user_transcript"],
|
||
"status": "completed"
|
||
})
|
||
|
||
# Start assistant speech response
|
||
active_speaking_task = asyncio.create_task(speak_assistant_turn(turn_counter))
|
||
turn_counter += 1
|
||
|
||
# 2. Text / JSON messages (e.g. quick test triggers)
|
||
elif "text" in message and message["text"]:
|
||
try:
|
||
payload = json.loads(message["text"])
|
||
ptype = payload.get("type")
|
||
|
||
if ptype == "user_text_message":
|
||
# If assistant was speaking, cancel
|
||
if active_speaking_task and not active_speaking_task.done():
|
||
active_speaking_task.cancel()
|
||
|
||
user_text = payload.get("text", "سؤال کاربر")
|
||
turn_ref = f"live-turn-{turn_counter + 1}"
|
||
await websocket.send_json({
|
||
"type": "transcript",
|
||
"turn_ref": turn_ref,
|
||
"role": "user",
|
||
"text": user_text,
|
||
"status": "completed"
|
||
})
|
||
active_speaking_task = asyncio.create_task(speak_assistant_turn(turn_counter))
|
||
turn_counter += 1
|
||
|
||
except Exception:
|
||
pass
|
||
|
||
except WebSocketDisconnect:
|
||
pass
|
||
except Exception as e:
|
||
print(f"[WS ERROR]: {e}")
|
||
finally:
|
||
if active_speaking_task and not active_speaking_task.done():
|
||
active_speaking_task.cancel()
|
||
print(f"[WS CLOSED] Session {sid} finished")
|
||
|
||
|
||
# ============================================================================
|
||
# Interactive In-Browser Reference Client (GET /)
|
||
# Executes the EXACT Phase 0 -> Phase 1 -> Phase 2 -> Phase 3 Flow
|
||
# ============================================================================
|
||
|
||
HTML_REFERENCE_CLIENT = """<!DOCTYPE html>
|
||
<html lang="fa" dir="rtl">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>شبیهساز مکالمه صوتی دوجانبه (Voice-to-Voice Mock Flow)</title>
|
||
<style>
|
||
:root {
|
||
--bg: #090d16;
|
||
--surface: #111827;
|
||
--surface-border: #1f2937;
|
||
--primary: #4f46e5;
|
||
--accent: #10b981;
|
||
--warning: #f59e0b;
|
||
--danger: #ef4444;
|
||
--text: #f9fafb;
|
||
--dim: #9ca3af;
|
||
}
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
body {
|
||
font-family: system-ui, -apple-system, Tahoma, Arial, sans-serif;
|
||
background: var(--bg);
|
||
color: var(--text);
|
||
padding: 1.5rem;
|
||
min-height: 100vh;
|
||
}
|
||
.container { max-width: 1200px; margin: 0 auto; }
|
||
header {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
margin-bottom: 1.5rem;
|
||
padding-bottom: 1rem;
|
||
border-bottom: 1px solid var(--surface-border);
|
||
flex-wrap: wrap;
|
||
gap: 1rem;
|
||
}
|
||
.flow-stepper {
|
||
display: flex;
|
||
gap: 0.5rem;
|
||
margin-bottom: 1.5rem;
|
||
overflow-x: auto;
|
||
padding-bottom: 0.5rem;
|
||
}
|
||
.step-pill {
|
||
background: rgba(255,255,255,0.04);
|
||
border: 1px solid var(--surface-border);
|
||
padding: 0.45rem 0.85rem;
|
||
border-radius: 9999px;
|
||
font-size: 0.78rem;
|
||
color: var(--dim);
|
||
white-space: nowrap;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 0.35rem;
|
||
}
|
||
.step-pill.done { border-color: var(--accent); color: var(--accent); background: rgba(16, 185, 129, 0.08); }
|
||
.step-pill.active { border-color: #38bdf8; color: #38bdf8; background: rgba(56, 189, 248, 0.1); font-weight: 600; }
|
||
|
||
.main-grid {
|
||
display: grid;
|
||
grid-template-columns: 1fr 360px;
|
||
gap: 1.5rem;
|
||
}
|
||
@media (max-width: 900px) { .main-grid { grid-template-columns: 1fr; } }
|
||
|
||
.card {
|
||
background: var(--surface);
|
||
border: 1px solid var(--surface-border);
|
||
border-radius: 14px;
|
||
padding: 1.25rem;
|
||
margin-bottom: 1.5rem;
|
||
}
|
||
.state-banner {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
padding: 0.85rem 1.25rem;
|
||
border-radius: 10px;
|
||
margin-bottom: 1.25rem;
|
||
background: rgba(255,255,255,0.03);
|
||
border: 1px solid var(--surface-border);
|
||
}
|
||
.state-badge {
|
||
font-size: 0.88rem;
|
||
font-weight: 700;
|
||
padding: 0.35rem 0.95rem;
|
||
border-radius: 9999px;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 0.4rem;
|
||
}
|
||
.state-idle { background: #374151; color: #e5e7eb; }
|
||
.state-listening { background: rgba(16, 185, 129, 0.2); color: var(--accent); border: 1px solid var(--accent); }
|
||
.state-processing { background: rgba(245, 158, 11, 0.2); color: var(--warning); border: 1px solid var(--warning); }
|
||
.state-speaking { background: rgba(99, 102, 241, 0.2); color: #818cf8; border: 1px solid #818cf8; }
|
||
.state-interrupted { background: rgba(239, 68, 68, 0.25); color: var(--danger); border: 1px solid var(--danger); }
|
||
|
||
/* Audio Visualizer Orb */
|
||
.orb-wrapper {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
padding: 1.5rem;
|
||
}
|
||
.orb {
|
||
width: 90px;
|
||
height: 90px;
|
||
border-radius: 50%;
|
||
background: radial-gradient(circle, #4f46e5 0%, #1e1b4b 70%);
|
||
box-shadow: 0 0 20px rgba(79, 70, 229, 0.4);
|
||
transition: transform 0.1s ease, box-shadow 0.1s ease;
|
||
}
|
||
.orb.speaking {
|
||
background: radial-gradient(circle, #60a5fa 0%, #1e3a8a 70%);
|
||
box-shadow: 0 0 35px rgba(96, 165, 250, 0.6);
|
||
animation: orbPulse 1.2s infinite;
|
||
}
|
||
.orb.listening {
|
||
background: radial-gradient(circle, #10b981 0%, #064e3b 70%);
|
||
box-shadow: 0 0 35px rgba(16, 185, 129, 0.5);
|
||
}
|
||
@keyframes orbPulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.15); } }
|
||
|
||
.chat-container {
|
||
height: 340px;
|
||
overflow-y: auto;
|
||
border: 1px solid var(--surface-border);
|
||
border-radius: 10px;
|
||
padding: 1rem;
|
||
background: rgba(0,0,0,0.3);
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 0.85rem;
|
||
margin-bottom: 1rem;
|
||
}
|
||
.row { display: flex; width: 100%; }
|
||
.row.user { justify-content: flex-start; }
|
||
.row.ai { justify-content: flex-end; }
|
||
.bubble {
|
||
max-width: 82%;
|
||
padding: 0.75rem 1.1rem;
|
||
border-radius: 12px;
|
||
font-size: 0.9rem;
|
||
line-height: 1.6;
|
||
}
|
||
.bubble.user { background: #1e3a8a; border: 1px solid #2563eb; color: #eff6ff; }
|
||
.bubble.ai { background: #1f2937; border: 1px solid #374151; color: #f3f4f6; }
|
||
.btn {
|
||
background: var(--primary);
|
||
color: #fff;
|
||
border: none;
|
||
padding: 0.7rem 1.4rem;
|
||
border-radius: 8px;
|
||
cursor: pointer;
|
||
font-size: 0.9rem;
|
||
font-weight: 600;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 0.4rem;
|
||
}
|
||
.btn.danger { background: var(--danger); }
|
||
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||
.source-card {
|
||
background: rgba(255,255,255,0.03);
|
||
border: 1px solid var(--surface-border);
|
||
border-radius: 8px;
|
||
padding: 0.75rem;
|
||
margin-bottom: 0.6rem;
|
||
font-size: 0.82rem;
|
||
}
|
||
.source-card h4 { color: #818cf8; margin-bottom: 0.25rem; }
|
||
.log-area {
|
||
background: #000;
|
||
padding: 0.75rem;
|
||
border-radius: 8px;
|
||
font-family: monospace;
|
||
font-size: 0.75rem;
|
||
color: #38bdf8;
|
||
height: 250px;
|
||
overflow-y: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="container">
|
||
<header>
|
||
<div>
|
||
<h1>پیادهسازی ماک جریان صوتی دوجانبه (Voice-to-Voice Flow)</h1>
|
||
<p style="color: var(--dim); font-size: 0.88rem; margin-top: 4px;">
|
||
اجرای گام به گام: لاگین → کوکی → <code>/me</code> → <code>/configuration</code> → ایجاد مکالمه → سشن صوتی → وبسوکت ۱۶/۲۴ کیلوهرتز → Barge-in → بستن تماس
|
||
</p>
|
||
</div>
|
||
<div id="connectionBadge" class="step-pill active">● آماده برای شروع</div>
|
||
</header>
|
||
|
||
<!-- Stepper tracking Phase 1 -> 2 -> 3 -->
|
||
<div class="flow-stepper">
|
||
<div class="step-pill" id="stepAuth">۱. احراز هویت و کوکی</div>
|
||
<div class="step-pill" id="stepMe">۲. GET /me & CSRF</div>
|
||
<div class="step-pill" id="stepConfig">۳. GET /configuration</div>
|
||
<div class="step-pill" id="stepConv">۴. ایجاد مکالمه (mode: voice)</div>
|
||
<div class="step-pill" id="stepSession">۵. رزرو نشست صوتی (V01)</div>
|
||
<div class="step-pill" id="stepWs">۶. وبسوکت و session_ready</div>
|
||
<div class="step-pill" id="stepDuplex">۷. مکالمه زنده و Barge-in</div>
|
||
</div>
|
||
|
||
<div class="main-grid">
|
||
<div>
|
||
<div class="card">
|
||
<div class="state-banner">
|
||
<div>
|
||
<span style="font-size: 0.82rem; color: var(--dim);">وضعیت کلاینت:</span>
|
||
<span class="state-badge state-idle" id="stateBadge">IDLE (آماده)</span>
|
||
</div>
|
||
<div style="display: flex; gap: 0.5rem;">
|
||
<button class="btn" id="startCallBtn" onclick="startVoiceFlow()">📞 شروع تماس صوتی (start())</button>
|
||
<button class="btn danger" id="endCallBtn" onclick="endVoiceFlow()" disabled>⏹ پایان تماس (end())</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="orb-wrapper">
|
||
<div class="orb" id="visualOrb"></div>
|
||
</div>
|
||
|
||
<div class="chat-container" id="chatContainer">
|
||
<div class="row ai">
|
||
<div class="bubble ai">
|
||
🤖 سلام! برای آغاز مکالمه صوتی دوجانبه دکمه «شروع تماس صوتی» را فشار دهید. تمام فلوهای REST و وبسوکت به ترتیب استاندارد اجرا خواهند شد.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display: flex; gap: 0.5rem;">
|
||
<input type="text" id="manualInput" placeholder="یا در حین تماس متنی بنویسید و ارسال کنید..." style="flex:1; background:rgba(255,255,255,0.05); border:1px solid var(--surface-border); border-radius:8px; padding:0.6rem 1rem; color:#fff;" onkeydown="if(event.key==='Enter') sendManualText()">
|
||
<button class="btn" onclick="sendManualText()">ارسال</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div>
|
||
<div class="card">
|
||
<h3 style="font-size: 0.95rem; margin-bottom: 0.75rem;">مدارک استنادشده (Sources)</h3>
|
||
<div id="sourcesBox">
|
||
<p style="color: var(--dim); font-size: 0.82rem;">هنوز استنادی ثبت نشده است.</p>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="card">
|
||
<h3 style="font-size: 0.95rem; margin-bottom: 0.75rem;">لاگ زنده وقایع (VoiceStreamService Logs)</h3>
|
||
<div class="log-area" id="logArea"></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<script>
|
||
// State Machine States: IDLE, LISTENING, PROCESSING, SPEAKING, INTERRUPTED
|
||
let clientState = 'IDLE';
|
||
let ws = null;
|
||
let audioContext = null;
|
||
let mediaStream = null;
|
||
let scriptProcessor = null;
|
||
let currentSessionId = null;
|
||
let csrfToken = null;
|
||
let activeSources = [];
|
||
let nextPlayTime = 0;
|
||
let currentAiBubble = null;
|
||
|
||
const stateBadge = document.getElementById('stateBadge');
|
||
const visualOrb = document.getElementById('visualOrb');
|
||
const startCallBtn = document.getElementById('startCallBtn');
|
||
const endCallBtn = document.getElementById('endCallBtn');
|
||
const chatContainer = document.getElementById('chatContainer');
|
||
const logArea = document.getElementById('logArea');
|
||
const sourcesBox = document.getElementById('sourcesBox');
|
||
|
||
function appendLog(action, detail) {
|
||
const time = new Date().toLocaleTimeString();
|
||
const div = document.createElement('div');
|
||
div.innerHTML = `<span style="color:#f59e0b;">[${time}]</span> <b>${action}</b> ${detail ? JSON.stringify(detail) : ''}`;
|
||
logArea.insertBefore(div, logArea.firstChild);
|
||
}
|
||
|
||
function setClientState(state) {
|
||
clientState = state;
|
||
stateBadge.className = 'state-badge state-' + state.toLowerCase();
|
||
stateBadge.innerText = state;
|
||
|
||
visualOrb.className = 'orb ' + (state === 'SPEAKING' ? 'speaking' : state === 'LISTENING' ? 'listening' : '');
|
||
|
||
if (state === 'INTERRUPTED') {
|
||
// Brief flash after barge-in (~150 ms) -> back to LISTENING
|
||
setTimeout(() => {
|
||
if (clientState === 'INTERRUPTED') {
|
||
setClientState('LISTENING');
|
||
}
|
||
}, 150);
|
||
}
|
||
}
|
||
|
||
function stopPlayback() {
|
||
nextPlayTime = 0;
|
||
while (activeSources.length > 0) {
|
||
const s = activeSources.pop();
|
||
try { s.stop(0); s.disconnect(); } catch(e) {}
|
||
}
|
||
}
|
||
|
||
function playAudio24k(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 = activeSources.indexOf(source);
|
||
if (idx !== -1) activeSources.splice(idx, 1);
|
||
if (activeSources.length === 0 && clientState === 'SPEAKING') {
|
||
setClientState('LISTENING');
|
||
}
|
||
};
|
||
activeSources.push(source);
|
||
}
|
||
|
||
// Downsample input audio to 16 kHz for the capture worklet/processor
|
||
function downsampleTo16k(input, inSampleRate) {
|
||
if (inSampleRate === 16000) return input;
|
||
const ratio = inSampleRate / 16000;
|
||
const newLen = Math.round(input.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 < input.length; j++) {
|
||
sum += input[j]; count++;
|
||
}
|
||
result[i] = count > 0 ? (sum / count) : input[offsetBuffer];
|
||
offsetBuffer = nextOffset;
|
||
}
|
||
return result;
|
||
}
|
||
|
||
// ====================================================================
|
||
// Phase 1 — Start the call (VoiceStreamService.start())
|
||
// ====================================================================
|
||
async function startVoiceFlow() {
|
||
try {
|
||
startCallBtn.disabled = true;
|
||
setClientState('STARTING');
|
||
appendLog('Phase 1: Starting VoiceStreamService');
|
||
|
||
// 1. Mic + audio engine setup
|
||
audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 24000 });
|
||
if (audioContext.state === 'suspended') await audioContext.resume();
|
||
|
||
mediaStream = await navigator.mediaDevices.getUserMedia({
|
||
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }
|
||
});
|
||
appendLog('Audio Engine Ready', 'Mic permission granted');
|
||
document.getElementById('stepAuth').classList.add('done');
|
||
|
||
// 2. REST Setup
|
||
// 2.1 GET /api/v1/me -> csrf_token, user identity
|
||
appendLog('REST', 'GET /api/v1/me');
|
||
const meRes = await fetch('/api/v1/me', { credentials: 'include' });
|
||
const meData = await meRes.json();
|
||
csrfToken = meData.csrf_token;
|
||
document.getElementById('stepMe').classList.add('done');
|
||
|
||
// 2.2 GET /api/v1/configuration -> capabilities.voice === true
|
||
appendLog('REST', 'GET /api/v1/configuration');
|
||
const configRes = await fetch('/api/v1/configuration', { credentials: 'include' });
|
||
const configData = await configRes.json();
|
||
if (!configData.capabilities?.voice) {
|
||
throw new Error('Voice capability is disabled in configuration');
|
||
}
|
||
document.getElementById('stepConfig').classList.add('done');
|
||
|
||
// 2.3 POST /api/v1/conversations -> { mode: "voice" } -> id
|
||
appendLog('REST', 'POST /api/v1/conversations');
|
||
const convRes = await fetch('/api/v1/conversations', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken },
|
||
credentials: 'include',
|
||
body: JSON.stringify({ mode: 'voice', title: 'مکالمه صوتی' })
|
||
});
|
||
const convData = await convRes.json();
|
||
const conversationId = convData.id;
|
||
document.getElementById('stepConv').classList.add('done');
|
||
|
||
// 2.4 POST /api/v1/voice/sessions -> session_id, stream_path
|
||
appendLog('REST', 'POST /api/v1/voice/sessions');
|
||
const sessionRes = await fetch('/api/v1/voice/sessions', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken },
|
||
credentials: 'include',
|
||
body: JSON.stringify({ conversation_id: conversationId })
|
||
});
|
||
const sessionData = await sessionRes.json();
|
||
currentSessionId = sessionData.session_id;
|
||
const streamPath = sessionData.stream_path;
|
||
document.getElementById('stepSession').classList.add('done');
|
||
|
||
// 3. WebSocket Setup
|
||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||
const wsUrl = `${protocol}//${window.location.host}${streamPath}`;
|
||
appendLog('WebSocket Connecting', wsUrl);
|
||
|
||
ws = new WebSocket(wsUrl);
|
||
ws.binaryType = 'arraybuffer';
|
||
|
||
ws.onopen = () => {
|
||
appendLog('WebSocket Connected', 'Waiting for session_ready...');
|
||
};
|
||
|
||
ws.onmessage = (event) => {
|
||
if (typeof event.data === 'string') {
|
||
const msg = JSON.parse(event.data);
|
||
|
||
// 3.3 session_ready event received
|
||
if (msg.type === 'session_ready') {
|
||
appendLog('Event: session_ready', msg);
|
||
document.getElementById('stepWs').classList.add('done');
|
||
document.getElementById('stepDuplex').classList.add('done');
|
||
|
||
// Ready for user speech!
|
||
setClientState('LISTENING');
|
||
endCallBtn.disabled = false;
|
||
|
||
// Start mic forwarding over the socket (16kHz PCM16 binary frames)
|
||
startMicStreaming();
|
||
}
|
||
// Transcript event
|
||
else if (msg.type === 'transcript') {
|
||
appendLog('Event: transcript', { role: msg.role, text: msg.text, status: msg.status });
|
||
if (msg.role === 'user') {
|
||
if (msg.status === 'completed') {
|
||
setClientState('PROCESSING');
|
||
renderUserBubble(msg.text);
|
||
}
|
||
} else if (msg.role === 'assistant') {
|
||
setClientState('SPEAKING');
|
||
renderAiBubble(msg.text, msg.status);
|
||
}
|
||
}
|
||
// Sources event
|
||
else if (msg.type === 'sources') {
|
||
appendLog('Event: sources', msg.sources);
|
||
renderSources(msg.sources);
|
||
}
|
||
// Barge-in: turn_interrupted
|
||
else if (msg.type === 'turn_interrupted') {
|
||
appendLog('Barge-in: turn_interrupted', 'Flushing playback immediately!');
|
||
stopPlayback();
|
||
setClientState('INTERRUPTED');
|
||
}
|
||
} else if (event.data instanceof ArrayBuffer) {
|
||
// Binary 24kHz PCM16 audio frame received -> send to playback
|
||
playAudio24k(event.data);
|
||
}
|
||
};
|
||
|
||
ws.onclose = () => {
|
||
appendLog('WebSocket Closed');
|
||
endVoiceFlow();
|
||
};
|
||
|
||
} catch (err) {
|
||
alert('خطا در اجرای فلو: ' + err.message);
|
||
appendLog('Error', err.message);
|
||
endVoiceFlow();
|
||
}
|
||
}
|
||
|
||
// Capture mic, downsample to 16kHz, send binary PCM16 frames
|
||
function startMicStreaming() {
|
||
const source = audioContext.createMediaStreamSource(mediaStream);
|
||
scriptProcessor = audioContext.createScriptProcessor(1024, 1, 1);
|
||
|
||
scriptProcessor.onaudioprocess = (e) => {
|
||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
||
const inputData = e.inputBuffer.getChannelData(0);
|
||
const down16k = downsampleTo16k(inputData, audioContext.sampleRate);
|
||
const pcm16 = new Int16Array(down16k.length);
|
||
for (let i = 0; i < down16k.length; i++) {
|
||
let s = Math.max(-1, Math.min(1, down16k[i]));
|
||
pcm16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
|
||
}
|
||
// Forward binary-only frame
|
||
ws.send(pcm16.buffer);
|
||
};
|
||
|
||
source.connect(scriptProcessor);
|
||
// Mute loopback
|
||
const mute = audioContext.createGain();
|
||
mute.gain.value = 0;
|
||
scriptProcessor.connect(mute);
|
||
mute.connect(audioContext.destination);
|
||
}
|
||
|
||
function renderUserBubble(text) {
|
||
const row = document.createElement('div');
|
||
row.className = 'row user';
|
||
row.innerHTML = `<div class="bubble user">👤 ${text}</div>`;
|
||
chatContainer.appendChild(row);
|
||
chatContainer.scrollTop = chatContainer.scrollHeight;
|
||
currentAiBubble = null;
|
||
}
|
||
|
||
function renderAiBubble(text, status) {
|
||
if (!currentAiBubble) {
|
||
const row = document.createElement('div');
|
||
row.className = 'row ai';
|
||
currentAiBubble = document.createElement('div');
|
||
currentAiBubble.className = 'bubble ai';
|
||
row.appendChild(currentAiBubble);
|
||
chatContainer.appendChild(row);
|
||
}
|
||
if (status === 'partial') {
|
||
currentAiBubble.innerText += text;
|
||
} else {
|
||
currentAiBubble.innerText = text;
|
||
currentAiBubble = null;
|
||
}
|
||
chatContainer.scrollTop = chatContainer.scrollHeight;
|
||
}
|
||
|
||
function renderSources(sources) {
|
||
sourcesBox.innerHTML = '';
|
||
if (!sources || !sources.length) {
|
||
sourcesBox.innerHTML = '<p style="color:var(--dim); font-size:0.82rem;">بدون استناد.</p>';
|
||
return;
|
||
}
|
||
sources.forEach(s => {
|
||
const card = document.createElement('div');
|
||
card.className = 'source-card';
|
||
card.innerHTML = `<h4>${s.title}</h4><p>${s.text}</p>`;
|
||
sourcesBox.appendChild(card);
|
||
});
|
||
}
|
||
|
||
function sendManualText() {
|
||
const input = document.getElementById('manualInput');
|
||
const val = input.value.trim();
|
||
if (!val || !ws || ws.readyState !== WebSocket.OPEN) return;
|
||
input.value = '';
|
||
ws.send(JSON.stringify({ type: 'user_text_message', text: val }));
|
||
}
|
||
|
||
// ====================================================================
|
||
// Phase 3 — End the call (end() / teardown)
|
||
// ====================================================================
|
||
async function endVoiceFlow() {
|
||
appendLog('Phase 3: Teardown and end()');
|
||
|
||
// 1 & 2. Stop mic & close WS
|
||
if (scriptProcessor) { scriptProcessor.disconnect(); scriptProcessor = null; }
|
||
if (mediaStream) { mediaStream.getTracks().forEach(t => t.stop()); mediaStream = null; }
|
||
if (ws) { ws.close(); ws = null; }
|
||
|
||
// 3. Stop audio engine & playback
|
||
stopPlayback();
|
||
if (audioContext && audioContext.state !== 'closed') {
|
||
audioContext.close();
|
||
audioContext = null;
|
||
}
|
||
|
||
// 4. POST /api/v1/voice/sessions/{session_id}/close (best effort)
|
||
if (currentSessionId) {
|
||
try {
|
||
await fetch(`/api/v1/voice/sessions/${currentSessionId}/close`, {
|
||
method: 'POST',
|
||
headers: { 'X-CSRF-Token': csrfToken || '' },
|
||
credentials: 'include'
|
||
});
|
||
appendLog('REST', `Closed session ${currentSessionId}`);
|
||
} catch(e) {}
|
||
currentSessionId = null;
|
||
}
|
||
|
||
// 5 & 6. Reset state to IDLE
|
||
setClientState('IDLE');
|
||
startCallBtn.disabled = false;
|
||
endCallBtn.disabled = true;
|
||
|
||
// Reset steppers
|
||
document.querySelectorAll('.step-pill').forEach(p => p.classList.remove('done'));
|
||
appendLog('Call Ended', 'State = IDLE, connection = disconnected');
|
||
}
|
||
</script>
|
||
</body>
|
||
</html>
|
||
"""
|
||
|
||
|
||
@app.get("/", response_class=HTMLResponse)
|
||
@app.get("/voice-flow", response_class=HTMLResponse)
|
||
async def serve_reference_ui(request: Request, response: Response):
|
||
"""Serve the complete interactive Phase 0 -> Phase 3 reference client."""
|
||
set_session_cookie(response)
|
||
return HTMLResponse(content=HTML_REFERENCE_CLIENT)
|
||
|
||
|
||
# Wildcard fallback for any other unexpected requests
|
||
@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"])
|
||
async def catch_all(request: Request, full_path: str, response: Response):
|
||
set_session_cookie(response)
|
||
print(f"[REST CATCH-ALL] {request.method} /{full_path} -> 200 OK")
|
||
return {"status": "ok", "path": f"/{full_path}"}
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description="Voice-to-Voice Mock Server")
|
||
parser.add_argument("--port", type=int, default=int(os.getenv("PORT", "1322")), help="Port to listen on (default: 1322)")
|
||
parser.add_argument("--host", type=str, default="0.0.0.0", help="Host address (default: 0.0.0.0)")
|
||
args = parser.parse_args()
|
||
|
||
print("\n" + "="*65)
|
||
print(" 🚀 Universal Voice-to-Voice Mock Server Running")
|
||
print(f" 🌐 Interactive Reference Flow: http://localhost:{args.port}/")
|
||
print(f" 👤 REST Identity (/me): http://localhost:{args.port}/api/v1/me")
|
||
print(f" ⚙️ Config (/configuration): http://localhost:{args.port}/api/v1/configuration")
|
||
print(f" 💬 Conversations: http://localhost:{args.port}/api/v1/conversations")
|
||
print(f" 🎙️ Voice Sessions: http://localhost:{args.port}/api/v1/voice/sessions")
|
||
print(f" 🔌 WebSocket Stream: ws://localhost:{args.port}/api/v1/voice/stream")
|
||
print("="*65 + "\n")
|
||
|
||
uvicorn.run(app, host=args.host, port=args.port)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|