diff --git a/streaming/__pycache__/consumer.cpython-311.pyc b/streaming/__pycache__/consumer.cpython-311.pyc index 684bb2e..2a3b857 100644 Binary files a/streaming/__pycache__/consumer.cpython-311.pyc and b/streaming/__pycache__/consumer.cpython-311.pyc differ diff --git a/streaming/consumer.py b/streaming/consumer.py index 5f17488..182fcde 100644 --- a/streaming/consumer.py +++ b/streaming/consumer.py @@ -26,157 +26,86 @@ 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): + global read_task 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()) + 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: - # 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") + self.send_task.cancel() + await self.send_task except Exception: - return + pass - 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 + jpeg_data = await video_frame_queue.get() + img = cv2.imdecode(np.frombuffer(jpeg_data, dtype=np.uint8), cv2.IMREAD_COLOR) - if (time.time() - start_time) - (frame.time - start_read) > 0.3: - continue + # Обработка нейросетью + 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] - 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) + allowed_color = await asyncio.to_thread( + lambda: AllowedColor.objects.filter(name=predicted_class).first() + ) - 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) + 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": "Всё хорошо" + })) - _, 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) + 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("frame error: ", e) - await asyncio.sleep(1) - continue + 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') - while clients: - try: - container = av.open(settings.RTSP_URL) - video_stream = container.streams.video[0] - - for frame in container.decode(video_stream): + for packet in container.demux(video_stream): + for frame in packet.decode(): img = frame.to_ndarray(format='bgr24') - - # Сжимаем в JPEG ret, jpeg = cv2.imencode('.jpg', img) if not ret: continue @@ -185,7 +114,6 @@ async def read_rtsp_stream(): 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}") \ No newline at end of file + await asyncio.sleep(0.03) + except Exception as e: + print(f"[RTSP ERROR] {e}") \ No newline at end of file diff --git a/streaming/templates/streaming/stream.html b/streaming/templates/streaming/stream.html index 5161c27..9fab271 100644 --- a/streaming/templates/streaming/stream.html +++ b/streaming/templates/streaming/stream.html @@ -35,6 +35,9 @@
+
+ Всё хорошо +