""" Hugging Face Inference Endpoints — Custom Handler for TRIBEv2. Serves the TRIBEv2 brain encoding model. Accepts audio, video, or text input and returns fMRI predictions across ~10k cortical vertices. Uses audio_only mode to skip whisperx transcription (avoids dependency hell). The model still produces predictions using audio + video features. """ import base64 import logging import os import tempfile from pathlib import Path import numpy as np import pandas as pd import torch logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) CACHE_FOLDER = Path("/cache") CACHE_FOLDER.mkdir(parents=True, exist_ok=True) class EndpointHandler: def __init__(self, model_dir: str = ""): """Load TRIBEv2 model at worker startup.""" from tribev2.demo_utils import TribeModel device = "cuda" if torch.cuda.is_available() else "cpu" logger.info(f"Loading TRIBEv2 on {device}...") self.model = TribeModel.from_pretrained( "facebook/tribev2", cache_folder=str(CACHE_FOLDER), device=device, ) logger.info("TRIBEv2 loaded.") def _get_events_audio_only(self, file_path: str, event_type: str = "Audio") -> pd.DataFrame: """Build events without whisperx transcription (audio_only mode).""" from tribev2.demo_utils import get_audio_and_text_events event = { "type": event_type, "filepath": file_path, "start": 0, "timeline": "default", "subject": "default", } return get_audio_and_text_events(pd.DataFrame([event]), audio_only=True) def _get_events_text(self, text: str) -> pd.DataFrame: """Convert text to speech then get audio events (no whisperx needed).""" from gtts import gTTS from langdetect import detect audio_path = CACHE_FOLDER / "tts_audio.mp3" lang = detect(text) tts = gTTS(text, lang=lang) tts.save(str(audio_path)) logger.info(f"TTS audio saved to {audio_path}") return self._get_events_audio_only(str(audio_path), event_type="Audio") def __call__(self, data: dict) -> dict: """Handle inference request.""" inputs = data.get("inputs", data) file_path = None try: file_path, modality = self._decode_input(inputs) logger.info(f"Processing {modality}: {file_path}") # Build events — use audio_only mode to skip whisperx if modality == "text": text = Path(file_path).read_text() events = self._get_events_text(text) elif modality == "video": events = self._get_events_audio_only(str(file_path), event_type="Video") else: # audio events = self._get_events_audio_only(str(file_path), event_type="Audio") preds, segments = self.model.predict(events, verbose=False) logger.info(f"Prediction shape: {preds.shape}") return { "predictions": preds.tolist(), "shape": list(preds.shape), "n_timesteps": preds.shape[0], "n_vertices": preds.shape[1], "segments": [ { "start": float(seg.offset) if hasattr(seg, "offset") else None, "duration": float(seg.duration) if hasattr(seg, "duration") else None, } for seg in segments ], } finally: if file_path and file_path.exists() and str(file_path).startswith(str(CACHE_FOLDER)): try: file_path.unlink() except OSError: pass def _decode_input(self, inputs: dict) -> tuple[Path, str]: modality = inputs.get("modality") if not modality or modality not in ("video", "audio", "text"): raise ValueError("'modality' required: 'video', 'audio', or 'text'") suffix_map = {"video": ".mp4", "audio": ".wav", "text": ".txt"} if "data" in inputs: raw = base64.b64decode(inputs["data"]) ext = inputs.get("extension", suffix_map[modality]) if not ext.startswith("."): ext = f".{ext}" tmp = tempfile.NamedTemporaryFile(suffix=ext, dir=str(CACHE_FOLDER), delete=False) tmp.write(raw) tmp.close() return Path(tmp.name), modality if "url" in inputs: import requests as req ext = inputs.get("extension", suffix_map[modality]) if not ext.startswith("."): ext = f".{ext}" dest = CACHE_FOLDER / f"input_{os.getpid()}{ext}" with req.get(inputs["url"], stream=True, timeout=120) as r: r.raise_for_status() with open(dest, "wb") as f: for chunk in r.iter_content(chunk_size=256 * 1024): if chunk: f.write(chunk) return dest, modality if "text" in inputs: tmp = tempfile.NamedTemporaryFile( suffix=".txt", dir=str(CACHE_FOLDER), delete=False, mode="w" ) tmp.write(inputs["text"]) tmp.close() return Path(tmp.name), "text" raise ValueError("Input must contain 'data' (base64), 'url', or 'text'")