Spaces:
Sleeping
Sleeping
Download app.py from modernmuse2026/brain-analyzer: direct link, hf CLI and curl.
- Browser
- Download file 7.77 kB
-
https://huggingface.co/spaces/modernmuse2026/brain-analyzer/resolve/main/app.py
- Command line
-
hf download hf://spaces/modernmuse2026/brain-analyzer/app.py
-
curl -L -o app.py https://huggingface.co/spaces/modernmuse2026/brain-analyzer/resolve/main/app.py
7.77 kB
| import os | |
| os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0" | |
| import gradio as gr | |
| import numpy as np | |
| import tempfile | |
| import subprocess | |
| import shutil | |
| from pathlib import Path | |
| import pandas as pd | |
| # ββ Ensure uvx on PATH βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def ensure_uvx(): | |
| if shutil.which("uvx"): | |
| return | |
| print("Installing uv...") | |
| subprocess.run("curl -LsSf https://astral.sh/uv/install.sh | sh", | |
| shell=True, capture_output=True) | |
| for p in [Path.home()/".local/bin", Path.home()/".cargo/bin", Path("/root/.local/bin")]: | |
| if (p/"uvx").exists(): | |
| os.environ["PATH"] = str(p) + ":" + os.environ.get("PATH","") | |
| print(f"uvx at {p}") | |
| return | |
| ensure_uvx() | |
| # ββ Patch: intercept _get_transcript_from_audio to return empty DataFrame ββββ | |
| # From traceback line 184: transcript.to_csv(...) β transcript must be a DataFrame | |
| # with columns: word, start, end (at minimum) | |
| def _patch_tribev2(): | |
| try: | |
| import tribev2.eventstransforms as et | |
| import inspect | |
| EMPTY_TRANSCRIPT = pd.DataFrame(columns=["word", "start", "end", "score"]) | |
| def _skip_transcript(self, wav_filename, language): | |
| print(f"[PATCH] Skipping whisperx for {wav_filename}") | |
| return EMPTY_TRANSCRIPT | |
| patched = False | |
| for name in dir(et): | |
| obj = getattr(et, name) | |
| if isinstance(obj, type) and hasattr(obj, '_get_transcript_from_audio'): | |
| obj._get_transcript_from_audio = _skip_transcript | |
| print(f"[PATCH] Patched {name}._get_transcript_from_audio β empty DataFrame") | |
| patched = True | |
| if not patched: | |
| # Fallback: patch at module level if class not found directly | |
| print("[PATCH] No class found, trying module-level patch") | |
| src = inspect.getsource(et) | |
| print("[PATCH] Classes in eventstransforms:", | |
| [name for name in dir(et) if isinstance(getattr(et, name), type)]) | |
| except Exception as e: | |
| import traceback | |
| print(f"[PATCH ERROR] {e}\n{traceback.format_exc()}") | |
| _patch_tribev2() | |
| # ββ Lazy model loading ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _model = None | |
| _brain = None | |
| CACHE = Path("./cache") | |
| CACHE.mkdir(exist_ok=True) | |
| def get_model(): | |
| global _model, _brain | |
| if _model is None: | |
| from tribev2 import TribeModel | |
| from tribev2.plotting import PlotBrain | |
| print("Loading TRIBE v2 model...") | |
| _model = TribeModel.from_pretrained("facebook/tribev2", cache_folder=str(CACHE)) | |
| _brain = PlotBrain() | |
| print("Model ready β") | |
| return _model, _brain | |
| ROIS = { | |
| "Visual cortex": slice(0, 2000), | |
| "Auditory cortex": slice(2000, 4000), | |
| "Language areas": slice(4000, 6000), | |
| "Prefrontal cortex": slice(6000, 8000), | |
| } | |
| def score_label(val): | |
| if val > 0.7: return "π₯ Very High" | |
| if val > 0.5: return "β High" | |
| if val > 0.3: return "β‘οΈ Moderate" | |
| return "π€ Low" | |
| def predict(video_file): | |
| if video_file is None: | |
| return None, "β οΈ Please upload a video first.", "" | |
| try: | |
| model, brain = get_model() | |
| df = model.get_events_dataframe(video_path=video_file) | |
| preds, segments = model.predict(events=df) | |
| mean_activation = np.abs(preds).mean(axis=0) | |
| with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f: | |
| brain_img_path = f.name | |
| brain.plot_surface(mean_activation, output_path=brain_img_path, title="Brain activation") | |
| overall = float(np.abs(preds).mean()) | |
| md = "## π§ Brain Engagement Report\n\n" | |
| md += "> βΉοΈ _Analysed using video + audio (text modality disabled on CPU)_\n\n" | |
| md += f"**Overall score: `{overall:.3f}`**\n\n" | |
| md += "| Region | Activation | Level |\n|---|---|---|\n" | |
| for name, sl in ROIS.items(): | |
| v = float(mean_activation[sl].mean()) | |
| md += f"| {name} | `{v:.3f}` | {score_label(v)} |\n" | |
| peak_t = int(np.abs(preds).mean(axis=1).argmax()) | |
| md += f"\n**β± Peak activity at:** `{peak_t}s`" | |
| if overall > 0.5: | |
| md += "\n\n> π― Strong cortical engagement β likely stimulating and memorable." | |
| elif overall > 0.3: | |
| md += "\n\n> π Decent engagement β solid activation overall." | |
| else: | |
| md += "\n\n> π΄ Low engagement β consider more dynamic visuals or audio." | |
| return brain_img_path, md, "" | |
| except Exception as e: | |
| import traceback | |
| return None, f"β Error: {str(e)}\n\n```\n{traceback.format_exc()}\n```", "" | |
| CSS = """ | |
| @import url('https://fonts.googleapis.com/css2?family=Syne:wght@400;700;800&family=DM+Mono:wght@400;500&display=swap'); | |
| :root{--bg:#0a0a0f;--surface:#13131a;--border:#1e1e2e;--accent:#00e5ff;--accent2:#ff4ecd;--text:#e2e2ef;--muted:#6b6b8a;} | |
| body,.gradio-container{background:var(--bg)!important;font-family:'Syne',sans-serif!important;color:var(--text)!important;} | |
| .gradio-container{max-width:1100px!important;margin:0 auto!important;} | |
| #title-block{text-align:center;padding:3rem 1rem 2rem;background:radial-gradient(ellipse 80% 50% at 50% 0%,rgba(0,229,255,0.08) 0%,transparent 70%);border-bottom:1px solid var(--border);margin-bottom:2rem;} | |
| #title-block h1{font-size:2.8rem;font-weight:800;letter-spacing:-0.03em;background:linear-gradient(135deg,var(--accent) 0%,var(--accent2) 100%);-webkit-background-clip:text;-webkit-text-fill-color:transparent;margin:0 0 0.5rem;} | |
| #title-block p{color:var(--muted);font-size:1rem;font-family:'DM Mono',monospace;margin:0;} | |
| .panel{background:var(--surface)!important;border:1px solid var(--border)!important;border-radius:12px!important;} | |
| button.primary{background:linear-gradient(135deg,var(--accent),var(--accent2))!important;color:#000!important;font-family:'Syne',sans-serif!important;font-weight:700!important;border:none!important;border-radius:8px!important;padding:12px 32px!important;font-size:1rem!important;cursor:pointer!important;width:100%!important;margin-top:1rem!important;} | |
| .footer-note{text-align:center;color:var(--muted);font-size:0.78rem;font-family:'DM Mono',monospace;padding:1.5rem;border-top:1px solid var(--border);margin-top:2rem;} | |
| """ | |
| with gr.Blocks(css=CSS, title="TRIBE v2 β Brain Engagement Analyzer") as demo: | |
| gr.HTML('<div id="title-block"><h1>TRIBE v2</h1><p>// upload a video β see how the human brain reacts //</p></div>') | |
| with gr.Row(): | |
| with gr.Column(scale=1, elem_classes="panel"): | |
| gr.Markdown("### πΉ Upload your video") | |
| video_input = gr.Video(label="", height=280) | |
| run_btn = gr.Button("Analyze Brain Response β", variant="primary") | |
| gr.Markdown("_Supports `.mp4`, `.mov`, `.avi`. Best results with videos under 2 minutes._") | |
| with gr.Column(scale=1, elem_classes="panel"): | |
| gr.Markdown("### π§ Brain surface activation") | |
| brain_output = gr.Image(label="", height=280, show_label=False) | |
| with gr.Row(): | |
| with gr.Column(elem_classes="panel"): | |
| report_output = gr.Markdown("_Results will appear here after analysis..._") | |
| error_output = gr.Textbox(visible=False) | |
| run_btn.click(fn=predict, inputs=[video_input], outputs=[brain_output, report_output, error_output]) | |
| gr.HTML('<div class="footer-note">Powered by TRIBE v2 (Meta AI Research) Β· CC BY-NC 4.0 Β· For research use only</div>') | |
| if __name__ == "__main__": | |
| demo.launch() |