liquid/streaming/consumer.py
2025-05-12 18:10:11 +07:00

191 lines
6.9 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 connect(self):
await self.accept()
self.container = av.open(
VIDEO_RTSP, 'r',
options={
'rtsp_transport': 'tcp',
'fflags': 'nobuffer',
'flags': 'low_delay',
'stimeout': '100000',
'max_delay': '100000',
}
)
self.video_stream = next(s for s in self.container.streams if s.type == 'video')
self.recording_process = None
asyncio.create_task(self.send_frames())
async def disconnect(self, close_code):
clients.discard(self)
# try:
# if self.send_task:
# self.send_task.cancel()
# await self.send_task
# except asyncio.CancelledError:
# 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.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}"
self.recording_process = subprocess.Popen([
"ffmpeg",
"-rtsp_transport", "tcp",
"-i", VIDEO_RTSP,
"-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):
# while True:
# try:
# jpeg_data = await video_frame_queue.get()
# frame = cv2.imdecode(np.frombuffer(jpeg_data, dtype=np.uint8), cv2.IMREAD_COLOR)
# # Обработка кадра
# cropped = frame[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]
# confidence = results[0].probs.top1conf.item()
# label = f"{predicted_class}: {confidence:.2f}"
# cv2.putText(frame, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# _, jpeg = cv2.imencode('.jpg', frame)
# frame_data = base64.b64encode(jpeg.tobytes()).decode('utf-8')
# await self.send(text_data=frame_data)
# await asyncio.sleep(0.04) # 25 fps
# except Exception as e:
# print("frame error:", e)
# await asyncio.sleep(1)
async def send_frames(self):
from .models import AllowedColor
start_time = None
start_read = None
while True:
try:
for packet in self.container.demux(self.video_stream):
for frame in packet.decode():
if start_time is None:
start_time = time.time()
start_read = frame.time
if (time.time() - start_time) - (frame.time - start_read) > 0.3:
continue
img = frame.to_ndarray(format='bgr24')
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:
print(f"⚠️ Обнаружен запрещённый цвет: {predicted_class}")
# await self.send(text_data=json.dumps({"alert": f"Запрещённый цвет: {predicted_class}"}))
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.04)
except Exception as e:
print("frame error: ", e)
await asyncio.sleep(1)
continue
async def read_rtsp_stream():
while clients:
try:
container = av.open(settings.RTSP_URL)
video_stream = container.streams.video[0]
for frame in container.decode(video_stream):
img = frame.to_ndarray(format='bgr24')
# Сжимаем в JPEG
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) # ~30 fps
except Exception as e:
print(f"[ERROR] RTSP reader: {e}")