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