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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TRIBE v2 research-only, one-click multimodal smoke test for HF ZeroGPU."""
|
| 2 |
+
import functools
|
| 3 |
+
import io
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
import time
|
| 11 |
+
import traceback
|
| 12 |
+
import urllib.request
|
| 13 |
+
import zipfile
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
# WhisperX is executed in an isolated uvx subprocess. Do not leak hf_transfer setting.
|
| 17 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0"
|
| 18 |
+
os.environ.setdefault("HF_HOME", "/tmp/hf-home")
|
| 19 |
+
|
| 20 |
+
import gradio as gr
|
| 21 |
+
import numpy as np
|
| 22 |
+
import spaces
|
| 23 |
+
import torch
|
| 24 |
+
from huggingface_hub import hf_hub_download
|
| 25 |
+
|
| 26 |
+
REPO_DIR = Path("/tmp/tribev2-main")
|
| 27 |
+
CACHE_DIR = Path("/tmp/tribev2-cache")
|
| 28 |
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def ensure_official_code():
|
| 32 |
+
if not (REPO_DIR / "tribev2" / "__init__.py").is_file():
|
| 33 |
+
url = "https://github.com/facebookresearch/tribev2/archive/refs/heads/main.zip"
|
| 34 |
+
with urllib.request.urlopen(url, timeout=90) as response:
|
| 35 |
+
archive = response.read()
|
| 36 |
+
with zipfile.ZipFile(io.BytesIO(archive)) as z:
|
| 37 |
+
z.extractall("/tmp")
|
| 38 |
+
if str(REPO_DIR) not in sys.path:
|
| 39 |
+
sys.path.insert(0, str(REPO_DIR))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def check_video(video):
|
| 43 |
+
if not video or not Path(video).is_file():
|
| 44 |
+
raise ValueError("Сначала загрузите MP4")
|
| 45 |
+
if Path(video).suffix.lower() not in {".mp4", ".mov", ".webm", ".mkv", ".avi"}:
|
| 46 |
+
raise ValueError("Нужен MP4/MOV/WEBM/MKV/AVI")
|
| 47 |
+
cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", str(video)]
|
| 48 |
+
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
|
| 49 |
+
if proc.returncode:
|
| 50 |
+
raise RuntimeError(f"ffprobe error: {proc.stderr[-2000:]}")
|
| 51 |
+
duration = float(proc.stdout.strip())
|
| 52 |
+
if duration < 1 or duration > 20:
|
| 53 |
+
raise ValueError(f"Видео {duration:.1f} сек. Для первого теста загрузите клип от 1 до 20 сек.")
|
| 54 |
+
return duration
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@spaces.GPU(duration=240)
|
| 58 |
+
def run_full_pipeline(video, language, include_speech, progress=gr.Progress()):
|
| 59 |
+
logs = []
|
| 60 |
+
output_dir = Path(tempfile.mkdtemp(prefix="tribe_test_"))
|
| 61 |
+
t0 = time.monotonic()
|
| 62 |
+
stage = "START"
|
| 63 |
+
checkpoint = {}
|
| 64 |
+
def log(msg):
|
| 65 |
+
logs.append(f"[{time.monotonic()-t0:6.1f}s] {msg}")
|
| 66 |
+
print(logs[-1], flush=True)
|
| 67 |
+
|
| 68 |
+
def update(position, text):
|
| 69 |
+
progress(position, desc=text)
|
| 70 |
+
log(text)
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
stage = "PREFLIGHT"
|
| 74 |
+
update(0.03, "Проверяю инструменты, доступ и входной файл")
|
| 75 |
+
for tool in ["ffmpeg", "ffprobe", "uvx"]:
|
| 76 |
+
if not shutil.which(tool):
|
| 77 |
+
raise RuntimeError(f"Не найден {tool}. Проверьте packages.txt (ffmpeg) и requirements.txt (uv).")
|
| 78 |
+
duration = check_video(video)
|
| 79 |
+
log(f"Видео: {duration:.1f} сек | {Path(video).stat().st_size/1024**2:.2f} МБ")
|
| 80 |
+
log(f"GPU: {torch.cuda.get_device_name(0)} | PyTorch: {torch.__version__}")
|
| 81 |
+
token = os.environ.get("HF_TOKEN")
|
| 82 |
+
log(f"HF_TOKEN: {'задан' if token else 'не задан'}")
|
| 83 |
+
if include_speech:
|
| 84 |
+
try:
|
| 85 |
+
hf_hub_download("meta-llama/Llama-3.2-3B", "config.json", token=token or None)
|
| 86 |
+
log("Доступ к Llama 3.2-3B: OK")
|
| 87 |
+
except Exception as ex:
|
| 88 |
+
log(f"Доступ к Llama 3.2-3B не подтверждён: {type(ex).__name__}: {str(ex)[:350]}")
|
| 89 |
+
# Continue: some paths can process audio/video without text features.
|
| 90 |
+
|
| 91 |
+
stage = "IMPORT"
|
| 92 |
+
update(0.12, "Подключаю официальный код Meta")
|
| 93 |
+
ensure_official_code()
|
| 94 |
+
from tribev2 import TribeModel
|
| 95 |
+
from tribev2 import demo_utils as du
|
| 96 |
+
from tribev2.demo_utils import get_audio_and_text_events
|
| 97 |
+
import pandas as pd
|
| 98 |
+
|
| 99 |
+
stage = "MODEL"
|
| 100 |
+
update(0.20, "Загружаю TRIBE v2 на GPU")
|
| 101 |
+
model = TribeModel.from_pretrained(
|
| 102 |
+
"facebook/tribev2", cache_folder=str(CACHE_DIR), device="cuda"
|
| 103 |
+
)
|
| 104 |
+
log(f"Нейросеть: {sum(p.numel() for p in model._model.parameters()):,} параметров")
|
| 105 |
+
log(f"VRAM: {torch.cuda.memory_allocated()/1024**3:.2f} ГБ")
|
| 106 |
+
|
| 107 |
+
stage = "EVENTS"
|
| 108 |
+
update(0.35, "Извлекаю события из видео и аудиодорожки")
|
| 109 |
+
used_mode = "video_audio_no_transcript"
|
| 110 |
+
if include_speech:
|
| 111 |
+
old_constructor = du.ExtractWordsFromAudio
|
| 112 |
+
try:
|
| 113 |
+
# Meta defaults to English; force Spanish for Spanish-language Reels.
|
| 114 |
+
du.ExtractWordsFromAudio = functools.partial(old_constructor, language=language)
|
| 115 |
+
events = model.get_events_dataframe(video_path=str(video))
|
| 116 |
+
used_mode = "video_audio_text"
|
| 117 |
+
log(f"Полный режим: OK, язык распознавания {language}")
|
| 118 |
+
except Exception as ex:
|
| 119 |
+
log(f"Полный режим не прошёл: {type(ex).__name__}: {str(ex)[-900:]}")
|
| 120 |
+
if time.monotonic() - t0 > 175:
|
| 121 |
+
raise RuntimeError("Не осталось времени на запасной режим. Смотрите журнал выше.") from ex
|
| 122 |
+
log("Пробую официальный режим без транскрипции (video + audio).")
|
| 123 |
+
raw = pd.DataFrame([{
|
| 124 |
+
"type": "Video", "filepath": str(video), "start": 0,
|
| 125 |
+
"timeline": "default", "subject": "default"
|
| 126 |
+
}])
|
| 127 |
+
events = get_audio_and_text_events(raw, audio_only=True)
|
| 128 |
+
finally:
|
| 129 |
+
du.ExtractWordsFromAudio = old_constructor
|
| 130 |
+
else:
|
| 131 |
+
raw = pd.DataFrame([{
|
| 132 |
+
"type": "Video", "filepath": str(video), "start": 0,
|
| 133 |
+
"timeline": "default", "subject": "default"
|
| 134 |
+
}])
|
| 135 |
+
events = get_audio_and_text_events(raw, audio_only=True)
|
| 136 |
+
counts = events["type"].value_counts().to_dict()
|
| 137 |
+
log(f"События: {counts}")
|
| 138 |
+
|
| 139 |
+
stage = "PREDICT"
|
| 140 |
+
update(0.58, "Загружаю мультимодальные энкодеры и считаю fMRI-прогноз")
|
| 141 |
+
predictions, segments = model.predict(events=events, verbose=False)
|
| 142 |
+
predictions = np.asarray(predictions, dtype=np.float32)
|
| 143 |
+
if predictions.ndim != 2 or not predictions.shape[0]:
|
| 144 |
+
raise RuntimeError(f"Некорректная форма предсказаний: {predictions.shape}")
|
| 145 |
+
log(f"PREDICTION SUCCESS: shape={predictions.shape}, segments={len(segments)}")
|
| 146 |
+
|
| 147 |
+
stage = "REPORT"
|
| 148 |
+
update(0.87, "Строю график и сохраняю результаты")
|
| 149 |
+
# Purely descriptive aggregation; NOT attention, emotion or conversion.
|
| 150 |
+
activity = np.nanmean(np.abs(predictions), axis=1)
|
| 151 |
+
tr_seconds = float(model.data.TR)
|
| 152 |
+
times = np.arange(predictions.shape[0]) * tr_seconds
|
| 153 |
+
npz_file = output_dir / "brain_predictions.npz"
|
| 154 |
+
json_file = output_dir / "summary.json"
|
| 155 |
+
chart_file = output_dir / "brain_timeline.png"
|
| 156 |
+
np.savez_compressed(npz_file, predictions=predictions, time_seconds=times)
|
| 157 |
+
checkpoint = {
|
| 158 |
+
"status": "success", "mode": used_mode, "language": language,
|
| 159 |
+
"input_duration_seconds": duration,
|
| 160 |
+
"prediction_shape": list(predictions.shape),
|
| 161 |
+
"n_segments": len(segments), "TR_seconds": tr_seconds,
|
| 162 |
+
"mean_absolute_predicted_signal": activity.tolist(),
|
| 163 |
+
"time_seconds": times.tolist(),
|
| 164 |
+
"important": "Предсказанная нейронная fMRI-активность среднего субъекта, НЕ внимание/эмоции/конверсия. Около 5 сек поправки на гемодинамический лаг по документации Meta.",
|
| 165 |
+
"warnings": [line for line in logs if "не прош" in line or "не подтвержд" in line],
|
| 166 |
+
}
|
| 167 |
+
json_file.write_text(json.dumps(checkpoint, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 168 |
+
import matplotlib
|
| 169 |
+
matplotlib.use("Agg")
|
| 170 |
+
import matplotlib.pyplot as plt
|
| 171 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
| 172 |
+
ax.plot(times, activity)
|
| 173 |
+
ax.set_xlabel("Время предсказанного сигнала, сек (с учётом особенностей fMRI)")
|
| 174 |
+
ax.set_ylabel("Средний |fMRI-прогноз| по вершинам")
|
| 175 |
+
ax.set_title("TRIBE v2: прогнозированная fMRI-активность (не метрика внимания)")
|
| 176 |
+
fig.tight_layout()
|
| 177 |
+
fig.savefig(chart_file, dpi=130)
|
| 178 |
+
plt.close(fig)
|
| 179 |
+
update(1, "Готово")
|
| 180 |
+
return "\n".join(logs), str(chart_file), [str(json_file), str(npz_file)]
|
| 181 |
+
except Exception:
|
| 182 |
+
error_text = traceback.format_exc()
|
| 183 |
+
log(f"ОШИБКА на этапе {stage}:\n{error_text}")
|
| 184 |
+
diagnostic = output_dir / "diagnostics.txt"
|
| 185 |
+
diagnostic.write_text("\n".join(logs), encoding="utf-8")
|
| 186 |
+
return "\n".join(logs), None, [str(diagnostic)]
|
| 187 |
+
finally:
|
| 188 |
+
if torch.cuda.is_available():
|
| 189 |
+
try:
|
| 190 |
+
torch.cuda.empty_cache()
|
| 191 |
+
except Exception:
|
| 192 |
+
pass
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
with gr.Blocks(title="TRIBE v2 — All-in-one Research Test") as demo:
|
| 196 |
+
gr.Markdown("# TRIBE v2 — полная проверка видео\nИсследовательский тест модели Meta на HF ZeroGPU. НЕ коммерческий скоринг Reels.")
|
| 197 |
+
with gr.Row():
|
| 198 |
+
video_input = gr.Video(label="MP4 5–10 секунд для первого теста", format="mp4")
|
| 199 |
+
with gr.Column():
|
| 200 |
+
language_input = gr.Dropdown(choices=[("Испанский", "spanish"), ("Английский", "english")], value="spanish", label="Язык речи")
|
| 201 |
+
speech_checkbox = gr.Checkbox(value=True, label="Проверить распознавание речи + все три модальности (если ошибка — перейти на видео+звук)")
|
| 202 |
+
button = gr.Button("Проверить всё за один запуск", variant="primary")
|
| 203 |
+
logs = gr.Textbox(label="Журнал этапов (или полная ошибка)", lines=20)
|
| 204 |
+
chart = gr.Image(label="Прогнозируемый fMRI-сигнал", type="filepath")
|
| 205 |
+
files = gr.File(label="JSON, NPZ или diagnostics.txt", file_count="multiple")
|
| 206 |
+
button.click(run_full_pipeline, inputs=[video_input, language_input, speech_checkbox], outputs=[logs, chart, files], concurrency_limit=1)
|
| 207 |
+
|
| 208 |
+
demo.queue().launch()
|
packages.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
requirements.txt
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
neuralset==0.0.2
|
| 2 |
+
neuraltrain==0.0.2
|
| 3 |
+
exca==0.5.20
|
| 4 |
+
numpy==2.2.6
|
| 5 |
+
x-transformers==1.27.20
|
| 6 |
+
einops
|
| 7 |
+
pyyaml
|
| 8 |
+
moviepy>=2.2.1
|
| 9 |
+
huggingface_hub
|
| 10 |
+
gtts
|
| 11 |
+
langdetect
|
| 12 |
+
spacy
|
| 13 |
+
soundfile
|
| 14 |
+
Levenshtein
|
| 15 |
+
julius
|
| 16 |
+
transformers
|
| 17 |
+
pandas
|
| 18 |
+
pydantic
|
| 19 |
+
requests
|
| 20 |
+
tqdm
|
| 21 |
+
uv
|
| 22 |
+
matplotlib
|
| 23 |
+
accelerate
|
| 24 |
+
sentencepiece
|
| 25 |
+
safetensors
|
| 26 |
+
timm
|
| 27 |
+
opencv-python-headless
|