clone3 commited on
Commit
5dbf298
Β·
verified Β·
1 Parent(s): 10b69eb

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +29 -0
  2. README.md +26 -9
  3. app.py +215 -44
  4. gitattributes +35 -0
  5. requirements.txt +7 -0
Dockerfile ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # System dependencies
6
+ RUN apt-get update && apt-get install -y \
7
+ git \
8
+ curl \
9
+ build-essential \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ # Install tribev2 from GitHub first (not on PyPI)
13
+ RUN pip install --no-cache-dir git+https://github.com/facebookresearch/tribev2.git
14
+
15
+ # Install remaining dependencies
16
+ COPY requirements.txt .
17
+ RUN pip install --no-cache-dir -r requirements.txt
18
+
19
+ # Cache-bust: v6 (CPU fix: object.__setattr__ to bypass pydantic immutability)
20
+ LABEL version="6"
21
+
22
+ # Copy app
23
+ COPY app.py .
24
+
25
+ EXPOSE 7860
26
+ ENV PORT=7860
27
+ ENV PYTHONUNBUFFERED=1
28
+
29
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,13 +1,30 @@
1
  ---
2
- title: ProtocolDroidSMTPXMPPHTTP
3
- emoji: πŸ‘
4
- colorFrom: blue
5
- colorTo: yellow
6
- sdk: streamlit
7
- sdk_version: 1.31.1
8
- app_file: app.py
9
  pinned: false
10
- license: mit
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Tribe V2 Brain Prediction API
3
+ emoji: 🧠
4
+ colorFrom: purple
5
+ colorTo: pink
6
+ sdk: docker
 
 
7
  pinned: false
8
+ license: other
9
  ---
10
 
11
+ # Tribe V2 Brain Predictive Model – REST API
12
+
13
+ This Space exposes Meta's [Tribe V2](https://ai.meta.com/blog/tribe-v2-brain-predictive-foundation-model/) brain predictive model as a REST API for content scoring.
14
+
15
+ ## Endpoints
16
+
17
+ | Method | Path | Description |
18
+ |--------|------|-------------|
19
+ | `GET` | `/health` | Service status + model_loaded flag |
20
+ | `POST` | `/warmup` | Pre-load the model |
21
+ | `POST` | `/predict` | `{ "text": "..." }` β†’ brain activation scores |
22
+
23
+ ## Score Dimensions
24
+
25
+ - **language_processing** – Language region activation (IFG / STG)
26
+ - **visual_imagery** – Visual cortex activation (V1–V4)
27
+ - **attention_capture** – Attention network activation (IPS / FEF)
28
+ - **emotional_valence** – Reward/emotion network (vmPFC proxy)
29
+ - **overall_brain_engagement** – Default mode network (DMN)
30
+ - **viral_potential** – Weighted composite score (0–100)
app.py CHANGED
@@ -1,50 +1,221 @@
1
- import streamlit as st
2
- import smtplib
3
- from email.message import EmailMessage
4
- import http.client
5
- import requests
6
-
7
- # SMTP Example (Simplified)
8
- def smtp_client(server, port, from_email, to_email, subject, message):
9
- msg = EmailMessage()
10
- msg.set_content(message)
11
- msg['Subject'] = subject
12
- msg['From'] = from_email
13
- msg['To'] = to_email
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  try:
16
- with smtplib.SMTP(server, port) as smtp:
17
- smtp.send_message(msg)
18
- return "Email sent successfully!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  except Exception as e:
20
- return f"Failed to send email: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # HTTP Example
23
- def http_client(url):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  try:
25
- response = requests.get(url)
26
- return response.text[:500] # Return the first 500 characters for brevity
27
  except Exception as e:
28
- return f"Failed to retrieve the URL: {e}"
29
-
30
- # Streamlit UI
31
- st.title("Internet Communication Protocols Demo 🌐")
32
-
33
- # SMTP Section
34
- st.header("SMTP Demo πŸ“§")
35
- smtp_server = st.text_input("SMTP Server", value="smtp.example.com")
36
- smtp_port = st.text_input("SMTP Port", value="587")
37
- from_email = st.text_input("From Email", value="from@example.com")
38
- to_email = st.text_input("To Email", value="to@example.com")
39
- subject = st.text_input("Subject", value="Test Email")
40
- message = st.text_area("Message", value="This is a test email.")
41
- if st.button("Send Email"):
42
- result = smtp_client(smtp_server, smtp_port, from_email, to_email, subject, message)
43
- st.success(result)
44
-
45
- # HTTP Section
46
- st.header("HTTP Demo 🌐")
47
- url = st.text_input("URL to fetch", value="http://example.com")
48
- if st.button("Fetch URL"):
49
- result = http_client(url)
50
- st.text_area("Response", value=result, height=250)
 
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ flask>=3.0.0
2
+ numpy>=1.24.0
3
+ pandas>=2.0.0
4
+ torch>=2.1.0
5
+ transformers>=4.40.0
6
+ huggingface_hub>=0.23.0
7
+ # tribev2 installed via Dockerfile from GitHub