#!/usr/bin/env python3 # -*- coding: utf-8 -*- #==================================================================================== # Public Proxy #==================================================================================== import os import asyncio import json import uuid import struct import time from websockets.client import connect from fastapi import FastAPI, WebSocket, WebSocketDisconnect, File, UploadFile, Form from fastapi.responses import HTMLResponse, JSONResponse import httpx from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit from datetime import datetime, timedelta, timezone import logging import uvicorn # for MongoDB and HF Dataset from motor.motor_asyncio import AsyncIOMotorClient from huggingface_hub import HfApi #------------------------------- # Config #------------------------------- PRIVATE_WS = os.environ.get("PRIVATE_WS", "").rstrip('/') # backend URL INTERNAL_API_KEY = os.environ.get("INTERNAL_API_KEY", "") HF_TOKEN = os.environ.get("HF_TOKEN", "") HF_DATASET_TOKEN = os.environ.get("HF_DATASET_TOKEN", "") MAX_CLIENTS = int(os.environ.get("MAX_CLIENTS", 10)) PUBLIC_URL = os.environ.get("PUBLIC_URL", "").rstrip('/') KEEPALIVE_INTERVAL_SECONDS = max(60, int(os.environ.get("KEEPALIVE_INTERVAL_SECONDS", "600"))) KEEPALIVE_RETRIES = max(1, int(os.environ.get("KEEPALIVE_RETRIES", "4"))) WS_CONNECT_RETRIES = max(1, min(3, int(os.environ.get("WS_CONNECT_RETRIES", "3")))) MAX_UPLOAD_BYTES = max(1024 * 1024, int(os.environ.get("MAX_UPLOAD_BYTES", str(25 * 1024 * 1024)))) # MongoDB setup MONGO_URI = os.environ.get("MONGO_URI", "") HF_DATASET_REPO = os.environ.get("HF_DATASET_REPO", "") # name/runtime_audio DB_NAME = "ngt_runtime_db" mongo_client = None db = None database_ready = False active_clients = 0 clients_lock = asyncio.Lock() keepalive_task = None backend_probe = {"alive": False, "ready": False, "http_status": None, "checked_at": None, "checked_monotonic": 0.0} #--------------------------------------- # Taipei Time Logging Configuration #--------------------------------------- def get_taipei_time(): return datetime.now(timezone(timedelta(hours=8))) class TaipeiFormatter(logging.Formatter): def formatTime(self, record, datefmt=None): dt = get_taipei_time() return dt.strftime(datefmt or "%Y-%m-%d %H:%M:%S") def setup_logging(): # modify Uvicorn logging format log_config = uvicorn.config.LOGGING_CONFIG log_format = "[%(asctime)s] %(levelname)s: %(message)s" log_config["formatters"]["default"]["fmt"] = log_format log_config["formatters"]["access"]["fmt"] = "[%(asctime)s] %(levelname)s: %(client_addr)s - \"%(request_line)s\" %(status_code)s" # logging use taipei time formatter = TaipeiFormatter(log_format) for name in ["uvicorn", "uvicorn.error", "uvicorn.access"]: l = logging.getLogger(name) for handler in l.handlers: handler.setFormatter(formatter) def get_time_str(): return get_taipei_time().strftime("%Y-%m-%d %H:%M:%S") #--------------------------------------- # Client classifier #--------------------------------------- def classify_client(headers): ua = headers.get("user-agent", "") auth = headers.get("authorization", "") if "Android" in ua or "AndroidApp" in ua: return "ANDROID" if auth.startswith("Bearer "): return "KEEPALIVE" return "WEB" #--------------------------------------- # Keepalive Task (Backend + Self) #--------------------------------------- def private_http_base(): if not PRIVATE_WS: return "" parts = urlsplit(PRIVATE_WS) scheme = {"wss": "https", "ws": "http"}.get(parts.scheme.lower(), parts.scheme) path = parts.path.rstrip("/") if path.endswith("/ws/audio"): path = path[:-len("/ws/audio")] return urlunsplit((scheme, parts.netloc, path, "", "")).rstrip("/") def private_websocket_url(): parts = urlsplit(PRIVATE_WS) scheme = {"https": "wss", "http": "ws"}.get(parts.scheme.lower(), parts.scheme) path = parts.path.rstrip("/") if not path.endswith("/ws/audio"): path += "/ws/audio" query = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True) if k != "api_key"] return urlunsplit((scheme, parts.netloc, path, urlencode(query), "")) async def get_with_retries(client, url, headers=None, label="Space"): last_response = None for attempt in range(1, KEEPALIVE_RETRIES + 1): try: response = await client.get(url, headers=headers, timeout=20) last_response = response if response.status_code < 500 and response.status_code != 429: return response print(f"[{get_time_str()}] [Proxy][KEEPALIVE] {label} returned HTTP {response.status_code} (attempt {attempt}/{KEEPALIVE_RETRIES})") except httpx.RequestError as e: print(f"[{get_time_str()}] [Proxy][KEEPALIVE] {label} request failed ({type(e).__name__}, attempt {attempt}/{KEEPALIVE_RETRIES})") if attempt < KEEPALIVE_RETRIES: await asyncio.sleep(min(30, 2 ** attempt)) return last_response def response_payload(response): if response is None: return {} try: payload = response.json() return payload if isinstance(payload, dict) else {} except (ValueError, json.JSONDecodeError): return {} async def keep_alive_loop(): global backend_probe, database_ready if not PRIVATE_WS: print(f"[{get_time_str()}] [Proxy][KEEPALIVE] PRIVATE_WS is not configured; backend checks are disabled.") backend_base = private_http_base() headers = { "Authorization": f"Bearer {HF_TOKEN}", "User-Agent": "Mozilla/5.0 (compatible; FeedSafeHealthCheck/1.0)", } async with httpx.AsyncClient(follow_redirects=False) as client: while True: if backend_base and HF_TOKEN: alive_response = await get_with_retries(client, backend_base + "/healthz", headers, "Private Space liveness") ready_response = await get_with_retries(client, backend_base + "/readyz", headers, "Private Space readiness") alive_body = response_payload(alive_response) ready_body = response_payload(ready_response) alive = alive_response is not None and alive_response.status_code == 200 and alive_body.get("status") == "alive" ready = ready_response is not None and ready_response.status_code == 200 and ready_body.get("status") == "ready" status = ready_response.status_code if ready_response is not None else ( alive_response.status_code if alive_response is not None else None ) backend_probe = { "alive": alive, "ready": ready, "http_status": status, "checked_at": get_time_str(), "checked_monotonic": time.monotonic(), } print(f"[{get_time_str()}] [Proxy][KEEPALIVE] Private Space alive={alive}, ready={ready}, HTTP={status}") else: backend_probe = { "alive": False, "ready": False, "http_status": None, "checked_at": get_time_str(), "checked_monotonic": time.monotonic(), } await refresh_database_health() # This self-check is best-effort. An independent external monitor should # also request PUBLIC_URL/healthz because this task stops with the Space. if PUBLIC_URL: self_response = await get_with_retries(client, PUBLIC_URL + "/healthz", label="Public Space liveness") self_status = self_response.status_code if self_response is not None else None print(f"[{get_time_str()}] [Proxy][KEEPALIVE] Public Space HTTP={self_status}") else: print(f"[{get_time_str()}] [Proxy][KEEPALIVE] PUBLIC_URL is not configured; self-check skipped.") await asyncio.sleep(KEEPALIVE_INTERVAL_SECONDS) async def refresh_database_health(): """Check MongoDB and recreate the client after a transient startup failure.""" global mongo_client, db, database_ready if not MONGO_URI: database_ready = False return if mongo_client is None: mongo_client = AsyncIOMotorClient(MONGO_URI, serverSelectionTimeoutMS=5000) try: await mongo_client.admin.command("ping") db = mongo_client[DB_NAME] database_ready = True except Exception as e: database_ready = False print(f"[{get_time_str()}] [Proxy] MongoDB health check failed ({type(e).__name__})") #--------------------------------------- # FastAPI App #--------------------------------------- app = FastAPI() @app.on_event("startup") async def startup_event(): global keepalive_task setup_logging() await refresh_database_health() if database_ready: print(f"[{get_time_str()}] [Proxy] DB connected!") keepalive_task = asyncio.create_task(keep_alive_loop(), name="space-keepalive") @app.on_event("shutdown") async def shutdown_event(): global keepalive_task if keepalive_task is not None: keepalive_task.cancel() await asyncio.gather(keepalive_task, return_exceptions=True) keepalive_task = None if mongo_client: mongo_client.close() # Serve Frontend UI @app.get("/") async def index(): return { "status": "Proxy is running", "time": get_time_str(), "backend_ready": backend_probe["ready"], "database_ready": database_ready, } @app.get("/healthz") async def liveness(): """Return 200 while the public proxy process is serving requests.""" return {"status": "alive", "time": get_time_str()} @app.get("/readyz") async def readiness(): """Report inference readiness; dataset storage has a separate health endpoint.""" if not PRIVATE_WS or not INTERNAL_API_KEY or not HF_TOKEN: return JSONResponse(status_code=503, content={"status": "not_ready", "reason": "proxy_config_missing"}) probe_age = time.monotonic() - backend_probe["checked_monotonic"] probe_fresh = probe_age <= max(120, KEEPALIVE_INTERVAL_SECONDS + 60) if not backend_probe["ready"] or not probe_fresh: return JSONResponse( status_code=503, content={ "status": "not_ready", "inference_ready": False, "backend_alive": backend_probe["alive"], "probe_fresh": probe_fresh, "last_check": backend_probe["checked_at"], }, ) return {"status": "ready", "inference_ready": True, "last_check": backend_probe["checked_at"]} @app.get("/upload-readyz") async def upload_readiness(): """Report whether nurse-labeled recordings can be persisted.""" ready = bool(database_ready and db is not None and HF_DATASET_TOKEN and HF_DATASET_REPO) if not ready: return JSONResponse( status_code=503, content={ "status": "not_ready", "upload_ready": False, "database_ready": database_ready, "dataset_storage_configured": bool(HF_DATASET_TOKEN and HF_DATASET_REPO), }, ) return {"status": "ready", "upload_ready": True} @app.get("/ui") async def ui(): if os.path.exists("index.html"): with open("index.html", "r", encoding="utf-8") as f: return HTMLResponse(f.read()) return "index.html not found" def normalize_uploaded_wav(data: bytes, preferred_channel: int): """Validate an Android-supported PCM/float WAV and save the inference channel as mono.""" if len(data) < 44 or data[:4] != b"RIFF" or data[8:12] != b"WAVE": raise ValueError("audio_file must be a valid RIFF/WAVE file") riff_size = struct.unpack_from(" len(data) or riff_end < 44: raise ValueError("audio_file has an invalid RIFF size") fmt = None audio_data = None offset = 12 while offset + 8 <= riff_end: chunk_id = data[offset:offset + 4] chunk_size = struct.unpack_from(" riff_end: raise ValueError("audio_file contains a truncated WAV chunk") chunk = data[chunk_start:chunk_end] if chunk_id == b"fmt ": if chunk_size < 16: raise ValueError("audio_file has an incomplete format chunk") encoding, channels, sample_rate, byte_rate, block_align, bits = struct.unpack_from( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # upload audio file to HF Datasets #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> audio_url = "" try: file_bytes = await audio_file.read(MAX_UPLOAD_BYTES + 1) if not file_bytes: return JSONResponse(status_code=400, content={"status": "error", "message": "audio file is empty"}) if len(file_bytes) > MAX_UPLOAD_BYTES: return JSONResponse(status_code=413, content={"status": "error", "message": "audio file exceeds upload limit"}) try: preferred_channel = 1 if device_info.startswith("Tag_CH1_live_stream_") else 0 file_bytes, audio_metadata = normalize_uploaded_wav(file_bytes, preferred_channel) except ValueError as e: return JSONResponse(status_code=400, content={"status": "error", "message": str(e)}) except struct.error: return JSONResponse(status_code=400, content={"status": "error", "message": "audio_file has an invalid WAV structure"}) unique_id = uuid.uuid4().hex safe_filename = f"{unique_id}.wav" def upload_to_hf(): api = HfApi(token=HF_DATASET_TOKEN) api.upload_file( path_or_fileobj=file_bytes, path_in_repo=f"audio/{safe_filename}", repo_id=HF_DATASET_REPO, repo_type="dataset" ) return f"https://huggingface.co/datasets/{HF_DATASET_REPO}/resolve/main/audio/{safe_filename}" audio_url = await asyncio.to_thread(upload_to_hf) except Exception as e: print(f"[{get_time_str()}] [Error] HF upload failed ({type(e).__name__})") return JSONResponse(status_code=502, content={"status": "error", "message": "file upload failed"}) #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # write record to MongoDB #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> document = { "sid": sid, "nurse_label": nurse_label, "ai_prediction": ai_prediction, "ai_confidence": ai_confidence, "audio_url": audio_url, "audio_sample_rate_hz": audio_metadata["sample_rate_hz"], "audio_original_channels": audio_metadata["original_channels"], "audio_stored_channels": audio_metadata["stored_channels"], "audio_channel_selection": audio_metadata["channel_selection"], "audio_sample_width_bytes": audio_metadata["sample_width_bytes"], "audio_bits_per_sample": audio_metadata["bits_per_sample"], "audio_encoding": audio_metadata["encoding"], "audio_duration_seconds": audio_metadata["duration_seconds"], "device_info": device_info, "created_at": get_time_str() } try: result = await db["records"].insert_one(document) return {"status": "success", "id": str(result.inserted_id), "audio_url": audio_url} except Exception as e: print(f"[{get_time_str()}] [Error] MongoDB record write failed ({type(e).__name__})") database_ready = False return JSONResponse(status_code=503, content={"status": "error", "message": "record storage failed"}) #--------------------------------------- # WebSocket Proxy #--------------------------------------- async def connect_private_with_retry(client_ws, target_url, headers): last_error = None for attempt in range(1, WS_CONNECT_RETRIES + 1): try: return await connect( target_url, extra_headers=headers, ping_interval=20, ping_timeout=20, open_timeout=2, ) except Exception as e: last_error = e response = getattr(e, "response", None) status_code = getattr(e, "status_code", None) or getattr(response, "status_code", None) if status_code in (401, 403, 404): break if attempt >= WS_CONNECT_RETRIES: break delay = attempt print(f"[{get_time_str()}] [Proxy] Private Space connection failed ({type(e).__name__}); retry {attempt}/{WS_CONNECT_RETRIES} in {delay}s") try: await client_ws.send_json({"log": f"[Proxy] 推論服務啟動中,正在重試連線({attempt}/{WS_CONNECT_RETRIES})"}) except Exception: raise await asyncio.sleep(delay) error_type = type(last_error).__name__ if last_error is not None else "UnknownError" raise RuntimeError(f"Private inference Space unavailable ({error_type})") @app.websocket("/ws/audio") async def proxy_ws(client_ws: WebSocket): global active_clients client_type = classify_client(client_ws.headers) print(f"[{get_time_str()}] [Proxy][{client_type}] WS connection attempt") await client_ws.accept() if not PRIVATE_WS or not INTERNAL_API_KEY or not HF_TOKEN: print(f"[{get_time_str()}] [Proxy][{client_type}] Required backend configuration is missing") await client_ws.send_json({"error": "Proxy backend configuration is incomplete"}) await client_ws.close(code=1011, reason="Proxy backend configuration is incomplete") return # Max clients rejected = False async with clients_lock: if active_clients >= MAX_CLIENTS: rejected = True else: active_clients += 1 if rejected: print(f"[{get_time_str()}] [Proxy][{client_type}] Rejected: Max clients reached") await client_ws.close(code=1013, reason="Maximum client count reached") return private_ws = None forwarding_tasks = [] try: target_url = private_websocket_url() headers = { "Authorization": f"Bearer {HF_TOKEN}", "X-Internal-API-Key": INTERNAL_API_KEY, } private_ws = await connect_private_with_retry(client_ws, target_url, headers) print(f"[{get_time_str()}] [Proxy][{client_type}] Connected to Backend") await client_ws.send_json({"log": "[Proxy] Connected to Backend"}) async def forward_to_backend(): while True: msg = await client_ws.receive() if msg.get("type") == "websocket.disconnect": return if msg.get("text") is not None: await private_ws.send(msg["text"]) elif msg.get("bytes") is not None: await private_ws.send(msg["bytes"]) async def forward_to_client(): async for message in private_ws: if isinstance(message, str): await client_ws.send_text(message) else: await client_ws.send_bytes(message) forwarding_tasks = [ asyncio.create_task(forward_to_backend(), name="proxy-to-private"), asyncio.create_task(forward_to_client(), name="private-to-proxy"), ] done, pending = await asyncio.wait(forwarding_tasks, return_when=asyncio.FIRST_COMPLETED) backend_closed = forwarding_tasks[1] in done forwarding_error = False for task in done: try: task.result() except Exception as e: forwarding_error = True print(f"[{get_time_str()}] [Proxy][{client_type}] Forwarding ended ({type(e).__name__})") for task in pending: task.cancel() if pending: await asyncio.gather(*pending, return_exceptions=True) if backend_closed or forwarding_error: try: await client_ws.send_json({"error": "推論服務已中斷連線。"}) await client_ws.close(code=1011, reason="WebSocket forwarding ended") except Exception: pass except WebSocketDisconnect: print(f"[{get_time_str()}] [Proxy][{client_type}] Client disconnected") except Exception as e: # Avoid logging exception text because WebSocket URLs may contain the # private API key in their query string. print(f"[{get_time_str()}] [Proxy][{client_type}] Connection error ({type(e).__name__})") try: await client_ws.send_json({"error": "推論服務暫時無法連線,請稍後再試。"}) await client_ws.close(code=1013, reason="Private inference Space unavailable") except Exception: pass finally: for task in forwarding_tasks: if not task.done(): task.cancel() if forwarding_tasks: await asyncio.gather(*forwarding_tasks, return_exceptions=True) if private_ws is not None: try: await private_ws.close(code=1000, reason="Proxy session ended") except Exception: pass async with clients_lock: active_clients = max(0, active_clients - 1) print(f"[{get_time_str()}] [Proxy][{client_type}] WS closed. Active: {active_clients}")