|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +VLM Scene Analysis Skill — Offline clip understanding via vision language models. |
| 4 | +
|
| 5 | +Analyzes recorded video clips and generates natural language descriptions. |
| 6 | +""" |
| 7 | + |
| 8 | +import sys |
| 9 | +import json |
| 10 | +import argparse |
| 11 | +import signal |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | + |
| 15 | +def parse_args(): |
| 16 | + parser = argparse.ArgumentParser(description="VLM Scene Analysis Skill") |
| 17 | + parser.add_argument("--config", type=str) |
| 18 | + parser.add_argument("--model", type=str, default="smolvlm2-500m") |
| 19 | + parser.add_argument("--prompt", type=str, |
| 20 | + default="Describe what is happening in this security camera footage. Focus on people, vehicles, and any unusual activity.") |
| 21 | + parser.add_argument("--max-frames", type=int, default=4) |
| 22 | + parser.add_argument("--device", type=str, default="auto") |
| 23 | + return parser.parse_args() |
| 24 | + |
| 25 | + |
| 26 | +def load_config(args): |
| 27 | + if args.config and Path(args.config).exists(): |
| 28 | + with open(args.config) as f: |
| 29 | + return json.load(f) |
| 30 | + return { |
| 31 | + "model": args.model, |
| 32 | + "prompt": args.prompt, |
| 33 | + "max_frames": args.max_frames, |
| 34 | + "device": args.device, |
| 35 | + } |
| 36 | + |
| 37 | + |
| 38 | +def emit(event): |
| 39 | + print(json.dumps(event), flush=True) |
| 40 | + |
| 41 | + |
| 42 | +def extract_frames(video_path, max_frames=4): |
| 43 | + """Extract evenly spaced frames from a video clip.""" |
| 44 | + import cv2 |
| 45 | + cap = cv2.VideoCapture(video_path) |
| 46 | + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
| 47 | + if total <= 0: |
| 48 | + cap.release() |
| 49 | + return [] |
| 50 | + |
| 51 | + indices = [int(i * total / max_frames) for i in range(max_frames)] |
| 52 | + frames = [] |
| 53 | + for idx in indices: |
| 54 | + cap.set(cv2.CAP_PROP_POS_FRAMES, idx) |
| 55 | + ret, frame = cap.read() |
| 56 | + if ret: |
| 57 | + frames.append(frame) |
| 58 | + cap.release() |
| 59 | + return frames |
| 60 | + |
| 61 | + |
| 62 | +def main(): |
| 63 | + args = parse_args() |
| 64 | + config = load_config(args) |
| 65 | + |
| 66 | + try: |
| 67 | + from llama_cpp import Llama |
| 68 | + from llama_cpp.llama_chat_format import MiniCPMv26ChatHandler |
| 69 | + import cv2 |
| 70 | + import base64 |
| 71 | + |
| 72 | + model_path = Path(f"models/{config['model']}.gguf") |
| 73 | + if not model_path.exists(): |
| 74 | + emit({"event": "error", "message": f"Model not found: {model_path}. Run: python scripts/download_model.py --model {config['model']}", "retriable": False}) |
| 75 | + sys.exit(1) |
| 76 | + |
| 77 | + chat_handler = MiniCPMv26ChatHandler(clip_model_path=str(model_path.with_suffix(".mmproj"))) |
| 78 | + llm = Llama(model_path=str(model_path), chat_handler=chat_handler, n_ctx=4096) |
| 79 | + |
| 80 | + emit({"event": "ready", "model": config["model"], "device": config.get("device", "cpu")}) |
| 81 | + except Exception as e: |
| 82 | + emit({"event": "error", "message": f"Failed to load model: {e}", "retriable": False}) |
| 83 | + sys.exit(1) |
| 84 | + |
| 85 | + running = True |
| 86 | + def handle_signal(s, f): |
| 87 | + nonlocal running |
| 88 | + running = False |
| 89 | + signal.signal(signal.SIGTERM, handle_signal) |
| 90 | + signal.signal(signal.SIGINT, handle_signal) |
| 91 | + |
| 92 | + for line in sys.stdin: |
| 93 | + if not running: |
| 94 | + break |
| 95 | + line = line.strip() |
| 96 | + if not line: |
| 97 | + continue |
| 98 | + try: |
| 99 | + msg = json.loads(line) |
| 100 | + except json.JSONDecodeError: |
| 101 | + continue |
| 102 | + |
| 103 | + if msg.get("command") == "stop": |
| 104 | + break |
| 105 | + |
| 106 | + if msg.get("event") == "clip_ready": |
| 107 | + video_path = msg.get("video_path") |
| 108 | + clip_id = msg.get("clip_id", "unknown") |
| 109 | + camera_id = msg.get("camera_id", "unknown") |
| 110 | + |
| 111 | + if not video_path or not Path(video_path).exists(): |
| 112 | + emit({"event": "error", "message": f"Video not found: {video_path}", "retriable": True}) |
| 113 | + continue |
| 114 | + |
| 115 | + try: |
| 116 | + frames = extract_frames(video_path, config.get("max_frames", 4)) |
| 117 | + if not frames: |
| 118 | + emit({"event": "error", "message": "No frames extracted", "retriable": True}) |
| 119 | + continue |
| 120 | + |
| 121 | + # Encode frames as base64 for VLM |
| 122 | + images = [] |
| 123 | + for frame in frames: |
| 124 | + _, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 85]) |
| 125 | + images.append(f"data:image/jpeg;base64,{base64.b64encode(buf).decode()}") |
| 126 | + |
| 127 | + content = [{"type": "text", "text": config["prompt"]}] |
| 128 | + for img in images: |
| 129 | + content.append({"type": "image_url", "image_url": {"url": img}}) |
| 130 | + |
| 131 | + result = llm.create_chat_completion(messages=[ |
| 132 | + {"role": "user", "content": content} |
| 133 | + ]) |
| 134 | + |
| 135 | + description = result["choices"][0]["message"]["content"] |
| 136 | + emit({ |
| 137 | + "event": "analysis_result", |
| 138 | + "clip_id": clip_id, |
| 139 | + "camera_id": camera_id, |
| 140 | + "description": description, |
| 141 | + "objects": [], # Could be extracted from description |
| 142 | + "confidence": 0.9, |
| 143 | + }) |
| 144 | + except Exception as e: |
| 145 | + emit({"event": "error", "message": f"Analysis error: {e}", "retriable": True}) |
| 146 | + |
| 147 | + |
| 148 | +if __name__ == "__main__": |
| 149 | + main() |
0 commit comments