Spaces:
Sleeping
Sleeping
Download detector.py from Magnus1510/ServSecurityHost: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/spaces/Magnus1510/ServSecurityHost/resolve/main/detector.py
- Command line
-
hf download hf://spaces/Magnus1510/ServSecurityHost/detector.py
-
curl -L -o detector.py https://huggingface.co/spaces/Magnus1510/ServSecurityHost/resolve/main/detector.py
15 kB
| import cv2 | |
| import numpy as np | |
| import os | |
| import sys | |
| from pathlib import Path | |
| from typing import Optional | |
| from datetime import datetime | |
| import warnings | |
| # Suprimir advertencia de PyTorch 2.5 sobre torch.load() para mantener la terminal limpia | |
| warnings.filterwarnings("ignore", category=FutureWarning, module="torch") | |
| # ImportaciΓ³n lazy para no fallar si ultralytics no estΓ‘ instalado en tiempo de import | |
| try: | |
| from ultralytics import YOLO | |
| YOLO_AVAILABLE = True | |
| except ImportError: | |
| YOLO_AVAILABLE = False | |
| # Clase ΓΊnica para detectar: persona (class_id = 0 en COCO) | |
| PERSON_CLASS_ID = 0 | |
| # Colores BGR | |
| COLOR_BOX_NORMAL = (0, 255, 0) # verde | |
| COLOR_BOX_ALERT = (0, 0, 255) # rojo | |
| COLOR_ZONE_NORMAL = (0, 165, 255) # naranja | |
| COLOR_ZONE_ALERT = (0, 0, 255) # rojo | |
| COLOR_TEXT = (255, 255, 255) # blanco | |
| COLOR_TEXT_SHADOW = (0, 0, 0) # negro | |
| # Conexiones del esqueleto (COCO format) β constante a nivel de mΓ³dulo | |
| SKELETON_CONNECTIONS = ( | |
| (15, 13), (13, 11), (16, 14), (14, 12), (11, 12), | |
| (5, 11), (6, 12), (5, 6), (5, 7), (6, 8), (7, 9), | |
| (8, 10), (1, 2), (0, 1), (0, 2), (1, 3), (2, 4), | |
| (3, 5), (4, 6), | |
| ) | |
| # DetecciΓ³n de entorno | |
| _IS_CLOUD = sys.platform.startswith("linux") | |
| class PersonDetector: | |
| """ | |
| Encapsula el modelo YOLOv8 y la lΓ³gica de detecciΓ³n de personas. | |
| """ | |
| def __init__(self, model_name: str = "yolov8n-pose.pt", confidence: float = 0.75): | |
| """ | |
| Args: | |
| model_name: Nombre del modelo YOLOv8 a cargar. | |
| confidence: Umbral mΓnimo de confianza para aceptar una detecciΓ³n. | |
| """ | |
| if not YOLO_AVAILABLE: | |
| raise ImportError( | |
| "ultralytics no estΓ‘ instalado. Ejecuta: pip install ultralytics" | |
| ) | |
| self.confidence = confidence | |
| self.model = YOLO(model_name) | |
| # ResoluciΓ³n de inferencia adaptativa: | |
| # - Nube (CPU): 320px β duplica velocidad, YOLO mapea coordenadas de vuelta al original | |
| # - Local (GPU): 640px β mΓ‘xima precisiΓ³n | |
| self._pose_imgsz = 320 if _IS_CLOUD else 640 | |
| # Precalentamiento del modelo | |
| dummy = np.zeros((480, 640, 3), dtype=np.uint8) | |
| self.model(dummy, verbose=False, imgsz=self._pose_imgsz) | |
| # Cargar modelo de anomalΓas si existe (El "Cerebro 2") | |
| self.anomaly_model = None | |
| self._anomaly_imgsz = 224 # Entrenado a 224px β respetar resoluciΓ³n de entrenamiento | |
| # Frame-skip del modelo de anomalΓas: | |
| # No es necesario clasificar cada frame. Correr cada N frames ahorra | |
| # 50-150ms por frame en CPU sin perder calidad de detecciΓ³n. | |
| self._anomaly_run_every = 6 if _IS_CLOUD else 3 | |
| self._anomaly_frame_count = 0 | |
| self._last_anomaly_info = None # Cache del ΓΊltimo resultado | |
| anomaly_path = "runs/classify/servsecurity_anomaly_model/weights/best.pt" | |
| if os.path.exists(anomaly_path): | |
| self.anomaly_model = YOLO(anomaly_path) | |
| self.anomaly_model(dummy, verbose=False, imgsz=self._anomaly_imgsz) # Precalentamiento | |
| print("β Modelo de AnomalΓas cargado con Γ©xito.") | |
| def detect(self, frame: np.ndarray) -> tuple[list[dict], Optional[dict]]: | |
| # 1. MOTOR 1: DetecciΓ³n de Personas (Pose) | |
| results = self.model( | |
| frame, verbose=False, conf=self.confidence, | |
| classes=[PERSON_CLASS_ID], imgsz=self._pose_imgsz, | |
| ) | |
| detections = [] | |
| for result in results: | |
| boxes = result.boxes | |
| keypoints = result.keypoints | |
| if boxes is None: | |
| continue | |
| for i, box in enumerate(boxes): | |
| x1, y1, x2, y2 = map(int, box.xyxy[0].tolist()) | |
| conf = float(box.conf[0]) | |
| cx = (x1 + x2) // 2 | |
| cy = (y1 + y2) // 2 | |
| # Extraer keypoints si el modelo lo soporta (yolov8-pose) | |
| kpts = None | |
| if keypoints is not None and len(keypoints) > i: | |
| # kpts: (17, 3) donde [2] es la confianza del keypoint | |
| # Usamos .data[0] para obtener el tensor de la persona actual | |
| kpt_data = keypoints.data[i].cpu().numpy() | |
| kpts = kpt_data.tolist() | |
| # Filtro anti-alucinaciones (motos, macetas, objetos complejos): | |
| # Una moto puede engaΓ±ar a la IA y generar keypoints con ~0.5 de confianza. | |
| # Exigimos al menos 5 puntos anatΓ³micos con una certeza MUY alta (> 0.70). | |
| valid_kpts = sum(1 for kp in kpts if len(kp) >= 3 and kp[2] > 0.70) | |
| if valid_kpts < 5: | |
| continue # Descartar esta detecciΓ³n, es muy probable que sea un objeto | |
| # --- LΓ³gica de Recorte de Cabeza (Head Crop) para mejor reconocimiento --- | |
| head_crop = None | |
| if kpts is not None and len(kpts) >= 5: | |
| # Extraer keypoints faciales (0: nariz, 1: ojo izq, 2: ojo der, 3: oreja izq, 4: oreja der) | |
| face_kpts = [kp for kp in kpts[:5] if len(kp) >= 3 and kp[2] > 0.4] | |
| if len(face_kpts) >= 2: | |
| fx_min = int(min(kp[0] for kp in face_kpts)) | |
| fy_min = int(min(kp[1] for kp in face_kpts)) | |
| fx_max = int(max(kp[0] for kp in face_kpts)) | |
| fy_max = int(max(kp[1] for kp in face_kpts)) | |
| # AΓ±adir margen alrededor de la cara | |
| w = max(fx_max - fx_min, 10) | |
| h = max(fy_max - fy_min, 10) | |
| pad_x = int(w * 1.5) | |
| pad_y = int(h * 1.5) | |
| hx1 = max(0, fx_min - pad_x) | |
| hy1 = max(0, fy_min - pad_y * 1.5) | |
| hx2 = min(frame.shape[1], fx_max + pad_x) | |
| hy2 = min(frame.shape[0], fy_max + pad_y) | |
| head_crop = frame[int(hy1):int(hy2), int(hx1):int(hx2)].copy() | |
| # Fallback: Si no hay keypoints faciales fiables, tomar el 30% superior del cuerpo | |
| if head_crop is None or head_crop.size == 0: | |
| head_h = int((y2 - y1) * 0.3) | |
| head_crop = frame[y1:y1+head_h, x1:x2].copy() | |
| detections.append({ | |
| "bbox": (x1, y1, x2, y2), | |
| "confidence": conf, | |
| "center": (cx, cy), | |
| "keypoints": kpts, | |
| "crop": head_crop | |
| }) | |
| # 2. MOTOR 2: ClasificaciΓ³n de AnomalΓas (frame-skipping adaptativo) | |
| # Solo se ejecuta cada N frames para ahorrar CPU, reutilizando el | |
| # ΓΊltimo resultado conocido en los frames intermedios. | |
| self._anomaly_frame_count += 1 | |
| run_anomaly = ( | |
| self.anomaly_model is not None | |
| and len(detections) > 0 | |
| and self._anomaly_frame_count % self._anomaly_run_every == 0 | |
| ) | |
| if run_anomaly: | |
| cls_results = self.anomaly_model( | |
| frame, verbose=False, imgsz=self._anomaly_imgsz, | |
| ) | |
| anomaly_info = None | |
| if cls_results and len(cls_results) > 0: | |
| probs = cls_results[0].probs | |
| if probs is not None: | |
| top_class_idx = probs.top1 | |
| top_conf = float(probs.top1conf) | |
| top_class_name = cls_results[0].names[top_class_idx] | |
| if top_class_name.lower() != "normal" and top_conf > 0.70: | |
| anomaly_info = { | |
| "class": top_class_name.upper(), | |
| "conf": top_conf, | |
| } | |
| self._last_anomaly_info = anomaly_info | |
| else: | |
| # Reutilizar el ΓΊltimo resultado conocido | |
| anomaly_info = self._last_anomaly_info | |
| # Si ya no hay personas en el frame, limpiar el cache de anomalΓa | |
| if len(detections) == 0: | |
| self._last_anomaly_info = None | |
| anomaly_info = None | |
| return detections, anomaly_info | |
| def draw_detections( | |
| frame: np.ndarray, | |
| detections: list[dict], | |
| alerts: list[bool], | |
| zone: Optional[tuple] = None, | |
| zone_active: bool = True, | |
| draw_skeleton: bool = True, | |
| anomaly_info: Optional[dict] = None | |
| ) -> np.ndarray: | |
| """ | |
| Dibuja las bounding boxes, estado de alerta, zona restringida y anomalΓas globales. | |
| Args: | |
| frame: Imagen BGR original. | |
| detections: Lista de detecciones del detector. | |
| alerts: Lista booleana paralela a detections (True = alerta activa). | |
| zone: Tupla (x1, y1, x2, y2) de la zona restringida. | |
| zone_active: Si True, muestra la zona restringida. | |
| draw_skeleton: Si True, dibuja el esqueleto de la persona. | |
| anomaly_info: Diccionario con info de la anomalΓa global detectada, o None. | |
| Returns: | |
| Frame anotado. | |
| """ | |
| output = frame.copy() | |
| h, w = output.shape[:2] | |
| # ββ Zona restringida ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if zone_active and zone is not None: | |
| zx1, zy1, zx2, zy2 = zone | |
| any_alert = any(alerts) if alerts else False | |
| zone_color = COLOR_ZONE_ALERT if any_alert else COLOR_ZONE_NORMAL | |
| # Overlay semitransparente β solo sobre la sub-regiΓ³n de la zona (ROI) | |
| # En vez de copiar todo el frame, operamos solo sobre la zona restringida | |
| roi = output[zy1:zy2, zx1:zx2] | |
| overlay_roi = roi.copy() | |
| overlay_roi[:] = zone_color | |
| cv2.addWeighted(overlay_roi, 0.15, roi, 0.85, 0, roi) | |
| cv2.rectangle(output, (zx1, zy1), (zx2, zy2), zone_color, 2) | |
| # Etiqueta de zona | |
| label = "ZONA RESTRINGIDA" | |
| (lw, lh), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2) | |
| cv2.rectangle(output, (zx1, zy1 - lh - 8), (zx1 + lw + 8, zy1), zone_color, -1) | |
| cv2.putText(output, label, (zx1 + 4, zy1 - 4), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, COLOR_TEXT, 2) | |
| # ββ Bounding boxes de personas ββββββββββββββββββββββββββββββββββββββββββββ | |
| for i, det in enumerate(detections): | |
| x1, y1, x2, y2 = det["bbox"] | |
| conf = det["confidence"] | |
| is_alert = alerts[i] if i < len(alerts) else False | |
| box_color = COLOR_BOX_ALERT if is_alert else COLOR_BOX_NORMAL | |
| auth_status = det.get("is_authorized") | |
| if auth_status is True: | |
| auth_text = " [AUTORIZADO]" | |
| box_color = (255, 165, 0) # Celeste/Verde claro si esta autorizado | |
| elif auth_status is False: | |
| auth_text = " [DESCONOCIDO]" | |
| box_color = COLOR_BOX_ALERT # Rojo si es desconocido | |
| else: | |
| auth_text = " [Analizando...]" | |
| status_text = "[!] ALERTA" if is_alert else "Persona" | |
| label = f"{status_text}{auth_text} {conf:.0%}" | |
| # Caja | |
| cv2.rectangle(output, (x1, y1), (x2, y2), box_color, 2) | |
| # Etiqueta con fondo | |
| (lw, lh), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 2) | |
| cv2.rectangle(output, (x1, y1 - lh - 8), (x1 + lw + 6, y1), box_color, -1) | |
| cv2.putText(output, label, (x1 + 3, y1 - 4), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.55, COLOR_TEXT, 2) | |
| # ββ Dibujar Esqueleto (Keypoints) βββββββββββββββββββββββββββββββββββββ | |
| kpts = det.get("keypoints") | |
| if kpts is not None and draw_skeleton: | |
| # Dibujar uniones (huesos) β usa constante de mΓ³dulo | |
| for j1, j2 in SKELETON_CONNECTIONS: | |
| if j1 < len(kpts) and j2 < len(kpts): | |
| p1 = kpts[j1] | |
| p2 = kpts[j2] | |
| # Validar si tienen confianza > 0.5 (si la confianza existe en kpts[i][2]) | |
| if (len(p1) > 2 and p1[2] < 0.5) or (len(p2) > 2 and p2[2] < 0.5): | |
| continue | |
| if p1[0] == 0 or p2[0] == 0: # Keypoints no detectados | |
| continue | |
| pt1 = (int(p1[0]), int(p1[1])) | |
| pt2 = (int(p2[0]), int(p2[1])) | |
| # Dibujar linea semitransparente | |
| cv2.line(output, pt1, pt2, box_color, 2) | |
| # Dibujar puntos (articulaciones) | |
| for p in kpts: | |
| if p[0] != 0 and p[1] != 0: | |
| if len(p) > 2 and p[2] < 0.5: | |
| continue | |
| cv2.circle(output, (int(p[0]), int(p[1])), 3, (0, 255, 255), -1) | |
| # Punto central | |
| cx, cy = det["center"] | |
| cv2.circle(output, (cx, cy), 5, box_color, -1) | |
| # ββ Timestamp en esquina ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| cv2.putText(output, ts, (10, h - 10), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TEXT_SHADOW, 3) | |
| cv2.putText(output, ts, (10, h - 10), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TEXT, 1) | |
| # ββ Marca de agua βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| cv2.putText(output, "SERVSecurity v1.0", (10, 22), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.55, (180, 220, 255), 1) | |
| # ββ Alerta Global de AnomalΓa βββββββββββββββββββββββββββββββββββββββββββββ | |
| if anomaly_info is not None: | |
| anomaly_text = f"Β‘ALERTA CRITICA: {anomaly_info['class']} DETECTADO! ({anomaly_info['conf']:.0%})" | |
| (tw, th), _ = cv2.getTextSize(anomaly_text, cv2.FONT_HERSHEY_DUPLEX, 0.8, 2) | |
| tx = (w - tw) // 2 | |
| ty = 50 | |
| # Fondo rojo sangriento con borde negro | |
| cv2.rectangle(output, (tx - 20, ty - th - 15), (tx + tw + 20, ty + 15), (0, 0, 255), -1) | |
| cv2.rectangle(output, (tx - 20, ty - th - 15), (tx + tw + 20, ty + 15), (0, 0, 0), 2) | |
| # Texto blanco con sombra | |
| cv2.putText(output, anomaly_text, (tx+2, ty+2), cv2.FONT_HERSHEY_DUPLEX, 0.8, (0, 0, 0), 2) | |
| cv2.putText(output, anomaly_text, (tx, ty), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255, 255, 255), 2) | |
| return output | |