Spaces:
Running

File size: 26,074 Bytes
156d9b3
 
 
 
 
 
 
 
48a0d24
 
 
156d9b3
f2ee3a6
48a0d24
156d9b3
48a0d24
156d9b3
 
 
 
f2ee3a6
 
 
 
156d9b3
 
 
 
 
 
f2ee3a6
 
156d9b3
 
48a0d24
 
 
 
156d9b3
f2ee3a6
 
 
 
 
 
48a0d24
f2ee3a6
156d9b3
 
48a0d24
 
156d9b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48a0d24
156d9b3
48a0d24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156d9b3
48a0d24
 
 
 
156d9b3
48a0d24
156d9b3
 
48a0d24
156d9b3
 
48a0d24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156d9b3
48a0d24
 
156d9b3
48a0d24
 
 
 
 
 
 
156d9b3
 
 
 
 
 
 
 
48a0d24
156d9b3
48a0d24
 
 
 
 
156d9b3
f2ee3a6
 
48a0d24
 
 
 
 
f2ee3a6
 
 
156d9b3
 
 
48a0d24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156d9b3
 
 
 
 
 
 
 
48a0d24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2ee3a6
 
 
 
 
9a4b39d
f2ee3a6
 
 
 
 
 
48a0d24
 
 
 
 
 
 
 
 
 
 
f2ee3a6
 
 
 
 
 
48a0d24
 
 
 
 
 
 
 
 
 
 
 
 
 
f2ee3a6
 
 
 
 
 
 
 
 
 
 
48a0d24
f2ee3a6
48a0d24
 
f2ee3a6
 
 
 
 
9a4b39d
f2ee3a6
 
 
 
48a0d24
 
 
 
 
 
 
 
f2ee3a6
 
 
 
 
 
 
48a0d24
 
 
f2ee3a6
156d9b3
 
 
48a0d24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156d9b3
 
 
 
 
 
 
48a0d24
 
 
 
 
 
 
156d9b3
48a0d24
156d9b3
 
48a0d24
 
 
 
 
 
 
156d9b3
48a0d24
 
156d9b3
48a0d24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156d9b3
48a0d24
 
 
156d9b3
48a0d24
 
 
156d9b3
 
48a0d24
 
 
 
 
 
 
 
 
 
156d9b3
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
#!/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("<I", data, 4)[0]
    riff_end = riff_size + 8
    if riff_end > 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("<I", data, offset + 4)[0]
        chunk_start = offset + 8
        chunk_end = chunk_start + chunk_size
        if chunk_end > 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(
                "<HHIIHH", chunk, 0
            )
            if encoding == 0xFFFE:
                if chunk_size < 26:
                    raise ValueError("audio_file has an incomplete extensible WAV format")
                encoding = struct.unpack_from("<H", chunk, 24)[0]
            fmt = (encoding, channels, sample_rate, byte_rate, block_align, bits)
        elif chunk_id == b"data":
            if fmt is None:
                raise ValueError("audio_file data chunk appears before its format chunk")
            audio_data = chunk
            break

        offset = chunk_end + (chunk_size & 1)

    if fmt is None or audio_data is None:
        raise ValueError("audio_file is missing its format or audio data")
    encoding, channels, sample_rate, byte_rate, block_align, bits = fmt
    if encoding not in (1, 3):
        raise ValueError("audio_file must use uncompressed PCM or IEEE-float WAV")
    if channels not in range(1, 9):
        raise ValueError("audio_file must contain between one and eight channels")
    if not 1 <= sample_rate <= 192_000:
        raise ValueError("audio_file has an unsupported sample rate")
    if (encoding == 1 and bits not in (8, 16, 24, 32)) or (encoding == 3 and bits != 32):
        raise ValueError("audio_file has an unsupported sample format")

    bytes_per_sample = (bits + 7) // 8
    if block_align < channels * bytes_per_sample or byte_rate <= 0:
        raise ValueError("audio_file has an invalid channel layout")
    if not audio_data or len(audio_data) % block_align != 0:
        raise ValueError("audio_file audio data is empty or incomplete")

    frame_count = len(audio_data) // block_align
    channel = 0 if channels == 1 else min(max(preferred_channel, 0), channels - 1)
    selected_pcm = bytearray(frame_count * bytes_per_sample)
    for byte_index in range(bytes_per_sample):
        selected_pcm[byte_index::bytes_per_sample] = audio_data[
            channel * bytes_per_sample + byte_index::block_align
        ]

    selected_pcm = bytes(selected_pcm)
    fmt_chunk = struct.pack(
        "<HHIIHH",
        encoding,
        1,
        sample_rate,
        sample_rate * bytes_per_sample,
        bytes_per_sample,
        bits,
    )
    pad = b"\x00" if len(selected_pcm) & 1 else b""
    riff_payload_size = 4 + 8 + len(fmt_chunk) + 8 + len(selected_pcm) + len(pad)
    normalized = (
        b"RIFF"
        + struct.pack("<I", riff_payload_size)
        + b"WAVEfmt "
        + struct.pack("<I", len(fmt_chunk))
        + fmt_chunk
        + b"data"
        + struct.pack("<I", len(selected_pcm))
        + selected_pcm
        + pad
    )
    return normalized, {
        "sample_rate_hz": sample_rate,
        "original_channels": channels,
        "stored_channels": 1,
        "channel_selection": "mono" if channels == 1 else f"CH{channel}",
        "sample_width_bytes": bytes_per_sample,
        "bits_per_sample": bits,
        "encoding": "pcm" if encoding == 1 else "ieee_float",
        "duration_seconds": frame_count / sample_rate,
    }


#---------------------------------------
# runtime Record Upload API
#---------------------------------------
@app.post("/api/runtime_record")
async def save_runtime_record(
    sid: str = Form("Unknown"),
    nurse_label: str = Form(...),
    ai_prediction: str = Form("no"),
    ai_confidence: float = Form(0.0),
    device_info: str = Form("Unknown"),
    audio_file: UploadFile = File(...)
):
    global database_ready
    if db is None or not database_ready:
        return JSONResponse(status_code=503, content={"status": "error", "message": "database is not connected"})
    if not HF_DATASET_TOKEN or not HF_DATASET_REPO:
        return JSONResponse(status_code=503, content={"status": "error", "message": "dataset storage is not configured"})
    if nurse_label not in {"positive", "negative", "unknown"}:
        return JSONResponse(status_code=400, content={"status": "error", "message": "invalid nurse_label"})
    if ai_prediction not in {"yes", "no", "unknown"}:
        return JSONResponse(status_code=400, content={"status": "error", "message": "invalid ai_prediction"})
    if not 0.0 <= ai_confidence <= 1.0:
        return JSONResponse(status_code=400, content={"status": "error", "message": "ai_confidence must be between 0 and 1"})

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # 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}")