diff --git a/.env-example b/.env-example deleted file mode 100644 index 12af610..0000000 --- a/.env-example +++ /dev/null @@ -1,4 +0,0 @@ -SECRET_KEY='django-insecure-dwz6w*m*yl$!))@7v36)u=034$1=41gp9ph5u7!g3x!b0un#)e' -WEBSOCKET_URL='ws://192.168.0.169:8106/ws/stream' -RTSP_URL='rtsp://192.168.1.247:554/rtsp/streaming?channel=1&subtype=A' -MODEL_PATH='models/colors/v2/best_only_yellow_20_ep.pt' \ No newline at end of file diff --git a/docker-compose-dev.yaml b/docker-compose-dev.yaml index 9161254..b088543 100644 --- a/docker-compose-dev.yaml +++ b/docker-compose-dev.yaml @@ -7,53 +7,15 @@ services: daphne -b 0.0.0.0 -p 8000 app.asgi:application" volumes: - .:/app - - ./media:/app/media + - ./web/media:/app/media - ./web/staticfiles:/app/web/staticfiles - # - ./media:/app/media + ports: - "8000:8000" - # expose: - # - 8000 - depends_on: - redis # - vpn - - # network_mode: "service:vpn" - - - - - # vpn: - # image: ubergarm/l2tp-ipsec-vpn-client - # container_name: vpn - # privileged: true - # cap_add: - # - NET_ADMIN - # environment: - # VPN_SERVER_IP: "176.196.239.122" - # VPN_IPSEC_PSK: "ad71Vyad" - # VPN_USER: "cybercode" - # VPN_PASSWORD: "wPvyUHd8" - # restart: alwaysq - - # nginx: - # build: ./nginx/dev - # # image: nginx:latest - # ports: - # - "80:80" - # volumes: - - # - ./static:/home/app/static - # # - ./nginx/nginx.conf:/etc/nginx/nginx.conf - # # - ./nginx/nginx.conf:/etc/nginx/conf.d/nginx.conf - # depends_on: - # - web - - # restart: always - - redis: image: redis:alpine container_name: liquid-redis-2 diff --git a/docker-compose.yaml b/docker-compose.yaml index d4d90d2..ba21666 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -7,32 +7,17 @@ services: daphne -b 0.0.0.0 -p 8106 app.asgi:application" volumes: - .:/app - - ./media:/app/media + - ./web/media:/app/media - ./web/staticfiles:/app/web/staticfiles - # - ./media:/app/media + ports: - "8106:8106" - #expose: - # - "8106" + depends_on: - redis - # - vpn - # network_mode: "service:vpn" + restart: always - # vpn: - # image: ubergarm/l2tp-ipsec-vpn-client - # container_name: vpn - # privileged: true - # cap_add: - # - NET_ADMIN - # environment: - # VPN_SERVER_IP: "176.196.239.122" - # VPN_IPSEC_PSK: "ad71Vyad" - # VPN_USER: "cybercode" - # VPN_PASSWORD: "wPvyUHd8" - # restart: always - # nginx: # build: ./nginx/dev # # image: nginx:latest @@ -46,7 +31,6 @@ services: # restart: always - redis: image: redis:alpine volumes: @@ -61,4 +45,4 @@ services: restart: always volumes: - redis_data: + redis_data: \ No newline at end of file diff --git a/example.env b/example.env new file mode 100644 index 0000000..5822296 --- /dev/null +++ b/example.env @@ -0,0 +1,4 @@ +SECRET_KEY='django-insecure-dwz6w*m*yl$!))@7v36)u=034$1=41gp9ph5u7!g3x!b0un#)e' +WEBSOCKET_URL='ws://192.168.0.169:8106/ws/stream' +RTSP_URL='rtsp://192.168.1.247:554/rtsp/streaming?channel=01&subtype=A' +MODEL_PATH='models/colors/detection/v4/med/epochs_60/best.pt' \ No newline at end of file diff --git a/web/app/settings.py b/web/app/settings.py index bc2c595..e398f7e 100644 --- a/web/app/settings.py +++ b/web/app/settings.py @@ -129,7 +129,7 @@ USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.2/howto/static-files/ -STATIC_URL = 'staticfiles' +STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Default primary key field type diff --git a/web/dataset/__init__.py b/web/dataset/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/web/dataset/admin.py b/web/dataset/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/web/dataset/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/web/dataset/apps.py b/web/dataset/apps.py new file mode 100644 index 0000000..166bedb --- /dev/null +++ b/web/dataset/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class DatasetConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'dataset' diff --git a/web/dataset/migrations/__init__.py b/web/dataset/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/web/dataset/models.py b/web/dataset/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/web/dataset/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/web/dataset/tests.py b/web/dataset/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/web/dataset/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/web/dataset/views.py b/web/dataset/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/web/dataset/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/web/db.sqlite3 b/web/db.sqlite3 index e8de426..6866720 100644 Binary files a/web/db.sqlite3 and b/web/db.sqlite3 differ diff --git a/web/models/colors/v1/best_color_50epochs.pt b/web/models/colors/classification/v1/best_color_50epochs.pt similarity index 100% rename from web/models/colors/v1/best_color_50epochs.pt rename to web/models/colors/classification/v1/best_color_50epochs.pt diff --git a/web/models/colors/v1/last_color_50_epochs.pt b/web/models/colors/classification/v1/last_color_50_epochs.pt similarity index 100% rename from web/models/colors/v1/last_color_50_epochs.pt rename to web/models/colors/classification/v1/last_color_50_epochs.pt diff --git a/web/models/colors/v2/best_only_yellow_20_ep.pt b/web/models/colors/classification/v2/best_only_yellow_20_ep.pt similarity index 100% rename from web/models/colors/v2/best_only_yellow_20_ep.pt rename to web/models/colors/classification/v2/best_only_yellow_20_ep.pt diff --git a/web/models/colors/v2/last_only_yellow_20_ep.pt b/web/models/colors/classification/v2/last_only_yellow_20_ep.pt similarity index 100% rename from web/models/colors/v2/last_only_yellow_20_ep.pt rename to web/models/colors/classification/v2/last_only_yellow_20_ep.pt diff --git a/web/models/colors/detection/v3/best.pt b/web/models/colors/detection/v3/best.pt new file mode 100644 index 0000000..36e7dcd Binary files /dev/null and b/web/models/colors/detection/v3/best.pt differ diff --git a/web/models/colors/detection/v3/last.pt b/web/models/colors/detection/v3/last.pt new file mode 100644 index 0000000..a1b64ee Binary files /dev/null and b/web/models/colors/detection/v3/last.pt differ diff --git a/web/models/colors/detection/v4/med/epochs_50/best_spray.pt b/web/models/colors/detection/v4/med/epochs_50/best_spray.pt new file mode 100644 index 0000000..8cc9dba Binary files /dev/null and b/web/models/colors/detection/v4/med/epochs_50/best_spray.pt differ diff --git a/web/models/colors/detection/v4/med/epochs_50/last_spray.pt b/web/models/colors/detection/v4/med/epochs_50/last_spray.pt new file mode 100644 index 0000000..a8a7d6e Binary files /dev/null and b/web/models/colors/detection/v4/med/epochs_50/last_spray.pt differ diff --git a/web/models/colors/detection/v4/med/epochs_60/best.pt b/web/models/colors/detection/v4/med/epochs_60/best.pt new file mode 100644 index 0000000..8f91569 Binary files /dev/null and b/web/models/colors/detection/v4/med/epochs_60/best.pt differ diff --git a/web/models/colors/detection/v4/med/epochs_60/last.pt b/web/models/colors/detection/v4/med/epochs_60/last.pt new file mode 100644 index 0000000..3ff07a2 Binary files /dev/null and b/web/models/colors/detection/v4/med/epochs_60/last.pt differ diff --git a/web/models/colors/detection/v4/med/epochs_60/model.py b/web/models/colors/detection/v4/med/epochs_60/model.py new file mode 100644 index 0000000..b34379b --- /dev/null +++ b/web/models/colors/detection/v4/med/epochs_60/model.py @@ -0,0 +1,97 @@ +import cv2 as cv +from ultralytics import YOLO +import numpy + + +video = 'C:/projects/liquid_test/videos/2025-05-29 15-39-48.mkv' + +cap = cv.VideoCapture(video) +model = YOLO('../models/det/med/v1/epochs_60/best.pt') +crop_x, crop_y, crop_w, crop_h = (870, 530, 210, 120) +model.to("cuda") + +while cap.isOpened(): + success, frame = cap.read() + if not success: + break # Конец видео + + # Обработка кадра + + results = model(frame, verbose=False) + + cropped = frame[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w] + results = model.predict(source=cropped, save=False, verbose=False) # device='cuda' + annotated_img = frame.copy() + + 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 + + + # Проверяем, есть ли результат + cv.rectangle(annotated_img, (x1, y1), (x2, y2), (0, 0, 255), 2) + cv.putText( + annotated_img, + # f"{class_name} {conf:.2f}", + f"spray {conf:.2f}", + (x1, y1 - 10), + cv.FONT_HERSHEY_SIMPLEX, + 0.9, + (0, 0, 255), + 2 + ) # Без изменений, если ничего не найдено + + # Отображение + cv.imshow("YOLO Detection", annotated_img) + if cv.waitKey(1) & 0xFF == ord("q"): + break + +cap.release() +cv.destroyAllWindows() + +# while cap.isOpened(): +# ret, frame = cap.read() +# if not ret: +# break + +# cropped = frame[y1:y1 + y2, x1:x1 + x2] +# # Детекция (результат — список) +# results = model(frame)[0] + +# img_with_boxes = results[0].plot() # numpy array +# cv.imshow("Detection", img_with_boxes) +# cv.waitKey(0) +# cv.destroyAllWindows() + +# # Обработка результатов вручную +# # for box in results.boxes: +# # cls_id = int(box.cls[0]) # индекс класса +# # conf = float(box.conf[0]) # уверенность +# # label = model.names[cls_id] + +# # # Координаты бокса +# # x1, y1, x2, y2 = map(int, box.xyxy[0]) # (x1, y1) — левый верхний, (x2, y2) — правый нижний + +# # # Рисуем прямоугольник +# # cv.rectangle(frame, (x1, y1), (x2, y2), color=(0, 255, 0), thickness=2) + +# # # Подпись +# # text = f"{label} {conf:.2f}" +# # cv.putText(frame, text, (x1, y1 - 10), cv.FONT_HERSHEY_SIMPLEX, +# # 0.5, (0, 255, 0), 2) + +# # Показ результата +# cv.imshow("YOLO Detection", frame) +# if cv.waitKey(1) & 0xFF == ord('q'): +# cap.release() +# cv.destroyAllWindows() +# break + diff --git a/web/models/colors/detection/v4/nano/epochs_50/best_spray.pt b/web/models/colors/detection/v4/nano/epochs_50/best_spray.pt new file mode 100644 index 0000000..43573d2 Binary files /dev/null and b/web/models/colors/detection/v4/nano/epochs_50/best_spray.pt differ diff --git a/web/models/colors/detection/v4/nano/epochs_50/last_spray.pt b/web/models/colors/detection/v4/nano/epochs_50/last_spray.pt new file mode 100644 index 0000000..8a844d2 Binary files /dev/null and b/web/models/colors/detection/v4/nano/epochs_50/last_spray.pt differ diff --git a/web/streaming/consumer.py b/web/streaming/consumer.py index 7fcc41c..ec34395 100644 --- a/web/streaming/consumer.py +++ b/web/streaming/consumer.py @@ -26,7 +26,7 @@ clients = set() model = YOLO(MODEL_PATH) -crop_x, crop_y, crop_w, crop_h = 1200, 550, 300, 300 +crop_x, crop_y, crop_w, crop_h = 950, 600, 640, 640 RECORD_DURATION = 60 # 1 минута read_task_lock = asyncio.Lock() @@ -80,11 +80,14 @@ class VideoConsumer(AsyncWebsocketConsumer): "-an", "-vf", crop_filter, "-c:v", "libx264", - "-preset", "veryfast", + "-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 @@ -128,8 +131,13 @@ class VideoConsumer(AsyncWebsocketConsumer): # 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 + from .models import AllowedColor, DetectionHistory + min_width = 30 + min_height = 30 + min_area = 900 while True: try: @@ -141,55 +149,123 @@ class VideoConsumer(AsyncWebsocketConsumer): results = model.predict(source=cropped, save=False, verbose=False) detected = False - annotated_img = img.copy() # Можно заменить на cropped, если хочешь рисовать только в области + 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 - # Получаем координаты и корректируем с учётом 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 - ) + cv2.rectangle(annotated_img, (x1, y1), (x2, y2), (0, 255, 255), 2) + cv2.putText( + annotated_img, + # f"{class_name} {conf:.2f}", + f"quality {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() - ) - 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: + 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": "ok", - "message": "Объектов не обнаружено" + "status": "danger" if status_key == 'bad' else "ok", + "message": "внимание" if status_key == 'bad' else "все хорошо" })) + + + + # Кодируем и отправляем кадр _, jpeg = cv2.imencode('.jpg', annotated_img) @@ -204,6 +280,13 @@ class VideoConsumer(AsyncWebsocketConsumer): 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: diff --git a/web/streaming/migrations/0002_detectionhistory_alter_allowedcolor_name.py b/web/streaming/migrations/0002_detectionhistory_alter_allowedcolor_name.py new file mode 100644 index 0000000..dc33146 --- /dev/null +++ b/web/streaming/migrations/0002_detectionhistory_alter_allowedcolor_name.py @@ -0,0 +1,31 @@ +# Generated by Django 5.2 on 2025-05-28 11:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('streaming', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='DetectionHistory', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('timestamp', models.DateTimeField(auto_now_add=True, verbose_name='Дата и время')), + ('status', models.CharField(choices=[('good', 'Норма'), ('bad', 'Не норма')], max_length=4, verbose_name='Статус')), + ], + options={ + 'verbose_name': 'Запись истории', + 'verbose_name_plural': 'История обнаружений', + 'ordering': ['-timestamp'], + }, + ), + migrations.AlterField( + model_name='allowedcolor', + name='name', + field=models.CharField(help_text='введите цвет', max_length=50, unique=True), + ), + ] diff --git a/web/streaming/models.py b/web/streaming/models.py index 2ef89c6..c1155dd 100644 --- a/web/streaming/models.py +++ b/web/streaming/models.py @@ -21,4 +21,21 @@ class AllowedColor(models.Model): allowed = models.BooleanField(default=True) def __str__(self): - return f"{self.name} ({'Разрешён' if self.allowed else 'Запрещён'})" \ No newline at end of file + return f"{self.name} ({'Разрешён' if self.allowed else 'Запрещён'})" + +class DetectionHistory(models.Model): + STATUS_CHOICES = [ + ('good', 'Норма'), + ('bad', 'Не норма'), + ] + + timestamp = models.DateTimeField(auto_now_add=True, verbose_name='Дата и время') + status = models.CharField(max_length=4, choices=STATUS_CHOICES, verbose_name='Статус') + + class Meta: + ordering = ['-timestamp'] + verbose_name = 'Запись истории' + verbose_name_plural = 'История обнаружений' + + def __str__(self): + return f"{self.get_status_display()} — {self.timestamp:%Y-%m-%d %H:%M:%S}" \ No newline at end of file diff --git a/web/streaming/templates/streaming/stream.html b/web/streaming/templates/streaming/stream.html index 0278a69..49c1b90 100644 --- a/web/streaming/templates/streaming/stream.html +++ b/web/streaming/templates/streaming/stream.html @@ -1,13 +1,49 @@
| Время | +Статус | +
|---|---|
| {{ item.timestamp }} | +{{ item.status }} | +