import cv2 import base64 import asyncio import datetime import os import av import json import subprocess import time from django.conf import settings from ultralytics import YOLO from channels.generic.websocket import AsyncWebsocketConsumer import numpy as np from datetime import datetime from dotenv import load_dotenv load_dotenv() from .tasks import save_video_clip MODEL_PATH = os.getenv("MODEL_PATH") RTSP_URL = os.getenv("RTSP_URL") video_frame_queue = asyncio.Queue(maxsize=3) read_task = None clients = set() model = YOLO(MODEL_PATH) crop_x, crop_y, crop_w, crop_h = 1030, 650, 450, 500 RECORD_DURATION = 60 # 1 минута read_task_lock = asyncio.Lock() class VideoConsumer(AsyncWebsocketConsumer): async def connect(self): global read_task await self.accept() clients.add(self) async with read_task_lock: if read_task is None or read_task.done(): read_task = asyncio.create_task(read_rtsp_stream()) self.send_task = asyncio.create_task(self.send_frames()) async def disconnect(self, close_code): clients.discard(self) try: self.send_task.cancel() await self.send_task except Exception: pass async def receive(self, text_data): try: data = json.loads(text_data) mark_type = data.get("type") crop_x = data.get("cropX") crop_y = data.get("cropY") crop_w = data.get("cropW") crop_h = data.get("cropH") except Exception: return if mark_type in ["good", "bad"]: folder = f"../media/{mark_type}_clips" os.makedirs(folder, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = os.path.join(folder, f"{mark_type}_{timestamp}.mp4") # if self.recording_process: # self.recording_process.terminate() crop_filter = f"crop={crop_w}:{crop_h}:{crop_x}:{crop_y}" subprocess.Popen([ "ffmpeg", "-rtsp_transport", "tcp", "-i", RTSP_URL, "-t", str(RECORD_DURATION), "-an", "-vf", crop_filter, "-c:v", "libx264", "-preset", "slow", filename ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) await self.send(text_data="recording_started") # используется для classification # async def send_frames(self): # from .models import AllowedColor # while True: # try: # jpeg_data = await video_frame_queue.get() # img = cv2.imdecode(np.frombuffer(jpeg_data, dtype=np.uint8), cv2.IMREAD_COLOR) # # Обработка нейросетью # cropped = img[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w] # results = model.predict(source=cropped, save=False, verbose=False) # predicted_class = results[0].names[results[0].probs.top1] # allowed_color = await asyncio.to_thread( # lambda: AllowedColor.objects.filter(name=predicted_class).first() # ) # if allowed_color and not allowed_color.allowed: # await self.send(text_data=json.dumps({ # "status": "danger", # "message": f"Запрещённый цвет: {predicted_class}" # })) # else: # await self.send(text_data=json.dumps({ # "status": "ok", # "message": "Всё хорошо" # })) # confidence = results[0].probs.top1conf.item() # label = f"{predicted_class}: {confidence:.2f}" # cv2.putText(img, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # _, jpeg = cv2.imencode('.jpg', img) # frame_data = base64.b64encode(jpeg.tobytes()).decode('utf-8') # await self.send(text_data=frame_data) # await asyncio.sleep(0.1) # except asyncio.CancelledError: # break # except Exception as e: # print(f"[SEND_FRAME ERROR]: {e}") # await asyncio.sleep(0.04) # используется для detection async def send_frames(self): from .models import AllowedColor, DetectionHistory min_width = 30 min_height = 30 min_area = 900 while True: try: jpeg_data = await video_frame_queue.get() img = cv2.imdecode(np.frombuffer(jpeg_data, dtype=np.uint8), cv2.IMREAD_COLOR) # Кропим нужную зону для анализа cropped = img[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w] results = model.predict(source=cropped, save=False, verbose=False) detected = False annotated_img = img.copy() # annotated_img = cropped # для отображения рабочей области нейронки for box in results[0].boxes: cls_id = int(box.cls[0]) conf = float(box.conf[0]) class_name = results[0].names[cls_id] # Получаем координаты и корректируем с учётом crop x1, y1, x2, y2 = map(int, box.xyxy[0]) x1 += crop_x x2 += crop_x y1 += crop_y y2 += crop_y width = x2 - x1 height = y2 - y1 if width < min_width or height < min_height: detected = True if width * height < min_area: detected = True if class_name == "yellow": detected = True # Отображаем прямоугольник и подпись на изображении cv2.rectangle(annotated_img, (x1, y1), (x2, y2), (0, 255, 255), 2) cv2.putText( annotated_img, # f"{class_name} {conf:.2f}", f"spray {conf:.2f}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 255), 2 ) # Проверка в базе (если используешь) # if detected: # allowed_color = await asyncio.to_thread( # lambda: AllowedColor.objects.filter(name="yellow").first() # ) # status_key = 'bad' if allowed_color and not allowed_color.allowed else 'good' # # Сохраняем в историю # await asyncio.to_thread( # lambda: DetectionHistory.objects.create(status=status_key) # ) # # Посылаем статус на клиент # if status_key == 'bad': # await self.send(text_data=json.dumps({ # "status": "danger", # "message": "внимание" # })) # else: # await self.send(text_data=json.dumps({ # "status": "ok", # "message": "все хорошо" # })) # allowed_color = await asyncio.to_thread( # lambda: AllowedColor.objects.filter(name="yellow").first() # ) # if allowed_color and not allowed_color.allowed: # await self.send(text_data=json.dumps({ # "status": "danger", # "message": "внимание" # })) # else: # await self.send(text_data=json.dumps({ # "status": "ok", # "message": "все хорошо" # })) # else: # await self.send(text_data=json.dumps({ # "status": "ok", # "message": "Объектов не обнаружено" # })) if detected: # определяем статус allowed_color = await asyncio.to_thread( lambda: AllowedColor.objects.filter(name="yellow").first() ) status_key = 'bad' if allowed_color and not allowed_color.allowed else 'good' # сохраняем только 'bad' if status_key == 'bad': await asyncio.to_thread( lambda: DetectionHistory.objects.create(status=status_key) ) # if conf <= 30: # await asyncio.to_thread( # lambda # ) # отправляем статус клиенту await self.send(text_data=json.dumps({ "status": "danger" if status_key == 'bad' else "ok", "message": "внимание" if status_key == 'bad' else "все хорошо" })) # Кодируем и отправляем кадр _, jpeg = cv2.imencode('.jpg', annotated_img) frame_data = base64.b64encode(jpeg.tobytes()).decode('utf-8') await self.send(text_data=frame_data) await asyncio.sleep(0.1) except asyncio.CancelledError: break except Exception as e: print(f"[SEND_FRAME ERROR]: {e}") await asyncio.sleep(0.04) async def red_line(): return async def read_rtsp_stream(): global read_task try: container = av.open( RTSP_URL, 'r', options={ 'rtsp_transport': 'tcp', 'fflags': 'nobuffer', 'flags': 'low_delay', 'stimeout': '10000000', 'max_delay': '10000000', }) video_stream = next(s for s in container.streams if s.type == 'video') for packet in container.demux(video_stream): for frame in packet.decode(): img = frame.to_ndarray(format='bgr24') ret, jpeg = cv2.imencode('.jpg', img) if not ret: continue if video_frame_queue.full(): await video_frame_queue.get() await video_frame_queue.put(jpeg.tobytes()) await asyncio.sleep(0.03) except Exception as e: print(f"[RTSP ERROR] {e}")