voice-reflection-journal / model_loader.py
geraldadli's picture
Restore live WebSocket journal with session-based ZeroGPU emotion
b9e7c8b verified
Raw History Blame Contribute Delete
2.83 kB
"""Hugging Face Gradio/ZeroGPU entry point for the exported emotion model."""
from pathlib import Path
import hashlib
import time
import urllib.request
import html
import spaces # Initialize ZeroGPU before importing torch or the predictor.
import gradio as gr
import torch
from whisper_ser_deployment.predict import EmotionPredictor
torch.set_num_threads(2)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
BUNDLE = Path(__file__).resolve().parent / "whisper_ser_deployment"
ENCODER_SHA256 = "b52d093bf0935b15d411d68f25c03fdbc2fcee8e09f2016f2094c0b9e35a6548"
ENCODER_BYTES = 1273987688
ENCODER_URL = (
"https://media.githubusercontent.com/media/geraldadli/"
"speech-emotion-recognition/3dcf17ff762d4979dd66a62cb22697b0867d08f2/"
"whisper_ser_deployment/encoder/model.safetensors"
)
def valid_encoder(path):
if not path.is_file() or path.stat().st_size != ENCODER_BYTES:
return False
with path.open("rb") as source:
return hashlib.file_digest(source, "sha256").hexdigest() == ENCODER_SHA256
def ensure_encoder():
"""Download the exact exported encoder to runtime disk, outside Hub storage."""
target = BUNDLE / "encoder" / "model.safetensors"
target.parent.mkdir(parents=True, exist_ok=True)
if valid_encoder(target):
return
partial = target.with_suffix(".download")
for attempt in range(3):
try:
print("Downloading exported Whisper encoder (1.27 GB)...", flush=True)
request = urllib.request.Request(ENCODER_URL, headers={"User-Agent": "speech-emotion-demo"})
with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as output:
while chunk := response.read(1024 * 1024):
output.write(chunk)
if output.tell() > ENCODER_BYTES:
raise RuntimeError("Encoder download exceeded expected size")
if not valid_encoder(partial):
raise RuntimeError("Encoder download failed size/SHA-256 verification")
partial.replace(target)
print("Encoder verified and ready.", flush=True)
return
except Exception:
partial.unlink(missing_ok=True)
if attempt == 2:
raise
time.sleep(2 * (attempt + 1))
ensure_encoder()
# ZeroGPU requires CUDA model placement at startup, outside the decorated call.
predictor = EmotionPredictor(BUNDLE, device="cuda")
# Bound demo requests without changing the trained preprocessing or normalization.
predictor.config["max_seconds"] = 30.0
predictor.features.effective_batch_size = 1