Spaces:
Configuration error
Configuration error
Delete vision_analyzer_py.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281"""core/vision_analyzer.py=======================Frame-level visual understanding.
Model strategy (RAM-aware cascade): 1. BLIP-2 (salesforce/blip2-opt-2.7b) β default, ~6GB RAM, good captions 2. Fallback: BLIP-base (salesforce/blip-image-captioning-base) β ~500MB RAM 3. LLaVA-7B (llava-hf/llava-1.5-7b-hf) β only if β₯ 14GB RAM free
We use BLIP-2 as the smart default: - Rich scene descriptions - Runs on CPU (slow but functional) or GPU (fast) - No conversation overhead β just caption each frame efficiently
Frames are batched in groups of 4 to balance throughput and RAM.Results stored in MemoryStore with visual metadata tags."""
from __future__ import annotations
import gcimport osimport threadingfrom pathlib import Pathfrom typing import List, Optional, Callable, Dict
import psutilimport torchfrom PIL import Imagefrom loguru import loggerfrom transformers import ( BlipProcessor, BlipForConditionalGeneration, Blip2Processor, Blip2ForConditionalGeneration, AutoProcessor, LlavaForConditionalGeneration,)
from core.memory import MemoryStorefrom core.video_processor import FrameInfo
# ββ Model registry βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_vision_model = None_vision_processor = None_vision_lock = threading.Lock()_loaded_model_name: Optional[str] = ""
def _free_ram_gb() -> float: return psutil.virtual_memory().available / 1e9
def _pick_vision_model() -> str: free = _free_ram_gb() if free >= 12: return "blip2" return "blip_base"
def _load_vision_model(model_name: str): global _vision_model, _vision_processor, _loaded_model_name cache = os.path.expanduser("~/.cache/cineai/vision")
if model_name == "blip2": logger.info("Loading BLIP-2 (opt-2.7b) β requires ~6GB RAMβ¦") _vision_processor = Blip2Processor.from_pretrained( "Salesforce/blip2-opt-2.7b", cache_dir=cache ) _vision_model = Blip2ForConditionalGeneration.from_pretrained( "Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto", load_in_8bit=torch.cuda.is_available(), # 8-bit only on CUDA cache_dir=cache, )
elif model_name == "llava": logger.info("Loading LLaVA-1.5-7b (4-bit quantized)β¦") from transformers import BitsAndBytesConfig bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16) _vision_processor = AutoProcessor.from_pretrained( "llava-hf/llava-1.5-7b-hf", cache_dir=cache ) _vision_model = LlavaForConditionalGeneration.from_pretrained( "llava-hf/llava-1.5-7b-hf", quantization_config=bnb, device_map="auto", cache_dir=cache, )
else: # blip_base β tiny, always works logger.info("Loading BLIP-base (captioning-base)β¦") _vision_processor = BlipProcessor.from_pretrained( "Salesforce/blip-image-captioning-base", cache_dir=cache ) _vision_model = BlipForConditionalGeneration.from_pretrained( "Salesforce/blip-image-captioning-base", torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, cache_dir=cache, ) device = "cuda" if torch.cuda.is_available() else "cpu" _vision_model = _vision_model.to(device)
_loaded_model_name = model_name _vision_model.eval() logger.info(f"Vision model '{model_name}' loaded β")
def get_vision_model(preferred: Optional[str] = None): global _vision_model, _vision_processor with _vision_lock: target = preferred or _pick_vision_model() if _loaded_model_name != target: _unload_vision() _load_vision_model(target) return _vision_model, _vision_processor, _loaded_model_name
def _unload_vision(): global _vision_model, _vision_processor, _loaded_model_name if _vision_model is not None: del _vision_model del _vision_processor _vision_model = None _vision_processor = None _loaded_model_name = "" gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() logger.info("Vision model unloaded")
# ββ Vision analyser ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class VisionAnalyzer:
BATCH_SIZE = 4 # process 4 frames at a time MAX_NEW_TOKENS = 80 # keep captions concise
def analyze_frames( self, frames: List[FrameInfo], memory: Optional[MemoryStore] = None, progress_cb: Optional[Callable[[str, float], None]] = None, question: Optional[str] = None, # VQA mode ) -> List[Dict]: """ Generate a caption (or answer a question) for each frame. Results are stored in MemoryStore with type='scene'. Returns list of {timestamp_sec, caption, frame_path}. """ p = progress_cb or (lambda m, v: None) if not frames: return []
model, processor, model_name = get_vision_model() device = next(model.parameters()).device results = [] total = len(frames)
for batch_start in range(0, total, self.BATCH_SIZE): batch = frames[batch_start: batch_start + self.BATCH_SIZE] images = [Image.open(f.path).convert("RGB") for f in batch]
captions = self._batch_caption( model, processor, model_name, images, device, question )
for frame, cap in zip(batch, captions): results.append({ "timestamp_sec": frame.timestamp_sec, "caption": cap, "frame_path": frame.path, }) if memory: memory.add( content=cap, timestamp_sec=frame.timestamp_sec, memory_type="scene", metadata={"frame_path": frame.path, "visual": True}, )
pct = 0.0 + (batch_start + len(batch)) / total p(f"Analysing scenes⦠{batch_start + len(batch)}/{total}", pct)
return results
def _batch_caption( self, model, processor, model_name: str, images: List[Image.Image], device, question: Optional[str], ) -> List[str]: try: if model_name == "blip2": return self._blip2_caption(model, processor, images, device, question) elif model_name == "llava": return self._llava_caption(model, processor, images, device, question) else: return self._blip_base_caption(model, processor, images, device, question) except Exception as e: logger.warning(f"Vision batch failed: {e}") return ["Scene analysis unavailable"] * len(images)
def _blip2_caption(self, model, processor, images, device, question): prompt = question if question else "Describe what is happening in this scene in detail." prompts = [prompt] * len(images) inputs = processor(images=images, text=prompts, return_tensors="pt", padding=True).to(device) with torch.no_grad(): ids = model.generate( **inputs, max_new_tokens=self.MAX_NEW_TOKENS, do_sample=False, ) return [ processor.decode(i, skip_special_tokens=True).strip() for i in ids ]
def _blip_base_caption(self, model, processor, images, device, question): results = [] for img in images: if question: inputs = processor(img, question, return_tensors="pt").to(device) else: inputs = processor(img, return_tensors="pt").to(device) with torch.no_grad(): ids = model.generate(**inputs, max_new_tokens=self.MAX_NEW_TOKENS) results.append(processor.decode(ids[0], skip_special_tokens=True).strip()) return results
def _llava_caption(self, model, processor, images, device, question): prompt = question or "Describe this scene in detail." results = [] for img in images: conv = f"USER: <image>\n{prompt}\nASSISTANT:" inputs = processor(text=conv, images=img, return_tensors="pt").to(device) with torch.no_grad(): ids = model.generate(**inputs, max_new_tokens=self.MAX_NEW_TOKENS) out = processor.decode(ids[0][2:], skip_special_tokens=True) # Strip the prompt echo from LLaVA output if "ASSISTANT:" in out: out = out.split("ASSISTANT:")[-1].strip() results.append(out) return results
# ββ Smart frame selector for a query ββββββββββββββββββββββββββββββββββββββ def analyze_query_frames( self, frames: List[FrameInfo], query: str, memory: Optional[MemoryStore], top_k_frames: int = 5, ) -> str: """ For a user question, find the most relevant frames via memory search (skips re-running vision on all frames β much cheaper). Falls back to recent frames if no memory hits. """ context_chunks = [] if memory: hits = memory.search(query, top_k=top_k_frames, memory_type="scene") context_chunks = [h.content for h in hits]
if not context_chunks and frames: # Use the middle N frames as fallback mid = len(frames) // 2 subset = frames[max(0, mid - 2): mid + 3] model, processor, name = get_vision_model() device = next(model.parameters()).device images = [Image.open(f.path).convert("RGB") for f in subset] context_chunks = self._batch_caption(model, processor, name, images, device, query)
return "\n".join(context_chunks) if context_chunks else "No visual context found."vision_analyzer_py.pyDeleted-281