|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +YOLO Detection Skill — Real-time object detection for SharpAI Aegis. |
| 4 | +
|
| 5 | +Communicates via JSON lines over stdin/stdout: |
| 6 | + stdin: {"event": "frame", "camera_id": "...", "frame_path": "...", ...} |
| 7 | + stdout: {"event": "detections", "camera_id": "...", "objects": [...]} |
| 8 | +
|
| 9 | +Usage: |
| 10 | + python detect.py --config config.json |
| 11 | + python detect.py --model yolov11n --confidence 0.5 --device auto |
| 12 | +""" |
| 13 | + |
| 14 | +import sys |
| 15 | +import json |
| 16 | +import argparse |
| 17 | +import signal |
| 18 | +from pathlib import Path |
| 19 | + |
| 20 | +def parse_args(): |
| 21 | + parser = argparse.ArgumentParser(description="YOLO Detection Skill") |
| 22 | + parser.add_argument("--config", type=str, help="Path to config JSON file") |
| 23 | + parser.add_argument("--model", type=str, default="yolov11n", |
| 24 | + choices=["yolov11n", "yolov11s", "yolov11m", "yolov10n", "yolov10s", "yolov8n"]) |
| 25 | + parser.add_argument("--confidence", type=float, default=0.5) |
| 26 | + parser.add_argument("--classes", type=str, default="person,car,dog,cat") |
| 27 | + parser.add_argument("--device", type=str, default="auto", choices=["auto", "cpu", "cuda", "mps"]) |
| 28 | + parser.add_argument("--fps", type=int, default=5) |
| 29 | + return parser.parse_args() |
| 30 | + |
| 31 | + |
| 32 | +def load_config(args): |
| 33 | + """Load config from JSON file or CLI args.""" |
| 34 | + if args.config: |
| 35 | + config_path = Path(args.config) |
| 36 | + if config_path.exists(): |
| 37 | + with open(config_path) as f: |
| 38 | + return json.load(f) |
| 39 | + return { |
| 40 | + "model": args.model, |
| 41 | + "confidence": args.confidence, |
| 42 | + "classes": args.classes.split(","), |
| 43 | + "device": args.device, |
| 44 | + "fps": args.fps, |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | +def select_device(preference: str) -> str: |
| 49 | + """Select the best available inference device.""" |
| 50 | + if preference != "auto": |
| 51 | + return preference |
| 52 | + try: |
| 53 | + import torch |
| 54 | + if torch.cuda.is_available(): |
| 55 | + return "cuda" |
| 56 | + if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): |
| 57 | + return "mps" |
| 58 | + except ImportError: |
| 59 | + pass |
| 60 | + return "cpu" |
| 61 | + |
| 62 | + |
| 63 | +def emit(event: dict): |
| 64 | + """Write a JSON line to stdout.""" |
| 65 | + print(json.dumps(event), flush=True) |
| 66 | + |
| 67 | + |
| 68 | +def main(): |
| 69 | + args = parse_args() |
| 70 | + config = load_config(args) |
| 71 | + |
| 72 | + # Select device |
| 73 | + device = select_device(config.get("device", "auto")) |
| 74 | + model_name = config.get("model", "yolov11n") |
| 75 | + confidence = config.get("confidence", 0.5) |
| 76 | + target_classes = config.get("classes", ["person", "car", "dog", "cat"]) |
| 77 | + |
| 78 | + # Load YOLO model |
| 79 | + try: |
| 80 | + from ultralytics import YOLO |
| 81 | + model = YOLO(f"{model_name}.pt") |
| 82 | + model.to(device) |
| 83 | + emit({ |
| 84 | + "event": "ready", |
| 85 | + "model": model_name, |
| 86 | + "device": device, |
| 87 | + "classes": len(model.names), |
| 88 | + }) |
| 89 | + except Exception as e: |
| 90 | + emit({"event": "error", "message": f"Failed to load model: {e}", "retriable": False}) |
| 91 | + sys.exit(1) |
| 92 | + |
| 93 | + # Graceful shutdown |
| 94 | + running = True |
| 95 | + def handle_signal(signum, frame): |
| 96 | + nonlocal running |
| 97 | + running = False |
| 98 | + signal.signal(signal.SIGTERM, handle_signal) |
| 99 | + signal.signal(signal.SIGINT, handle_signal) |
| 100 | + |
| 101 | + # Main loop: read frames from stdin, output detections to stdout |
| 102 | + for line in sys.stdin: |
| 103 | + if not running: |
| 104 | + break |
| 105 | + |
| 106 | + line = line.strip() |
| 107 | + if not line: |
| 108 | + continue |
| 109 | + |
| 110 | + try: |
| 111 | + msg = json.loads(line) |
| 112 | + except json.JSONDecodeError: |
| 113 | + continue |
| 114 | + |
| 115 | + if msg.get("command") == "stop": |
| 116 | + break |
| 117 | + |
| 118 | + if msg.get("event") == "frame": |
| 119 | + frame_path = msg.get("frame_path") |
| 120 | + camera_id = msg.get("camera_id", "unknown") |
| 121 | + timestamp = msg.get("timestamp", "") |
| 122 | + |
| 123 | + if not frame_path or not Path(frame_path).exists(): |
| 124 | + emit({"event": "error", "message": f"Frame not found: {frame_path}", "retriable": True}) |
| 125 | + continue |
| 126 | + |
| 127 | + # Run inference |
| 128 | + try: |
| 129 | + results = model(frame_path, conf=confidence, verbose=False) |
| 130 | + objects = [] |
| 131 | + for r in results: |
| 132 | + for box in r.boxes: |
| 133 | + cls_id = int(box.cls[0]) |
| 134 | + cls_name = model.names[cls_id] |
| 135 | + if cls_name in target_classes or not target_classes: |
| 136 | + x1, y1, x2, y2 = box.xyxy[0].tolist() |
| 137 | + objects.append({ |
| 138 | + "class": cls_name, |
| 139 | + "confidence": round(float(box.conf[0]), 3), |
| 140 | + "bbox": [int(x1), int(y1), int(x2), int(y2)], |
| 141 | + }) |
| 142 | + |
| 143 | + emit({ |
| 144 | + "event": "detections", |
| 145 | + "camera_id": camera_id, |
| 146 | + "timestamp": timestamp, |
| 147 | + "objects": objects, |
| 148 | + }) |
| 149 | + except Exception as e: |
| 150 | + emit({"event": "error", "message": f"Inference error: {e}", "retriable": True}) |
| 151 | + |
| 152 | + |
| 153 | +if __name__ == "__main__": |
| 154 | + main() |
0 commit comments