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 = 1200, 550, 300, 300 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", "veryfast", filename ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) await self.send(text_data="recording_started") # 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) 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) detected = False annotated_img = img.copy() # Можно заменить на 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] if class_name == "yellow": detected = True # Получаем координаты и корректируем с учётом crop x1, y1, x2, y2 = map(int, box.xyxy[0]) x1 += crop_x x2 += crop_x y1 += crop_y y2 += crop_y # Отображаем прямоугольник и подпись на изображении cv2.rectangle(annotated_img, (x1, y1), (x2, y2), (0, 255, 255), 2) cv2.putText( annotated_img, f"{class_name} {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() ) 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": "Yellow — разрешён" })) else: await self.send(text_data=json.dumps({ "status": "ok", "message": "Объектов не обнаружено" })) # Кодируем и отправляем кадр _, 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 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}")