clone3 commited on
Commit
a72dc05
Β·
verified Β·
1 Parent(s): 0e2d818

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +382 -154
app.py CHANGED
@@ -1,174 +1,402 @@
 
 
 
 
 
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
- })
 
1
+ """
2
+ Tribe V2 Brain Predictive Model – Gradio App
3
+ Deployed on Hugging Face Spaces (CPU)
4
+ """
5
+
6
  import os
7
+ import math
8
+ import warnings
9
+ import threading
10
  import traceback
11
 
12
  import numpy as np
13
+ import gradio as gr
14
+
15
+ warnings.filterwarnings("ignore")
16
+
17
+ # ─── Configuration ────────────────────────────────────────────────────────
18
+
19
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
20
+ CKPT = os.environ.get("TRIBE_CKPT", "facebook/tribev2")
21
+
22
+ _model = None
23
+ _model_loaded = False
24
+ _model_loading = False
25
+ _model_error = None
26
+ _model_lock = threading.Lock()
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
+ # ─── Model loading ───────────────────────────────────────────────────────
39
+
40
+ def _load_model():
41
+ global _model, _model_loaded, _model_loading, _model_error
42
+
43
+ with _model_lock:
44
+ if _model_loaded or _model_loading:
45
+ return
46
+ _model_loading = True
47
+ _model_error = None
48
+
49
+ try:
50
+ print("[Tribe V2] Starting model load...", flush=True)
51
+
52
+ if HF_TOKEN:
53
+ os.environ["HF_TOKEN"] = HF_TOKEN
54
+ os.environ["HUGGING_FACE_HUB_TOKEN"] = HF_TOKEN
55
+
56
+ try:
57
+ from huggingface_hub import login
58
+ login(token=HF_TOKEN, add_to_git_credential=False)
59
+ print("[Tribe V2] Hugging Face login OK", flush=True)
60
+ except Exception as e:
61
+ print(f"[Tribe V2] Login warning: {e}", flush=True)
62
+
63
+ import torch
64
+ print(f"[Tribe V2] PyTorch {torch.__version__}", flush=True)
65
+
66
+ # Force neuralset text extractor to CPU.
67
+ try:
68
+ from neuralset.extractors.text import HuggingFaceText
69
+
70
+ orig_load = HuggingFaceText._load_model
71
+
72
+ def cpu_patched_load(self):
73
+ object.__setattr__(self, "device", "cpu")
74
+ return orig_load(self)
75
+
76
+ HuggingFaceText._load_model = cpu_patched_load
77
+ print("[Tribe V2] CPU patch applied", flush=True)
78
+
79
+ except Exception as e:
80
+ print(f"[Tribe V2] CPU patch warning: {e}", flush=True)
81
+
82
+ from tribev2 import TribeModel
83
+
84
+ print(f"[Tribe V2] Loading {CKPT}...", flush=True)
85
+ model = TribeModel.from_pretrained(CKPT, device="cpu")
86
+
87
+ with _model_lock:
88
+ _model = model
89
+ _model_loaded = True
90
+ _model_loading = False
91
+ _model_error = None
92
+
93
+ print("[Tribe V2] Model ready!", flush=True)
94
+
95
+ except Exception as e:
96
+ traceback.print_exc()
97
+
98
+ with _model_lock:
99
+ _model_loading = False
100
+ _model_error = str(e)
101
+
102
+
103
+ def model_status():
104
+ with _model_lock:
105
+ if _model_loaded:
106
+ return "🟒 Model loaded and ready"
107
+ if _model_loading:
108
+ return "🟑 Model is loading..."
109
+ if _model_error:
110
+ return f"πŸ”΄ Model loading failed: {_model_error}"
111
+ return "βšͺ Model not loaded"
112
+
113
+
114
+ def warmup():
115
+ with _model_lock:
116
+ if _model_loaded:
117
+ return "🟒 Model already loaded"
118
+ if _model_loading:
119
+ return "🟑 Model is already loading"
120
+
121
+ threading.Thread(target=_load_model, daemon=True).start()
122
+ return "🟑 Model loading started. Check status shortly."
123
+
124
+
125
+ # ─── Scoring ────────────────────────────────────────────────────────────��
126
+
127
+ def _normalize_roi(val, overall):
128
+ if overall == 0:
129
+ return 50.0
130
+
131
+ ratio = val / overall
132
+ score = 50 + 50 * math.tanh((ratio - 1.0) * 2)
133
+
134
+ return round(min(100.0, max(0.0, score)), 1)
135
+
136
+
137
+ def _score_text(text):
138
+ import pandas as pd
139
+
140
+ words = [w for w in text.split() if w.strip()]
141
+
142
+ if not words:
143
+ raise ValueError("Empty text")
144
+
145
+ duration = 0.5
146
+
147
+ rows = [
148
+ {
149
+ "type": "Word",
150
+ "text": word,
151
+ "context": text,
152
+ "start": i * duration,
153
+ "duration": duration,
154
+ "timeline": "default",
155
+ }
156
+ for i, word in enumerate(words)
157
+ ]
158
+
159
+ events_df = pd.DataFrame(rows)
160
+
161
+ result = _model.predict(events_df, verbose=False)
162
+ pred_array = result[0] if isinstance(result, tuple) else result
163
+
164
+ if hasattr(pred_array, "numpy"):
165
+ pred_array = pred_array.numpy()
166
+
167
+ pred_array = np.asarray(pred_array)
168
+
169
+ if pred_array.ndim == 1:
170
+ pred_array = pred_array.reshape(1, -1)
171
+
172
+ n_timesteps, n_vertices = pred_array.shape
173
+ overall_mean = float(np.abs(pred_array).mean())
174
+
175
+ def roi_score(indices):
176
+ safe = [i for i in indices if i < n_vertices]
177
+ if not safe:
178
+ return overall_mean
179
+ return float(np.abs(pred_array[:, safe]).mean())
180
+
181
+ lang = roi_score(ROI_INDICES["language"])
182
+ vis = roi_score(ROI_INDICES["visual"])
183
+ att = roi_score(ROI_INDICES["attention"])
184
+ emo = roi_score(ROI_INDICES["emotion"])
185
+ dmn = roi_score(ROI_INDICES["default"])
186
+
187
+ lp = _normalize_roi(lang, overall_mean)
188
+ vi = _normalize_roi(vis, overall_mean)
189
+ ac = _normalize_roi(att, overall_mean)
190
+ ev = _normalize_roi(emo, overall_mean)
191
+ be = _normalize_roi(dmn, overall_mean)
192
+
193
+ viral = round(
194
+ be * 0.35
195
+ + ev * 0.30
196
+ + ac * 0.20
197
+ + lp * 0.10
198
+ + vi * 0.05,
199
+ 1,
200
+ )
201
+
202
+ timeline = [
203
+ round(float(np.abs(pred_array[t]).mean()), 4)
204
+ for t in range(n_timesteps)
205
+ ]
206
+
207
+ mid = n_vertices // 2
208
+
209
+ left_mean = float(np.abs(pred_array[:, :mid]).mean())
210
+ right_mean = float(np.abs(pred_array[:, mid:]).mean())
211
+
212
+ dom = "Left" if left_mean >= right_mean else "Right"
213
+
214
+ return {
215
+ "language_processing": lp,
216
+ "visual_imagery": vi,
217
+ "attention_capture": ac,
218
+ "emotional_valence": ev,
219
+ "overall_brain_engagement": be,
220
+ "viral_potential": viral,
221
+ "activation_timeline": timeline,
222
+ "n_timesteps": n_timesteps,
223
+ "n_vertices": n_vertices,
224
+ "dominant_hemisphere": dom,
225
+ "word_count": len(words),
226
+ "overall_mean_activation": round(overall_mean, 6),
227
+ }
228
+
229
+
230
+ # ─── Gradio prediction handler ───────────────────────────────────────────
231
+
232
+ def predict(text):
233
+ text = (text or "").strip()[:5000]
234
+
235
+ if len(text) < 5:
236
+ raise gr.Error("Please enter at least 5 characters.")
237
+
238
+ with _model_lock:
239
+ loaded = _model_loaded
240
+ loading = _model_loading
241
+ error = _model_error
242
+
243
+ if not loaded:
244
+ if loading:
245
+ raise gr.Error("Model is still loading. Please try again shortly.")
246
+ if error:
247
+ raise gr.Error(f"Model failed to load: {error}")
248
+ raise gr.Error("Model is not loaded. Click Load Model first.")
249
+
250
+ try:
251
+ scores = _score_text(text)
252
+
253
+ table = [
254
+ ["Language Processing", scores["language_processing"]],
255
+ ["Visual Imagery", scores["visual_imagery"]],
256
+ ["Attention Capture", scores["attention_capture"]],
257
+ ["Emotional Valence", scores["emotional_valence"]],
258
+ ["Brain Engagement", scores["overall_brain_engagement"]],
259
+ ["Viral Potential", scores["viral_potential"]],
260
+ ]
261
+
262
+ timeline = scores["activation_timeline"]
263
+
264
+ details = {
265
+ "Word count": scores["word_count"],
266
+ "Timesteps": scores["n_timesteps"],
267
+ "Vertices": scores["n_vertices"],
268
+ "Dominant hemisphere": scores["dominant_hemisphere"],
269
+ "Mean activation": scores["overall_mean_activation"],
270
+ }
271
+
272
+ return (
273
+ table,
274
+ {
275
+ "viral_potential": scores["viral_potential"],
276
+ "overall_brain_engagement": scores[
277
+ "overall_brain_engagement"
278
+ ],
279
+ },
280
+ timeline,
281
+ details,
282
  )
283
 
284
+ except gr.Error:
285
+ raise
286
+ except Exception as e:
287
+ traceback.print_exc()
288
+ raise gr.Error(f"Prediction failed: {str(e)}")
289
+
290
+
291
+ # ─── Gradio UI ──────────────────────────────────────────────��────────────
292
 
293
+ with gr.Blocks(title="Tribe V2 Brain Predictive Model") as demo:
 
294
 
295
+ gr.Markdown(
296
+ """
297
+ # 🧠 Tribe V2 Brain Predictive Model
298
+
299
+ Analyze text using the Tribe V2 prediction model.
300
+
301
+ Enter text to calculate model-derived activation scores.
302
+ """
303
+ )
304
 
305
+ with gr.Row():
306
+ status = gr.Textbox(
307
+ label="Model Status",
308
+ value=model_status(),
309
+ interactive=False,
310
  )
311
+ load_btn = gr.Button("Load Model", variant="secondary")
312
+ refresh_btn = gr.Button("Refresh Status")
313
+
314
+ load_btn.click(
315
+ fn=warmup,
316
+ outputs=status,
317
+ )
318
+
319
+ refresh_btn.click(
320
+ fn=model_status,
321
+ outputs=status,
322
+ )
323
+
324
+ text_input = gr.Textbox(
325
+ label="Text to Analyze",
326
+ placeholder="Enter your text here...",
327
+ lines=6,
328
+ max_lines=12,
329
+ )
330
 
331
+ predict_btn = gr.Button("Analyze Text", variant="primary")
332
+
333
+ with gr.Row():
334
+ score_table = gr.Dataframe(
335
+ headers=["Metric", "Score (0–100)"],
336
+ label="Prediction Scores",
337
+ datatype=["str", "number"],
338
+ interactive=False,
339
+ )
340
+
341
+ with gr.Row():
342
+ viral_output = gr.Number(
343
+ label="Viral Potential (model-derived score)",
344
+ precision=1,
345
+ )
346
+ engagement_output = gr.Number(
347
+ label="Brain Engagement (model-derived score)",
348
+ precision=1,
349
  )
350
 
351
+ timeline_output = gr.LinePlot(
352
+ x="timestep",
353
+ y="activation",
354
+ title="Activation Timeline",
355
+ x_title="Timestep",
356
+ y_title="Mean Absolute Activation",
357
+ show_legend=False,
358
+ )
359
 
360
+ details_output = gr.JSON(label="Prediction Details")
361
 
362
+ predict_btn.click(
363
+ fn=lambda text: (
364
+ lambda result: (
365
+ result[0],
366
+ result[1]["viral_potential"],
367
+ result[1]["overall_brain_engagement"],
368
+ {
369
+ "timestep": list(range(len(result[2]))),
370
+ "activation": result[2],
371
+ },
372
+ result[3],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  )
374
+ )(predict(text)),
375
+ inputs=text_input,
376
+ outputs=[
377
+ score_table,
378
+ viral_output,
379
+ engagement_output,
380
+ timeline_output,
381
+ details_output,
382
+ ],
383
+ )
384
 
385
+ gr.Markdown(
386
+ """
387
+ ---
388
+ **Note:** These outputs are model-derived numerical scores, not
389
+ validated measurements of actual brain activity or a guarantee
390
+ that content will go viral.
391
+ """
392
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
 
 
 
 
 
 
 
 
 
 
394
 
395
+ if __name__ == "__main__":
396
+ # Load the model in the background when the Space starts.
397
+ threading.Thread(target=_load_model, daemon=True).start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
 
399
+ demo.queue().launch(
400
+ server_name="0.0.0.0",
401
+ server_port=int(os.environ.get("PORT", 7860)),
402
+ )