File size: 5,484 Bytes
74db089
 
 
f055136
 
 
 
 
74db089
 
 
 
 
 
 
 
 
f055136
74db089
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f055136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d20509a
74db089
d20509a
74db089
 
 
 
 
 
 
 
f055136
 
 
 
 
 
 
 
74db089
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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'")