Download app.py from facebook/tribev2: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/facebook/tribev2/resolve/refs%2Fpr%2F14/app.py
- Command line
-
hf download hf://facebook/tribev2@refs/pr/14/app.py
-
curl -L -o app.py https://huggingface.co/facebook/tribev2/resolve/refs%2Fpr%2F14/app.py
10.8 kB
| """TRIBE v2 research-only, one-click multimodal smoke test for HF ZeroGPU.""" | |
| import functools | |
| import io | |
| import json | |
| import os | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import traceback | |
| import urllib.request | |
| import zipfile | |
| from pathlib import Path | |
| # WhisperX is executed in an isolated uvx subprocess. Do not leak hf_transfer setting. | |
| os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0" | |
| os.environ.setdefault("HF_HOME", "/tmp/hf-home") | |
| import gradio as gr | |
| import numpy as np | |
| import spaces | |
| import torch | |
| from huggingface_hub import hf_hub_download | |
| REPO_DIR = Path("/tmp/tribev2-main") | |
| CACHE_DIR = Path("/tmp/tribev2-cache") | |
| CACHE_DIR.mkdir(parents=True, exist_ok=True) | |
| def ensure_official_code(): | |
| if not (REPO_DIR / "tribev2" / "__init__.py").is_file(): | |
| url = "https://github.com/facebookresearch/tribev2/archive/refs/heads/main.zip" | |
| with urllib.request.urlopen(url, timeout=90) as response: | |
| archive = response.read() | |
| with zipfile.ZipFile(io.BytesIO(archive)) as z: | |
| z.extractall("/tmp") | |
| if str(REPO_DIR) not in sys.path: | |
| sys.path.insert(0, str(REPO_DIR)) | |
| def check_video(video): | |
| if not video or not Path(video).is_file(): | |
| raise ValueError("Сначала загрузите MP4") | |
| if Path(video).suffix.lower() not in {".mp4", ".mov", ".webm", ".mkv", ".avi"}: | |
| raise ValueError("Нужен MP4/MOV/WEBM/MKV/AVI") | |
| cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", str(video)] | |
| proc = subprocess.run(cmd, capture_output=True, text=True, timeout=15) | |
| if proc.returncode: | |
| raise RuntimeError(f"ffprobe error: {proc.stderr[-2000:]}") | |
| duration = float(proc.stdout.strip()) | |
| if duration < 1 or duration > 20: | |
| raise ValueError(f"Видео {duration:.1f} сек. Для первого теста загрузите клип от 1 до 20 сек.") | |
| return duration | |
| def run_full_pipeline(video, language, include_speech, progress=gr.Progress()): | |
| logs = [] | |
| output_dir = Path(tempfile.mkdtemp(prefix="tribe_test_")) | |
| t0 = time.monotonic() | |
| stage = "START" | |
| checkpoint = {} | |
| def log(msg): | |
| logs.append(f"[{time.monotonic()-t0:6.1f}s] {msg}") | |
| print(logs[-1], flush=True) | |
| def update(position, text): | |
| progress(position, desc=text) | |
| log(text) | |
| try: | |
| stage = "PREFLIGHT" | |
| update(0.03, "Проверяю инструменты, доступ и входной файл") | |
| for tool in ["ffmpeg", "ffprobe", "uvx"]: | |
| if not shutil.which(tool): | |
| raise RuntimeError(f"Не найден {tool}. Проверьте packages.txt (ffmpeg) и requirements.txt (uv).") | |
| duration = check_video(video) | |
| log(f"Видео: {duration:.1f} сек | {Path(video).stat().st_size/1024**2:.2f} МБ") | |
| log(f"GPU: {torch.cuda.get_device_name(0)} | PyTorch: {torch.__version__}") | |
| token = os.environ.get("HF_TOKEN") | |
| log(f"HF_TOKEN: {'задан' if token else 'не задан'}") | |
| if include_speech: | |
| try: | |
| hf_hub_download("meta-llama/Llama-3.2-3B", "config.json", token=token or None) | |
| log("Доступ к Llama 3.2-3B: OK") | |
| except Exception as ex: | |
| log(f"Доступ к Llama 3.2-3B не подтверждён: {type(ex).__name__}: {str(ex)[:350]}") | |
| # Continue: some paths can process audio/video without text features. | |
| stage = "IMPORT" | |
| update(0.12, "Подключаю официальный код Meta") | |
| ensure_official_code() | |
| from tribev2 import TribeModel | |
| from tribev2 import demo_utils as du | |
| from tribev2.demo_utils import get_audio_and_text_events | |
| import pandas as pd | |
| stage = "MODEL" | |
| update(0.20, "Загружаю TRIBE v2 на GPU") | |
| model = TribeModel.from_pretrained( | |
| "facebook/tribev2", cache_folder=str(CACHE_DIR), device="cuda" | |
| ) | |
| log(f"Нейросеть: {sum(p.numel() for p in model._model.parameters()):,} параметров") | |
| log(f"VRAM: {torch.cuda.memory_allocated()/1024**3:.2f} ГБ") | |
| stage = "EVENTS" | |
| update(0.35, "Извлекаю события из видео и аудиодорожки") | |
| used_mode = "video_audio_no_transcript" | |
| if include_speech: | |
| old_constructor = du.ExtractWordsFromAudio | |
| try: | |
| # Meta defaults to English; force Spanish for Spanish-language Reels. | |
| du.ExtractWordsFromAudio = functools.partial(old_constructor, language=language) | |
| events = model.get_events_dataframe(video_path=str(video)) | |
| used_mode = "video_audio_text" | |
| log(f"Полный режим: OK, язык распознавания {language}") | |
| except Exception as ex: | |
| log(f"Полный режим не прошёл: {type(ex).__name__}: {str(ex)[-900:]}") | |
| if time.monotonic() - t0 > 175: | |
| raise RuntimeError("Не осталось времени на запасной режим. Смотрите журнал выше.") from ex | |
| log("Пробую официальный режим без транскрипции (video + audio).") | |
| raw = pd.DataFrame([{ | |
| "type": "Video", "filepath": str(video), "start": 0, | |
| "timeline": "default", "subject": "default" | |
| }]) | |
| events = get_audio_and_text_events(raw, audio_only=True) | |
| finally: | |
| du.ExtractWordsFromAudio = old_constructor | |
| else: | |
| raw = pd.DataFrame([{ | |
| "type": "Video", "filepath": str(video), "start": 0, | |
| "timeline": "default", "subject": "default" | |
| }]) | |
| events = get_audio_and_text_events(raw, audio_only=True) | |
| counts = events["type"].value_counts().to_dict() | |
| log(f"События: {counts}") | |
| stage = "PREDICT" | |
| update(0.58, "Загружаю мультимодальные энкодеры и считаю fMRI-прогноз") | |
| predictions, segments = model.predict(events=events, verbose=False) | |
| predictions = np.asarray(predictions, dtype=np.float32) | |
| if predictions.ndim != 2 or not predictions.shape[0]: | |
| raise RuntimeError(f"Некорректная форма предсказаний: {predictions.shape}") | |
| log(f"PREDICTION SUCCESS: shape={predictions.shape}, segments={len(segments)}") | |
| stage = "REPORT" | |
| update(0.87, "Строю график и сохраняю результаты") | |
| # Purely descriptive aggregation; NOT attention, emotion or conversion. | |
| activity = np.nanmean(np.abs(predictions), axis=1) | |
| tr_seconds = float(model.data.TR) | |
| times = np.arange(predictions.shape[0]) * tr_seconds | |
| npz_file = output_dir / "brain_predictions.npz" | |
| json_file = output_dir / "summary.json" | |
| chart_file = output_dir / "brain_timeline.png" | |
| np.savez_compressed(npz_file, predictions=predictions, time_seconds=times) | |
| checkpoint = { | |
| "status": "success", "mode": used_mode, "language": language, | |
| "input_duration_seconds": duration, | |
| "prediction_shape": list(predictions.shape), | |
| "n_segments": len(segments), "TR_seconds": tr_seconds, | |
| "mean_absolute_predicted_signal": activity.tolist(), | |
| "time_seconds": times.tolist(), | |
| "important": "Предсказанная нейронная fMRI-активность среднего субъекта, НЕ внимание/эмоции/конверсия. Около 5 сек поправки на гемодинамический лаг по документации Meta.", | |
| "warnings": [line for line in logs if "не прош" in line or "не подтвержд" in line], | |
| } | |
| json_file.write_text(json.dumps(checkpoint, ensure_ascii=False, indent=2), encoding="utf-8") | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| fig, ax = plt.subplots(figsize=(10, 4)) | |
| ax.plot(times, activity) | |
| ax.set_xlabel("Время предсказанного сигнала, сек (с учётом особенностей fMRI)") | |
| ax.set_ylabel("Средний |fMRI-прогноз| по вершинам") | |
| ax.set_title("TRIBE v2: прогнозированная fMRI-активность (не метрика внимания)") | |
| fig.tight_layout() | |
| fig.savefig(chart_file, dpi=130) | |
| plt.close(fig) | |
| update(1, "Готово") | |
| return "\n".join(logs), str(chart_file), [str(json_file), str(npz_file)] | |
| except Exception: | |
| error_text = traceback.format_exc() | |
| log(f"ОШИБКА на этапе {stage}:\n{error_text}") | |
| diagnostic = output_dir / "diagnostics.txt" | |
| diagnostic.write_text("\n".join(logs), encoding="utf-8") | |
| return "\n".join(logs), None, [str(diagnostic)] | |
| finally: | |
| if torch.cuda.is_available(): | |
| try: | |
| torch.cuda.empty_cache() | |
| except Exception: | |
| pass | |
| with gr.Blocks(title="TRIBE v2 — All-in-one Research Test") as demo: | |
| gr.Markdown("# TRIBE v2 — полная проверка видео\nИсследовательский тест модели Meta на HF ZeroGPU. НЕ коммерческий скоринг Reels.") | |
| with gr.Row(): | |
| video_input = gr.Video(label="MP4 5–10 секунд для первого теста", format="mp4") | |
| with gr.Column(): | |
| language_input = gr.Dropdown(choices=[("Испанский", "spanish"), ("Английский", "english")], value="spanish", label="Язык речи") | |
| speech_checkbox = gr.Checkbox(value=True, label="Проверить распознавание речи + все три модальности (если ошибка — перейти на видео+звук)") | |
| button = gr.Button("Проверить всё за один запуск", variant="primary") | |
| logs = gr.Textbox(label="Журнал этапов (или полная ошибка)", lines=20) | |
| chart = gr.Image(label="Прогнозируемый fMRI-сигнал", type="filepath") | |
| files = gr.File(label="JSON, NPZ или diagnostics.txt", file_count="multiple") | |
| button.click(run_full_pipeline, inputs=[video_input, language_input, speech_checkbox], outputs=[logs, chart, files], concurrency_limit=1) | |
| demo.queue().launch() | |