Spaces:
Sleeping

File size: 23,072 Bytes
39b3d5a
6e60f86
10f1be9
 
39b3d5a
 
 
 
 
 
6e60f86
 
39b3d5a
 
 
 
 
 
 
6e60f86
39b3d5a
 
 
 
 
 
 
 
 
6e60f86
39b3d5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac23582
39b3d5a
ac23582
39b3d5a
ac23582
 
 
 
39b3d5a
ac23582
 
39b3d5a
ac23582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39b3d5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e60f86
10f1be9
39b3d5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e60f86
39b3d5a
 
6e60f86
 
 
 
 
 
 
 
 
 
 
39b3d5a
 
 
c40f26e
 
10f1be9
b9b2df9
 
 
c40f26e
b9b2df9
 
10f1be9
6e60f86
b9b2df9
c40f26e
 
 
 
 
 
 
b9b2df9
 
c40f26e
 
 
 
 
 
 
 
 
 
 
b9b2df9
c40f26e
 
 
10f1be9
b9b2df9
 
 
 
 
 
 
c40f26e
 
 
 
10f1be9
b9b2df9
10f1be9
 
 
 
 
 
 
 
 
 
 
 
 
6e60f86
10f1be9
 
 
 
 
 
 
 
 
 
 
39b3d5a
10f1be9
 
 
6e60f86
10f1be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e60f86
39b3d5a
 
6e60f86
 
 
10f1be9
8da871d
ac23582
6e60f86
39b3d5a
 
 
 
 
 
 
10f1be9
39b3d5a
 
 
 
 
 
 
 
 
 
 
 
 
 
6e60f86
 
10f1be9
 
39b3d5a
 
 
 
 
 
 
 
6e60f86
39b3d5a
10f1be9
 
 
 
 
 
 
 
 
6e60f86
 
 
 
 
 
10f1be9
 
6e60f86
 
 
 
 
 
 
 
 
 
 
d688be6
6e60f86
d688be6
 
 
 
10f1be9
 
 
6e60f86
10f1be9
 
 
 
 
6e60f86
 
 
 
 
 
 
10f1be9
6e60f86
 
 
 
 
 
 
 
 
 
 
10f1be9
6e60f86
10f1be9
 
 
6e60f86
10f1be9
 
 
6e60f86
10f1be9
 
 
 
 
6e60f86
39b3d5a
 
 
 
72713f6
 
10f1be9
 
72713f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f1be9
72713f6
 
 
 
 
 
 
 
 
822fb19
72713f6
10f1be9
 
 
72713f6
 
 
 
 
10f1be9
72713f6
 
 
 
 
 
619ca35
 
 
10f1be9
 
619ca35
 
 
 
 
 
 
10f1be9
 
 
619ca35
10f1be9
619ca35
 
 
 
10f1be9
 
 
 
 
 
 
 
619ca35
10f1be9
619ca35
 
10f1be9
619ca35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f1be9
 
619ca35
 
 
 
 
 
 
 
 
 
 
 
 
10f1be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619ca35
 
 
 
 
10f1be9
619ca35
10f1be9
 
619ca35
10f1be9
619ca35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f1be9
619ca35
 
 
 
 
 
 
39b3d5a
 
 
 
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
"""
Tribe V2 Brain Predictive Model - REST API Service
Uses the OFFICIAL TribeModel.get_events_dataframe() pipeline
so the model actually processes video frames and audio.
"""
import os
import math
import warnings
import threading
import traceback
import tempfile
import subprocess
import numpy as np
from flask import Flask, request, jsonify

warnings.filterwarnings("ignore")

app = Flask(__name__)

# Global model state
_model = None
_model_loaded = False
_model_loading = False
_model_error = None
_model_lock = threading.Lock()

HF_TOKEN = os.environ.get("HF_TOKEN", "")
CKPT = os.environ.get("TRIBE_CKPT", "facebook/tribev2")

# ROI vertex indices
ROI_INDICES = {
    "language":  list(range(0, 800)),
    "visual":    list(range(800, 1600)),
    "attention": list(range(1600, 2400)),
    "emotion":   list(range(2400, 3200)),
    "default":   list(range(3200, 4000)),
}


def _load_model():
    global _model, _model_loaded, _model_loading, _model_error
    with _model_lock:
        if _model_loaded or _model_loading:
            return
        _model_loading = True
        _model_error = None

    try:
        print("[Tribe V2] Starting model load...", flush=True)

        if HF_TOKEN:
            os.environ["HUGGING_FACE_HUB_TOKEN"] = HF_TOKEN
            os.environ["HF_TOKEN"] = HF_TOKEN
            try:
                from huggingface_hub import login
                login(token=HF_TOKEN, add_to_git_credential=False)
                print(f"[Tribe V2] HF login OK (len={len(HF_TOKEN)})", flush=True)
            except Exception as login_err:
                print(f"[Tribe V2] HF login warning: {login_err}", flush=True)
        else:
            print("[Tribe V2] WARNING: No HF_TOKEN set!", flush=True)

        import torch
        print(f"[Tribe V2] PyTorch {torch.__version__}", flush=True)

        # CPU Patch for ALL extractors (text, video, audio all default to cuda)
        try:
            import torch

            # Patch text extractor (Llama)
            from neuralset.extractors.text import HuggingFaceText
            orig_text_load = HuggingFaceText._load_model
            def cpu_patched_text_load(self):
                object.__setattr__(self, 'device', 'cpu')
                return orig_text_load(self)
            HuggingFaceText._load_model = cpu_patched_text_load

            # Patch video extractor's image device
            try:
                from neuralset.extractors.video import VideoFeature
                orig_video_load = VideoFeature._load_model
                def cpu_patched_video_load(self):
                    result = orig_video_load(self)
                    if hasattr(self, 'image') and hasattr(self.image, 'device'):
                        object.__setattr__(self.image, 'device', 'cpu')
                    return result
                VideoFeature._load_model = cpu_patched_video_load
            except Exception as ve:
                print(f"[Tribe V2] Video patch warning: {ve}", flush=True)

            # Patch audio extractor
            try:
                from neuralset.extractors.audio import AudioFeature
                orig_audio_load = AudioFeature._load_model
                def cpu_patched_audio_load(self):
                    result = orig_audio_load(self)
                    if hasattr(self, 'device'):
                        object.__setattr__(self, 'device', 'cpu')
                    return result
                AudioFeature._load_model = cpu_patched_audio_load
            except Exception as ae:
                print(f"[Tribe V2] Audio patch warning: {ae}", flush=True)

            # Nuclear option: override torch.cuda.is_available to force CPU everywhere
            if not torch.cuda.is_available():
                torch.cuda.is_available = lambda: False
                # Also patch any .to('cuda') calls by monkey-patching Module.to
                orig_to = torch.nn.Module.to
                def safe_to(self_module, *args, **kwargs):
                    args = tuple('cpu' if a == 'cuda' or (isinstance(a, torch.device) and a.type == 'cuda') else a for a in args)
                    if 'device' in kwargs:
                        d = kwargs['device']
                        if d == 'cuda' or (isinstance(d, torch.device) and d.type == 'cuda'):
                            kwargs['device'] = 'cpu'
                    return orig_to(self_module, *args, **kwargs)
                torch.nn.Module.to = safe_to

            print("[Tribe V2] All CPU patches applied (text + video + audio + Module.to)", flush=True)
        except Exception as e:
            print(f"[Tribe V2] CPU patch warning: {e}", flush=True)

        from tribev2 import TribeModel
        print("[Tribe V2] Loading TribeModel...", flush=True)
        model = TribeModel.from_pretrained(CKPT, device='cpu')
        print("[Tribe V2] TribeModel loaded!", flush=True)

        with _model_lock:
            _model = model
            _model_loaded = True
            _model_loading = False
        print("[Tribe V2] Ready!", flush=True)

    except Exception as e:
        err = traceback.format_exc()
        print(f"[Tribe V2] LOAD ERROR:\n{err}", flush=True)
        with _model_lock:
            _model_loading = False
            _model_error = str(e)


def _normalize_roi(val: float, overall: float) -> float:
    if overall == 0:
        return 50.0
    ratio = val / overall
    score = 50 + 50 * math.tanh((ratio - 1.0) * 2)
    return round(min(100.0, max(0.0, score)), 1)


def _score_preds(pred_array) -> dict:
    """Convert prediction array to brain scores."""
    if hasattr(pred_array, "bfloat16"):
        pred_array = pred_array.bfloat16().float()
    if hasattr(pred_array, "numpy"):
        pred_array = pred_array.numpy()
    pred_array = np.array(pred_array)
    if pred_array.ndim == 1:
        pred_array = pred_array.reshape(1, -1)

    n_timesteps, n_vertices = pred_array.shape
    overall_mean = float(np.abs(pred_array).mean())

    def roi_score(indices):
        safe = [i for i in indices if i < n_vertices]
        return float(np.abs(pred_array[:, safe]).mean()) if safe else overall_mean

    lang  = roi_score(ROI_INDICES["language"])
    vis   = roi_score(ROI_INDICES["visual"])
    att   = roi_score(ROI_INDICES["attention"])
    emo   = roi_score(ROI_INDICES["emotion"])
    dmn   = roi_score(ROI_INDICES["default"])

    lp = _normalize_roi(lang, overall_mean)
    vi = _normalize_roi(vis,  overall_mean)
    ac = _normalize_roi(att,  overall_mean)
    ev = _normalize_roi(emo,  overall_mean)
    be = _normalize_roi(dmn,  overall_mean)

    viral = round(be*0.35 + ev*0.30 + ac*0.20 + lp*0.10 + vi*0.05, 1)
    timeline = [round(float(np.abs(pred_array[t]).mean()), 4) for t in range(n_timesteps)]
    mid = n_vertices // 2
    dom = "left" if float(np.abs(pred_array[:, :mid]).mean()) >= float(np.abs(pred_array[:, mid:]).mean()) else "right"

    return {
        "language_processing": lp,
        "visual_imagery": vi,
        "attention_capture": ac,
        "emotional_valence": ev,
        "overall_brain_engagement": be,
        "viral_potential": viral,
        "activation_timeline": timeline,
        "n_timesteps": n_timesteps,
        "n_vertices": n_vertices,
        "dominant_hemisphere": dom,
        "overall_mean_activation": round(overall_mean, 6),
    }


def _predict_file(file_path: str, mode: str = "video"):
    """Build proper events with filepath so the model actually processes media.
    
    The critical difference from the old code: we create Video events
    with 'filepath' pointing to the actual file, so the visual extractor
    reads real frame data.
    
    On CPU Spaces: skip audio extraction (audio extractor needs CUDA).
    On GPU local: enable full pipeline with audio.
    """
    import pandas as pd
    import torch
    from neuralset.events.utils import standardize_events
    from neuralset.events.transforms import (
        ExtractAudioFromVideo,
        ChunkEvents,
        RemoveMissing,
    )
    
    has_cuda = torch.cuda.is_available()
    
    # Build initial event with filepath -- this is the critical part
    event_type = "Audio" if mode == "audio" else "Video"
    event = {
        "type": event_type,
        "filepath": str(file_path),
        "start": 0,
        "timeline": "default",
        "subject": "default",
    }
    events_df = pd.DataFrame([event])
    
    # Build transforms -- skip audio extraction on CPU
    transforms = [
        ChunkEvents(event_type_to_chunk="Video", max_duration=60, min_duration=30),
    ]
    
    if has_cuda:
        # Full pipeline: extract audio from video, then chunk both
        transforms.insert(0, ExtractAudioFromVideo())
        transforms.append(ChunkEvents(event_type_to_chunk="Audio", max_duration=60, min_duration=30))
    
    transforms.append(RemoveMissing())
    
    events_df = standardize_events(events_df)
    for transform in transforms:
        events_df = transform(events_df)
    events_df = standardize_events(events_df)
    
    print(f"[Tribe V2] Events created: {len(events_df)} events, types: {events_df['type'].value_counts().to_dict()}, cuda={has_cuda}", flush=True)
    
    result = _model.predict(events_df, verbose=True)
    pred_array = result[0] if isinstance(result, tuple) else result
    return pred_array, events_df


def _predict_text_official(text: str):
    """Text prediction via official API (requires TTS + transcription)."""
    # Write text to temp file
    with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tmp:
        tmp.write(text)
        tmp_path = tmp.name
    
    try:
        events_df = _model.get_events_dataframe(text_path=tmp_path)
        print(f"[Tribe V2] Text events: {len(events_df)} events, types: {events_df['type'].value_counts().to_dict()}", flush=True)
        result = _model.predict(events_df, verbose=True)
        pred_array = result[0] if isinstance(result, tuple) else result
        return pred_array, events_df
    finally:
        try:
            os.unlink(tmp_path)
        except:
            pass


def _predict_text_fast(text: str):
    """Fast text prediction without TTS (manual Word events + context).
    Works without Llama download access, uses text extractor directly."""
    import pandas as pd
    
    words = [w for w in text.split() if w.strip()]
    duration = 0.5
    rows = [{"type": "Word",
             "text": w,
             "context": text,
             "start": i * duration,
             "duration": duration,
             "timeline": "default"}
            for i, w in enumerate(words)]
    events_df = pd.DataFrame(rows)
    
    result = _model.predict(events_df, verbose=True)
    pred_array = result[0] if isinstance(result, tuple) else result
    return pred_array


# ---- Routes ----

@app.route("/", methods=["GET"])
def index():
    return jsonify({
        "service": "tribe-v2-api",
        "status": "ok",
        "pipeline": "official-tribemodel",
        "/endpoints": ["/health", "/warmup", "/predict_text", "/predict_video", "/predict_audio", "/predict_image", "/predict_raw"],
        "version": "cpu-patches-v1"
    })


@app.route("/health", methods=["GET"])
def health():
    return jsonify({
        "status": "ok" if _model_loaded else ("loading" if _model_loading else "offline"),
        "model": "tribe-v2",
        "pipeline": "official",
        "model_loaded": _model_loaded,
        "model_loading": _model_loading,
        "error": _model_error,
    })


@app.route("/warmup", methods=["POST"])
def warmup():
    if not _model_loaded and not _model_loading:
        threading.Thread(target=_load_model, daemon=True).start()
    return jsonify({"status": "warming_up", "model_loaded": _model_loaded,
                    "model_loading": _model_loading})


@app.route("/predict_text", methods=["POST"])
def predict_text():
    """Text -> brain scores. Uses fast path (Word events) by default.
    Set ?official=true to use TTS pipeline (slower, needs gTTS + whisperx)."""
    if not _model_loaded:
        return jsonify({"error": "Model not loaded. Call /warmup first.",
                        "model_loading": _model_loading,
                        "load_error": _model_error}), 503
    data = request.get_json(force=True, silent=True) or {}
    text = (data.get("text") or "").strip()[:5000]
    if len(text) < 5:
        return jsonify({"error": "Text too short (min 5 chars)"}), 400

    try:
        use_official = request.args.get("official", "false").lower() == "true"
        if use_official:
            pred_array, events_df = _predict_text_official(text)
            events_info = {"types": events_df['type'].value_counts().to_dict(), "total": len(events_df)}
        else:
            pred_array = _predict_text_fast(text)
            events_info = {"mode": "fast", "words": len(text.split())}

        return jsonify({"scores": _score_preds(pred_array), "status": "ok", "events": events_info})
    except Exception as e:
        return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500


@app.route("/predict_video", methods=["POST"])
def predict_video():
    """Video file -> brain scores using OFFICIAL pipeline.
    The model actually reads video frames and extracts audio."""
    if not _model_loaded:
        return jsonify({"error": "Model not loaded. Call /warmup first.",
                        "model_loading": _model_loading,
                        "load_error": _model_error}), 503

    try:
        video_file = request.files.get("video")
        if not video_file:
            return jsonify({"error": "No video file provided"}), 400

        suffix = os.path.splitext(video_file.filename)[1] or ".mp4"
        tmp_path = None
        try:
            with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
                video_file.save(tmp.name)
                tmp_path = tmp.name

            pred_array, events_df = _predict_file(tmp_path, mode="video")
            events_info = {"types": events_df['type'].value_counts().to_dict(), "total": len(events_df)}
            return jsonify({"scores": _score_preds(pred_array), "status": "ok", "events": events_info})
        finally:
            if tmp_path:
                try:
                    os.unlink(tmp_path)
                except:
                    pass

    except Exception as e:
        return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500


@app.route("/predict_audio", methods=["POST"])
def predict_audio():
    """Audio file -> brain scores using OFFICIAL pipeline."""
    if not _model_loaded:
        return jsonify({"error": "Model not loaded. Call /warmup first.",
                        "model_loading": _model_loading,
                        "load_error": _model_error}), 503

    try:
        audio_file = request.files.get("audio")
        if not audio_file:
            return jsonify({"error": "No audio file provided"}), 400

        suffix = os.path.splitext(audio_file.filename)[1] or ".wav"
        tmp_path = None
        try:
            with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
                audio_file.save(tmp.name)
                tmp_path = tmp.name

            pred_array, events_df = _predict_file(tmp_path, mode="audio")
            events_info = {"types": events_df['type'].value_counts().to_dict(), "total": len(events_df)}
            return jsonify({"scores": _score_preds(pred_array), "status": "ok", "events": events_info})
        finally:
            if tmp_path:
                try:
                    os.unlink(tmp_path)
                except:
                    pass

    except Exception as e:
        return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500


@app.route("/predict_image", methods=["POST"])
def predict_image():
    """Image file -> brain scores.
    Converts image to 3s video, then uses official video pipeline."""
    if not _model_loaded:
        return jsonify({"error": "Model not loaded. Call /warmup first.",
                        "model_loading": _model_loading,
                        "load_error": _model_error}), 503

    try:
        image_file = request.files.get("image")
        if not image_file:
            return jsonify({"error": "No image file provided"}), 400

        suffix = os.path.splitext(image_file.filename)[1] or ".jpg"
        img_path = None
        vid_path = None
        try:
            with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
                image_file.save(tmp.name)
                img_path = tmp.name

            # Convert image to 3s video (official pipeline needs video or audio)
            vid_path = img_path + ".mp4"
            result = subprocess.run([
                "ffmpeg", "-y", "-loop", "1", "-i", img_path,
                "-c:v", "libx264", "-t", "3", "-pix_fmt", "yuv420p",
                "-vf", "scale=224:224",
                vid_path
            ], capture_output=True, timeout=30)

            if result.returncode != 0:
                return jsonify({"error": f"ffmpeg video failed: {result.stderr.decode()[:200]}"}), 500

            pred_array, events_df = _predict_file(vid_path, mode="video")
            events_info = {"types": events_df['type'].value_counts().to_dict(), "total": len(events_df)}
            return jsonify({"scores": _score_preds(pred_array), "status": "ok", "events": events_info})
        finally:
            for p in [img_path, vid_path]:
                if p:
                    try:
                        os.unlink(p)
                    except:
                        pass

    except Exception as e:
        return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500


@app.route("/predict_raw", methods=["POST"])
def predict_raw():
    """Return the FULL prediction tensor (n_timesteps x n_vertices) as raw data.
    Accepts: image (multipart), video (multipart), audio (multipart), or text (JSON).
    Uses official pipeline for all inputs."""
    if not _model_loaded:
        return jsonify({"error": "Model not loaded. Call /warmup first.",
                        "model_loading": _model_loading,
                        "load_error": _model_error}), 503

    try:
        content_type = request.content_type or ""
        pred_array = None
        events_info = {}

        if "application/json" in content_type:
            # Text input
            data = request.get_json(force=True, silent=True) or {}
            text = (data.get("text") or "").strip()[:5000]
            if len(text) < 5:
                return jsonify({"error": "Text too short (min 5 chars)"}), 400
            
            use_official = request.args.get("official", "false").lower() == "true"
            if use_official:
                pred_array, events_df = _predict_text_official(text)
                events_info = {"types": events_df['type'].value_counts().to_dict(), "total": len(events_df)}
            else:
                pred_array = _predict_text_fast(text)
                events_info = {"mode": "fast", "words": len(text.split())}
        else:
            # Multipart: image, video, or audio
            image_file = request.files.get("image")
            video_file = request.files.get("video")
            audio_file = request.files.get("audio")

            if image_file:
                suffix = os.path.splitext(image_file.filename)[1] or ".jpg"
                img_path = None
                vid_path = None
                try:
                    with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
                        image_file.save(tmp.name)
                        img_path = tmp.name
                    vid_path = img_path + ".mp4"
                    r = subprocess.run([
                        "ffmpeg", "-y", "-loop", "1", "-i", img_path,
                        "-c:v", "libx264", "-t", "3", "-pix_fmt", "yuv420p",
                        "-vf", "scale=224:224", vid_path
                    ], capture_output=True, timeout=30)
                    if r.returncode != 0:
                        return jsonify({"error": f"ffmpeg failed: {r.stderr.decode()[:200]}"}), 500
                    pred_array, events_df = _predict_file(vid_path, mode="video")
                    events_info = {"input": "image->video", "types": events_df['type'].value_counts().to_dict()}
                finally:
                    for p in [img_path, vid_path]:
                        if p:
                            try: os.unlink(p)
                            except: pass

            elif video_file:
                suffix = os.path.splitext(video_file.filename)[1] or ".mp4"
                tmp_path = None
                try:
                    with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
                        video_file.save(tmp.name)
                        tmp_path = tmp.name
                    pred_array, events_df = _predict_file(tmp_path, mode="video")
                    events_info = {"input": "video", "types": events_df['type'].value_counts().to_dict()}
                finally:
                    if tmp_path:
                        try: os.unlink(tmp_path)
                        except: pass

            elif audio_file:
                suffix = os.path.splitext(audio_file.filename)[1] or ".wav"
                tmp_path = None
                try:
                    with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
                        audio_file.save(tmp.name)
                        tmp_path = tmp.name
                    pred_array, events_df = _predict_file(tmp_path, mode="audio")
                    events_info = {"input": "audio", "types": events_df['type'].value_counts().to_dict()}
                finally:
                    if tmp_path:
                        try: os.unlink(tmp_path)
                        except: pass
            else:
                return jsonify({"error": "No input provided. Send image, video, audio, or text."}), 400

        if pred_array is None:
            return jsonify({"error": "Could not generate predictions"}), 500

        # Convert tensor
        if hasattr(pred_array, "bfloat16"):
            pred_array = pred_array.bfloat16().float()
        if hasattr(pred_array, "numpy"):
            pred_array = pred_array.numpy()
        pred_array = np.array(pred_array)
        if pred_array.ndim == 1:
            pred_array = pred_array.reshape(1, -1)

        n_timesteps, n_vertices = pred_array.shape

        return jsonify({
            "raw_predictions": pred_array.tolist(),
            "shape": [n_timesteps, n_vertices],
            "roi_indices": ROI_INDICES,
            "scores": _score_preds(pred_array),
            "events": events_info,
            "status": "ok",
        })

    except Exception as e:
        return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500


if __name__ == "__main__":
    threading.Thread(target=_load_model, daemon=True).start()
    port = int(os.environ.get("PORT", 7860))
    app.run(host="0.0.0.0", port=port, debug=False)