lazurit/streaming/consumer.py
2025-05-12 19:01:22 +07:00

119 lines
3.8 KiB
Python

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
video_frame_queue = asyncio.Queue(maxsize=3)
read_task = None
clients = set()
VIDEO_RTSP = "rtsp://192.168.1.247:554/rtsp/streaming?channel=1&subtype=A"
model = YOLO("models/colors/v1/best_color_50epochs.pt")
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 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 read_rtsp_stream():
global read_task
try:
container = av.open(
VIDEO_RTSP, '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}")