clone3 commited on
Commit
0e2d818
·
verified ·
1 Parent(s): 5dbf298

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -211
app.py CHANGED
@@ -1,221 +1,174 @@
1
- """
2
- Tribe V2 Brain Predictive Model – REST API Service
3
- Deployed on HuggingFace Spaces (CPU)
4
- """
5
-
6
  import os
7
- import math
8
- import warnings
9
- import threading
10
  import traceback
 
11
  import numpy as np
12
- from flask import Flask, request, jsonify
13
-
14
- warnings.filterwarnings("ignore")
15
-
16
- app = Flask(__name__)
17
-
18
- # ─── Global model state ──────────────────────────────────────────────────────
19
- _model = None
20
- _model_loaded = False
21
- _model_loading = False
22
- _model_error = None
23
- _model_lock = threading.Lock()
24
-
25
- HF_TOKEN = os.environ.get("HF_TOKEN", "")
26
- CKPT = os.environ.get("TRIBE_CKPT", "facebook/tribev2")
27
-
28
- # ─── ROI vertex indices ───────────────────────────────────────────────────────
29
- ROI_INDICES = {
30
- "language": list(range(0, 800)),
31
- "visual": list(range(800, 1600)),
32
- "attention": list(range(1600, 2400)),
33
- "emotion": list(range(2400, 3200)),
34
- "default": list(range(3200, 4000)),
35
- }
36
-
37
-
38
- def _load_model():
39
- global _model, _model_loaded, _model_loading, _model_error
40
- with _model_lock:
41
- if _model_loaded or _model_loading:
42
- return
43
- _model_loading = True
44
- _model_error = None
45
-
46
- try:
47
- print("[Tribe V2] Starting model load...", flush=True)
48
-
49
- # Set HF token for gated model access (all methods)
50
- if HF_TOKEN:
51
- os.environ["HUGGING_FACE_HUB_TOKEN"] = HF_TOKEN
52
- os.environ["HF_TOKEN"] = HF_TOKEN
53
- # Also login via huggingface_hub so transformers picks it up
54
- try:
55
- from huggingface_hub import login
56
- login(token=HF_TOKEN, add_to_git_credential=False)
57
- print(f"[Tribe V2] HF login OK (len={len(HF_TOKEN)})", flush=True)
58
- except Exception as login_err:
59
- print(f"[Tribe V2] HF login warning: {login_err}", flush=True)
60
- else:
61
- print("[Tribe V2] WARNING: No HF_TOKEN set!", flush=True)
62
-
63
- import torch
64
- print(f"[Tribe V2] PyTorch {torch.__version__}", flush=True)
65
-
66
- # ── CPU Patch ──────────────────────────────────────────────────────
67
- # The Tribe V2 config.yaml has device: cuda for the text extractor.
68
- # We patch HuggingFaceText._load_model to force device='cpu' via
69
- # object.__setattr__ (bypasses pydantic's immutability) BEFORE
70
- # the model weights are moved to device.
71
- try:
72
- from neuralset.extractors.text import HuggingFaceText
73
- orig_load = HuggingFaceText._load_model
74
-
75
- def cpu_patched_load(self):
76
- """Force CPU device before loading model weights."""
77
- object.__setattr__(self, 'device', 'cpu')
78
- return orig_load(self)
79
-
80
- HuggingFaceText._load_model = cpu_patched_load
81
- print("[Tribe V2] CPU patch applied (object.__setattr__)", flush=True)
82
- except Exception as e:
83
- print(f"[Tribe V2] CPU patch warning: {e}", flush=True)
84
-
85
- from tribev2 import TribeModel
86
- print("[Tribe V2] Loading TribeModel...", flush=True)
87
- model = TribeModel.from_pretrained(CKPT, device='cpu')
88
- print("[Tribe V2] TribeModel loaded!", flush=True)
89
-
90
- with _model_lock:
91
- _model = model
92
- _model_loaded = True
93
- _model_loading = False
94
- print("[Tribe V2] Ready!", flush=True)
95
-
96
- except Exception as e:
97
- err = traceback.format_exc()
98
- print(f"[Tribe V2] LOAD ERROR:\n{err}", flush=True)
99
- with _model_lock:
100
- _model_loading = False
101
- _model_error = str(e)
102
-
103
-
104
- def _normalize_roi(val: float, overall: float) -> float:
105
- if overall == 0:
106
- return 50.0
107
- ratio = val / overall
108
- score = 50 + 50 * math.tanh((ratio - 1.0) * 2)
109
- return round(min(100.0, max(0.0, score)), 1)
110
-
111
-
112
- def _score_text(text: str) -> dict:
113
- import pandas as pd
114
-
115
- words = [w for w in text.split() if w.strip()]
116
- if not words:
117
- raise ValueError("Empty text")
118
-
119
- duration = 0.5
120
- # neuralset Word-Felder: start (float), timeline (str), text, context, duration
121
- rows = [{"type": "Word",
122
- "text": w,
123
- "context": text,
124
- "start": i * duration,
125
- "duration": duration,
126
- "timeline": "default"}
127
- for i, w in enumerate(words)]
128
- events_df = pd.DataFrame(rows)
129
-
130
- # TribeModel.predict() gibt (preds_array, segments) als Tuple zurück
131
- result = _model.predict(events_df, verbose=False)
132
- pred_array = result[0] if isinstance(result, tuple) else result
133
- if hasattr(pred_array, "numpy"):
134
- pred_array = pred_array.numpy()
135
- pred_array = np.array(pred_array)
136
- if pred_array.ndim == 1:
137
- pred_array = pred_array.reshape(1, -1)
138
-
139
- n_timesteps, n_vertices = pred_array.shape
140
- overall_mean = float(np.abs(pred_array).mean())
141
-
142
- def roi_score(indices):
143
- safe = [i for i in indices if i < n_vertices]
144
- return float(np.abs(pred_array[:, safe]).mean()) if safe else overall_mean
145
-
146
- lang = roi_score(ROI_INDICES["language"])
147
- vis = roi_score(ROI_INDICES["visual"])
148
- att = roi_score(ROI_INDICES["attention"])
149
- emo = roi_score(ROI_INDICES["emotion"])
150
- dmn = roi_score(ROI_INDICES["default"])
151
-
152
- lp = _normalize_roi(lang, overall_mean)
153
- vi = _normalize_roi(vis, overall_mean)
154
- ac = _normalize_roi(att, overall_mean)
155
- ev = _normalize_roi(emo, overall_mean)
156
- be = _normalize_roi(dmn, overall_mean)
157
-
158
- viral = round(be*0.35 + ev*0.30 + ac*0.20 + lp*0.10 + vi*0.05, 1)
159
- timeline = [round(float(np.abs(pred_array[t]).mean()), 4) for t in range(n_timesteps)]
160
- mid = n_vertices // 2
161
- dom = "links" if float(np.abs(pred_array[:, :mid]).mean()) >= float(np.abs(pred_array[:, mid:]).mean()) else "rechts"
162
-
163
- return {
164
- "language_processing": lp, "visual_imagery": vi,
165
- "attention_capture": ac, "emotional_valence": ev,
166
- "overall_brain_engagement": be, "viral_potential": viral,
167
- "activation_timeline": timeline, "n_timesteps": n_timesteps,
168
- "n_vertices": n_vertices, "dominant_hemisphere": dom,
169
- "word_count": len(words), "overall_mean_activation": round(overall_mean, 6),
170
- }
171
-
172
-
173
- # ─── Routes ──────────────────────────────────────────────────────────────────
174
-
175
- @app.route("/", methods=["GET"])
176
- def index():
177
- return jsonify({"service": "tribe-v2-api", "status": "ok",
178
- "endpoints": ["/health", "/warmup", "/predict"]})
179
-
180
-
181
- @app.route("/health", methods=["GET"])
182
- def health():
183
- return jsonify({
184
- "status": "ok" if _model_loaded else ("loading" if _model_loading else "offline"),
185
- "model": "tribe-v2",
186
- "model_loaded": _model_loaded,
187
- "model_loading": _model_loading,
188
- "error": _model_error,
189
- })
190
 
 
 
 
191
 
192
- @app.route("/warmup", methods=["POST"])
193
- def warmup():
194
- if not _model_loaded and not _model_loading:
195
- threading.Thread(target=_load_model, daemon=True).start()
196
- return jsonify({"status": "warming_up", "model_loaded": _model_loaded,
197
- "model_loading": _model_loading})
 
 
 
 
 
 
198
 
199
 
200
  @app.route("/predict", methods=["POST"])
201
  def predict():
202
  if not _model_loaded:
203
- return jsonify({"error": "Model not loaded. Call /warmup first.",
204
- "model_loading": _model_loading,
205
- "load_error": _model_error}), 503
206
- data = request.get_json(force=True, silent=True) or {}
207
- text = (data.get("text") or "").strip()[:5000]
208
- if len(text) < 5:
209
- return jsonify({"error": "Text too short (min 5 chars)"}), 400
210
- try:
211
- return jsonify({"scores": _score_text(text), "status": "ok"})
212
- except Exception as e:
213
- return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500
214
-
215
-
216
- # ─── Entry point ─────────────────────────────────────────────────────────────
217
- if __name__ == "__main__":
218
- # Start model loading immediately on startup
219
- threading.Thread(target=_load_model, daemon=True).start()
220
- port = int(os.environ.get("PORT", 7860))
221
- app.run(host="0.0.0.0", port=port, debug=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import tempfile
 
 
3
  import traceback
4
+
5
  import numpy as np
6
+ from flask import request, jsonify
7
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ MAX_UPLOAD_BYTES = 100 * 1024 * 1024 # 100 MB
10
+ ALLOWED_VIDEO = {".mp4", ".mov", ".mkv", ".webm"}
11
+ ALLOWED_AUDIO = {".wav", ".mp3", ".flac", ".m4a", ".ogg"}
12
 
13
+
14
+ def _json_safe(value):
15
+ """Convert NumPy values to JSON-compatible values."""
16
+ if isinstance(value, np.ndarray):
17
+ return value.tolist()
18
+ if isinstance(value, np.generic):
19
+ return value.item()
20
+ if isinstance(value, dict):
21
+ return {str(k): _json_safe(v) for k, v in value.items()}
22
+ if isinstance(value, (list, tuple)):
23
+ return [_json_safe(v) for v in value]
24
+ return value
25
 
26
 
27
  @app.route("/predict", methods=["POST"])
28
  def predict():
29
  if not _model_loaded:
30
+ return jsonify({
31
+ "error": "Model not loaded. Call /warmup first.",
32
+ "model_loading": _model_loading,
33
+ "load_error": _model_error,
34
+ }), 503
35
+
36
+ # Support multipart uploads and JSON text/path inputs.
37
+ if request.files:
38
+ uploaded = (
39
+ request.files.get("video")
40
+ or request.files.get("audio")
41
+ or request.files.get("text_file")
42
+ )
43
+
44
+ if uploaded is None or not uploaded.filename:
45
+ return jsonify({
46
+ "error": "Upload a video, audio, or text_file."
47
+ }), 400
48
+
49
+ filename = uploaded.filename
50
+ ext = os.path.splitext(filename)[1].lower()
51
+
52
+ if uploaded.content_length and uploaded.content_length > MAX_UPLOAD_BYTES:
53
+ return jsonify({"error": "File exceeds 100 MB."}), 413
54
+
55
+ modality = (
56
+ "video" if request.files.get("video") else
57
+ "audio" if request.files.get("audio") else
58
+ "text"
59
+ )
60
+
61
+ allowed = (
62
+ ALLOWED_VIDEO if modality == "video" else
63
+ ALLOWED_AUDIO if modality == "audio" else
64
+ {".txt"}
65
+ )
66
+
67
+ if ext not in allowed:
68
+ return jsonify({"error": "Unsupported file extension."}), 400
69
+
70
+ temp_path = None
71
+
72
+ try:
73
+ # Use a temporary file rather than trusting the uploaded filename.
74
+ with tempfile.NamedTemporaryFile(
75
+ suffix=ext, delete=False
76
+ ) as tmp:
77
+ temp_path = tmp.name
78
+ uploaded.save(tmp)
79
+
80
+ if os.path.getsize(temp_path) > MAX_UPLOAD_BYTES:
81
+ return jsonify({"error": "File exceeds 100 MB."}), 413
82
+
83
+ if modality == "video":
84
+ events = _model.get_events_dataframe(
85
+ video_path=temp_path
86
+ )
87
+ elif modality == "audio":
88
+ events = _model.get_events_dataframe(
89
+ audio_path=temp_path
90
+ )
91
+ else:
92
+ events = _model.get_events_dataframe(
93
+ text_path=temp_path
94
+ )
95
+
96
+ preds, segments = _model.predict(
97
+ events=events, verbose=False
98
+ )
99
+
100
+ except Exception as exc:
101
+ app.logger.exception("TRIBE v2 prediction failed")
102
+ return jsonify({
103
+ "error": str(exc),
104
+ "type": "prediction_failed",
105
+ }), 500
106
+
107
+ finally:
108
+ if temp_path and os.path.exists(temp_path):
109
+ os.remove(temp_path)
110
+
111
+ else:
112
+ data = request.get_json(silent=True) or {}
113
+ text = (data.get("text") or "").strip()
114
+
115
+ if len(text) < 5:
116
+ return jsonify({
117
+ "error": (
118
+ "Provide a text string of at least 5 characters, "
119
+ "or upload a video/audio/text file."
120
+ )
121
+ }), 400
122
+
123
+ # Avoid an unbounded text request.
124
+ if len(text) > 5000:
125
+ return jsonify({"error": "Text exceeds 5000 characters."}), 400
126
+
127
+ try:
128
+ with tempfile.NamedTemporaryFile(
129
+ mode="w",
130
+ suffix=".txt",
131
+ encoding="utf-8",
132
+ delete=False,
133
+ ) as tmp:
134
+ tmp.write(text)
135
+ temp_path = tmp.name
136
+
137
+ try:
138
+ events = _model.get_events_dataframe(
139
+ text_path=temp_path
140
+ )
141
+ preds, segments = _model.predict(
142
+ events=events, verbose=False
143
+ )
144
+ finally:
145
+ if os.path.exists(temp_path):
146
+ os.remove(temp_path)
147
+
148
+ except Exception as exc:
149
+ app.logger.exception("TRIBE v2 prediction failed")
150
+ return jsonify({
151
+ "error": str(exc),
152
+ "type": "prediction_failed",
153
+ }), 500
154
+
155
+ preds = np.asarray(
156
+ preds.detach().cpu().numpy()
157
+ if hasattr(preds, "detach")
158
+ else preds
159
+ )
160
+
161
+ return jsonify({
162
+ "status": "ok",
163
+ "model": "facebook/tribev2",
164
+ "modality": modality if request.files else "text",
165
+ "prediction": {
166
+ "shape": list(preds.shape),
167
+ "n_timesteps": int(preds.shape[0]),
168
+ "n_vertices": int(preds.shape[1])
169
+ if preds.ndim > 1 else 1,
170
+ "segments": _json_safe(segments),
171
+ "activation_mean_abs": float(np.abs(preds).mean()),
172
+ "activation_std": float(preds.std()),
173
+ },
174
+ })