From 07245cd5cac65cff92e99ef08e49ef0c13178829 Mon Sep 17 00:00:00 2001 From: amirhosein mazaheri Date: Thu, 8 Oct 2026 18:08:03 +0330 Subject: [PATCH] chore(dev): add standalone voice stream mock harness Add an isolated FastAPI mock with synthetic PCM, fixture transcripts and sources, simulated sessions and a browser reference client. Preserve the supplied development harness unchanged; it does not establish production voice, real-provider or browser acceptance. Validation: Python AST parse and CLI help passed. Staged whitespace check reports four existing whitespace-only lines in the embedded HTML. --- scripts/mock_stream_server.py | 1166 +++++++++++++++++++++++++++++++++ 1 file changed, 1166 insertions(+) create mode 100644 scripts/mock_stream_server.py diff --git a/scripts/mock_stream_server.py b/scripts/mock_stream_server.py new file mode 100644 index 0000000..633135c --- /dev/null +++ b/scripts/mock_stream_server.py @@ -0,0 +1,1166 @@ +"""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:/: + - 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(" 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) +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("/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 = """ + + + + + شبیه‌ساز مکالمه صوتی دوجانبه (Voice-to-Voice Mock Flow) + + + +
+
+
+

پیاده‌سازی ماک جریان صوتی دوجانبه (Voice-to-Voice Flow)

+

+ اجرای گام به گام: لاگین → کوکی → /me → /configuration → ایجاد مکالمه → سشن صوتی → وب‌سوکت ۱۶/۲۴ کیلوهرتز → Barge-in → بستن تماس +

+
+
● آماده برای شروع
+
+ + +
+
۱. احراز هویت و کوکی
+
۲. GET /me & CSRF
+
۳. GET /configuration
+
۴. ایجاد مکالمه (mode: voice)
+
۵. رزرو نشست صوتی (V01)
+
۶. وب‌سوکت و session_ready
+
۷. مکالمه زنده و Barge-in
+
+ +
+
+
+
+
+ وضعیت کلاینت: + IDLE (آماده) +
+
+ + +
+
+ +
+
+
+ +
+
+
+ 🤖 سلام! برای آغاز مکالمه صوتی دوجانبه دکمه «شروع تماس صوتی» را فشار دهید. تمام فلوهای REST و وب‌سوکت به ترتیب استاندارد اجرا خواهند شد. +
+
+
+ +
+ + +
+
+
+ +
+
+

مدارک استنادشده (Sources)

+
+

هنوز استنادی ثبت نشده است.

+
+
+ +
+

لاگ زنده وقایع (VoiceStreamService Logs)

+
+
+
+
+
+ + + + +""" + + +@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()