Spaces:
Configuration error
Configuration error
Delete vision_analyzer_py.py
Browse files- vision_analyzer_py.py +0 -281
vision_analyzer_py.py
DELETED
|
@@ -1,281 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
core/vision_analyzer.py
|
| 3 |
-
=======================
|
| 4 |
-
Frame-level visual understanding.
|
| 5 |
-
|
| 6 |
-
Model strategy (RAM-aware cascade):
|
| 7 |
-
1. BLIP-2 (salesforce/blip2-opt-2.7b) — default, ~6GB RAM, good captions
|
| 8 |
-
2. Fallback: BLIP-base (salesforce/blip-image-captioning-base) — ~500MB RAM
|
| 9 |
-
3. LLaVA-7B (llava-hf/llava-1.5-7b-hf) — only if ≥ 14GB RAM free
|
| 10 |
-
|
| 11 |
-
We use BLIP-2 as the smart default:
|
| 12 |
-
- Rich scene descriptions
|
| 13 |
-
- Runs on CPU (slow but functional) or GPU (fast)
|
| 14 |
-
- No conversation overhead — just caption each frame efficiently
|
| 15 |
-
|
| 16 |
-
Frames are batched in groups of 4 to balance throughput and RAM.
|
| 17 |
-
Results stored in MemoryStore with visual metadata tags.
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
from __future__ import annotations
|
| 21 |
-
|
| 22 |
-
import gc
|
| 23 |
-
import os
|
| 24 |
-
import threading
|
| 25 |
-
from pathlib import Path
|
| 26 |
-
from typing import List, Optional, Callable, Dict
|
| 27 |
-
|
| 28 |
-
import psutil
|
| 29 |
-
import torch
|
| 30 |
-
from PIL import Image
|
| 31 |
-
from loguru import logger
|
| 32 |
-
from transformers import (
|
| 33 |
-
BlipProcessor,
|
| 34 |
-
BlipForConditionalGeneration,
|
| 35 |
-
Blip2Processor,
|
| 36 |
-
Blip2ForConditionalGeneration,
|
| 37 |
-
AutoProcessor,
|
| 38 |
-
LlavaForConditionalGeneration,
|
| 39 |
-
)
|
| 40 |
-
|
| 41 |
-
from core.memory import MemoryStore
|
| 42 |
-
from core.video_processor import FrameInfo
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# ── Model registry ─────────────────────────────────────────────────────────────
|
| 46 |
-
|
| 47 |
-
_vision_model = None
|
| 48 |
-
_vision_processor = None
|
| 49 |
-
_vision_lock = threading.Lock()
|
| 50 |
-
_loaded_model_name: Optional[str] = ""
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def _free_ram_gb() -> float:
|
| 54 |
-
return psutil.virtual_memory().available / 1e9
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def _pick_vision_model() -> str:
|
| 58 |
-
free = _free_ram_gb()
|
| 59 |
-
if free >= 12:
|
| 60 |
-
return "blip2"
|
| 61 |
-
return "blip_base"
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def _load_vision_model(model_name: str):
|
| 65 |
-
global _vision_model, _vision_processor, _loaded_model_name
|
| 66 |
-
cache = os.path.expanduser("~/.cache/cineai/vision")
|
| 67 |
-
|
| 68 |
-
if model_name == "blip2":
|
| 69 |
-
logger.info("Loading BLIP-2 (opt-2.7b) — requires ~6GB RAM…")
|
| 70 |
-
_vision_processor = Blip2Processor.from_pretrained(
|
| 71 |
-
"Salesforce/blip2-opt-2.7b", cache_dir=cache
|
| 72 |
-
)
|
| 73 |
-
_vision_model = Blip2ForConditionalGeneration.from_pretrained(
|
| 74 |
-
"Salesforce/blip2-opt-2.7b",
|
| 75 |
-
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 76 |
-
device_map="auto",
|
| 77 |
-
load_in_8bit=torch.cuda.is_available(), # 8-bit only on CUDA
|
| 78 |
-
cache_dir=cache,
|
| 79 |
-
)
|
| 80 |
-
|
| 81 |
-
elif model_name == "llava":
|
| 82 |
-
logger.info("Loading LLaVA-1.5-7b (4-bit quantized)…")
|
| 83 |
-
from transformers import BitsAndBytesConfig
|
| 84 |
-
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16)
|
| 85 |
-
_vision_processor = AutoProcessor.from_pretrained(
|
| 86 |
-
"llava-hf/llava-1.5-7b-hf", cache_dir=cache
|
| 87 |
-
)
|
| 88 |
-
_vision_model = LlavaForConditionalGeneration.from_pretrained(
|
| 89 |
-
"llava-hf/llava-1.5-7b-hf",
|
| 90 |
-
quantization_config=bnb,
|
| 91 |
-
device_map="auto",
|
| 92 |
-
cache_dir=cache,
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
else: # blip_base — tiny, always works
|
| 96 |
-
logger.info("Loading BLIP-base (captioning-base)…")
|
| 97 |
-
_vision_processor = BlipProcessor.from_pretrained(
|
| 98 |
-
"Salesforce/blip-image-captioning-base", cache_dir=cache
|
| 99 |
-
)
|
| 100 |
-
_vision_model = BlipForConditionalGeneration.from_pretrained(
|
| 101 |
-
"Salesforce/blip-image-captioning-base",
|
| 102 |
-
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 103 |
-
cache_dir=cache,
|
| 104 |
-
)
|
| 105 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 106 |
-
_vision_model = _vision_model.to(device)
|
| 107 |
-
|
| 108 |
-
_loaded_model_name = model_name
|
| 109 |
-
_vision_model.eval()
|
| 110 |
-
logger.info(f"Vision model '{model_name}' loaded ✓")
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def get_vision_model(preferred: Optional[str] = None):
|
| 114 |
-
global _vision_model, _vision_processor
|
| 115 |
-
with _vision_lock:
|
| 116 |
-
target = preferred or _pick_vision_model()
|
| 117 |
-
if _loaded_model_name != target:
|
| 118 |
-
_unload_vision()
|
| 119 |
-
_load_vision_model(target)
|
| 120 |
-
return _vision_model, _vision_processor, _loaded_model_name
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def _unload_vision():
|
| 124 |
-
global _vision_model, _vision_processor, _loaded_model_name
|
| 125 |
-
if _vision_model is not None:
|
| 126 |
-
del _vision_model
|
| 127 |
-
del _vision_processor
|
| 128 |
-
_vision_model = None
|
| 129 |
-
_vision_processor = None
|
| 130 |
-
_loaded_model_name = ""
|
| 131 |
-
gc.collect()
|
| 132 |
-
if torch.cuda.is_available():
|
| 133 |
-
torch.cuda.empty_cache()
|
| 134 |
-
logger.info("Vision model unloaded")
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
# ── Vision analyser ────────────────────────────────────────────────────────────
|
| 138 |
-
|
| 139 |
-
class VisionAnalyzer:
|
| 140 |
-
|
| 141 |
-
BATCH_SIZE = 4 # process 4 frames at a time
|
| 142 |
-
MAX_NEW_TOKENS = 80 # keep captions concise
|
| 143 |
-
|
| 144 |
-
def analyze_frames(
|
| 145 |
-
self,
|
| 146 |
-
frames: List[FrameInfo],
|
| 147 |
-
memory: Optional[MemoryStore] = None,
|
| 148 |
-
progress_cb: Optional[Callable[[str, float], None]] = None,
|
| 149 |
-
question: Optional[str] = None, # VQA mode
|
| 150 |
-
) -> List[Dict]:
|
| 151 |
-
"""
|
| 152 |
-
Generate a caption (or answer a question) for each frame.
|
| 153 |
-
Results are stored in MemoryStore with type='scene'.
|
| 154 |
-
Returns list of {timestamp_sec, caption, frame_path}.
|
| 155 |
-
"""
|
| 156 |
-
p = progress_cb or (lambda m, v: None)
|
| 157 |
-
if not frames:
|
| 158 |
-
return []
|
| 159 |
-
|
| 160 |
-
model, processor, model_name = get_vision_model()
|
| 161 |
-
device = next(model.parameters()).device
|
| 162 |
-
results = []
|
| 163 |
-
total = len(frames)
|
| 164 |
-
|
| 165 |
-
for batch_start in range(0, total, self.BATCH_SIZE):
|
| 166 |
-
batch = frames[batch_start: batch_start + self.BATCH_SIZE]
|
| 167 |
-
images = [Image.open(f.path).convert("RGB") for f in batch]
|
| 168 |
-
|
| 169 |
-
captions = self._batch_caption(
|
| 170 |
-
model, processor, model_name, images, device, question
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
for frame, cap in zip(batch, captions):
|
| 174 |
-
results.append({
|
| 175 |
-
"timestamp_sec": frame.timestamp_sec,
|
| 176 |
-
"caption": cap,
|
| 177 |
-
"frame_path": frame.path,
|
| 178 |
-
})
|
| 179 |
-
if memory:
|
| 180 |
-
memory.add(
|
| 181 |
-
content=cap,
|
| 182 |
-
timestamp_sec=frame.timestamp_sec,
|
| 183 |
-
memory_type="scene",
|
| 184 |
-
metadata={"frame_path": frame.path, "visual": True},
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
pct = 0.0 + (batch_start + len(batch)) / total
|
| 188 |
-
p(f"Analysing scenes… {batch_start + len(batch)}/{total}", pct)
|
| 189 |
-
|
| 190 |
-
return results
|
| 191 |
-
|
| 192 |
-
def _batch_caption(
|
| 193 |
-
self,
|
| 194 |
-
model,
|
| 195 |
-
processor,
|
| 196 |
-
model_name: str,
|
| 197 |
-
images: List[Image.Image],
|
| 198 |
-
device,
|
| 199 |
-
question: Optional[str],
|
| 200 |
-
) -> List[str]:
|
| 201 |
-
try:
|
| 202 |
-
if model_name == "blip2":
|
| 203 |
-
return self._blip2_caption(model, processor, images, device, question)
|
| 204 |
-
elif model_name == "llava":
|
| 205 |
-
return self._llava_caption(model, processor, images, device, question)
|
| 206 |
-
else:
|
| 207 |
-
return self._blip_base_caption(model, processor, images, device, question)
|
| 208 |
-
except Exception as e:
|
| 209 |
-
logger.warning(f"Vision batch failed: {e}")
|
| 210 |
-
return ["Scene analysis unavailable"] * len(images)
|
| 211 |
-
|
| 212 |
-
def _blip2_caption(self, model, processor, images, device, question):
|
| 213 |
-
prompt = question if question else "Describe what is happening in this scene in detail."
|
| 214 |
-
prompts = [prompt] * len(images)
|
| 215 |
-
inputs = processor(images=images, text=prompts, return_tensors="pt", padding=True).to(device)
|
| 216 |
-
with torch.no_grad():
|
| 217 |
-
ids = model.generate(
|
| 218 |
-
**inputs,
|
| 219 |
-
max_new_tokens=self.MAX_NEW_TOKENS,
|
| 220 |
-
do_sample=False,
|
| 221 |
-
)
|
| 222 |
-
return [
|
| 223 |
-
processor.decode(i, skip_special_tokens=True).strip()
|
| 224 |
-
for i in ids
|
| 225 |
-
]
|
| 226 |
-
|
| 227 |
-
def _blip_base_caption(self, model, processor, images, device, question):
|
| 228 |
-
results = []
|
| 229 |
-
for img in images:
|
| 230 |
-
if question:
|
| 231 |
-
inputs = processor(img, question, return_tensors="pt").to(device)
|
| 232 |
-
else:
|
| 233 |
-
inputs = processor(img, return_tensors="pt").to(device)
|
| 234 |
-
with torch.no_grad():
|
| 235 |
-
ids = model.generate(**inputs, max_new_tokens=self.MAX_NEW_TOKENS)
|
| 236 |
-
results.append(processor.decode(ids[0], skip_special_tokens=True).strip())
|
| 237 |
-
return results
|
| 238 |
-
|
| 239 |
-
def _llava_caption(self, model, processor, images, device, question):
|
| 240 |
-
prompt = question or "Describe this scene in detail."
|
| 241 |
-
results = []
|
| 242 |
-
for img in images:
|
| 243 |
-
conv = f"USER: <image>\n{prompt}\nASSISTANT:"
|
| 244 |
-
inputs = processor(text=conv, images=img, return_tensors="pt").to(device)
|
| 245 |
-
with torch.no_grad():
|
| 246 |
-
ids = model.generate(**inputs, max_new_tokens=self.MAX_NEW_TOKENS)
|
| 247 |
-
out = processor.decode(ids[0][2:], skip_special_tokens=True)
|
| 248 |
-
# Strip the prompt echo from LLaVA output
|
| 249 |
-
if "ASSISTANT:" in out:
|
| 250 |
-
out = out.split("ASSISTANT:")[-1].strip()
|
| 251 |
-
results.append(out)
|
| 252 |
-
return results
|
| 253 |
-
|
| 254 |
-
# ── Smart frame selector for a query ──────────────────────────────────────
|
| 255 |
-
def analyze_query_frames(
|
| 256 |
-
self,
|
| 257 |
-
frames: List[FrameInfo],
|
| 258 |
-
query: str,
|
| 259 |
-
memory: Optional[MemoryStore],
|
| 260 |
-
top_k_frames: int = 5,
|
| 261 |
-
) -> str:
|
| 262 |
-
"""
|
| 263 |
-
For a user question, find the most relevant frames via memory search
|
| 264 |
-
(skips re-running vision on all frames — much cheaper).
|
| 265 |
-
Falls back to recent frames if no memory hits.
|
| 266 |
-
"""
|
| 267 |
-
context_chunks = []
|
| 268 |
-
if memory:
|
| 269 |
-
hits = memory.search(query, top_k=top_k_frames, memory_type="scene")
|
| 270 |
-
context_chunks = [h.content for h in hits]
|
| 271 |
-
|
| 272 |
-
if not context_chunks and frames:
|
| 273 |
-
# Use the middle N frames as fallback
|
| 274 |
-
mid = len(frames) // 2
|
| 275 |
-
subset = frames[max(0, mid - 2): mid + 3]
|
| 276 |
-
model, processor, name = get_vision_model()
|
| 277 |
-
device = next(model.parameters()).device
|
| 278 |
-
images = [Image.open(f.path).convert("RGB") for f in subset]
|
| 279 |
-
context_chunks = self._batch_caption(model, processor, name, images, device, query)
|
| 280 |
-
|
| 281 |
-
return "\n".join(context_chunks) if context_chunks else "No visual context found."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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