Compare commits

...

19 Commits
main ... dev

Author SHA1 Message Date
3cbe01a17d v0.0.00.5 2025-06-05 17:51:09 +07:00
7146efe8c6 v0.0.00.5 2025-06-05 17:31:39 +07:00
62464ea1a7 v0.0.00.5 2025-06-05 17:07:13 +07:00
f7e49dfceb v0.0.00.5 2025-06-05 17:01:32 +07:00
7932717980 v0.0.00.5 2025-06-05 16:46:48 +07:00
df69a89ed7 v0.0.00.5 2025-06-05 15:54:00 +07:00
5c815ea817 v0.0.00.5 2025-06-05 15:42:24 +07:00
b5002006d0 v0.0.00.5 2025-06-05 15:29:44 +07:00
36aacf8189 v0.0.00.5 2025-06-05 14:52:18 +07:00
6803a3ab82 v0.0.00.5 2025-06-05 14:11:29 +07:00
62232fd75a v0.0.4 2025-06-05 12:57:20 +07:00
644341e420 v0.0.4 2025-06-05 12:22:28 +07:00
9fc69f633c v0.0.4 2025-06-05 12:19:12 +07:00
75b55eb9a3 v0.0.4 2025-06-04 13:25:06 +07:00
cc8abbe006 v0.0.5 2025-06-03 18:06:01 +07:00
b2dabba384 v0.0.5 2025-06-03 18:00:47 +07:00
1814b59855 v0.0.4 2025-06-03 14:33:26 +07:00
3ca49eab31 v0.0.4 2025-06-03 14:32:42 +07:00
7264bdc956 v0.0.4 2025-06-03 13:14:25 +07:00
50 changed files with 939 additions and 213 deletions

View File

@ -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'

View File

@ -1,7 +1,14 @@
SECRET_KEY - секретный ключ django
RTSP_URL - путь до камеры. Пример: rtsp://admin:admin@192.168.1.108:554/cam/realmonitor?channel=1&subtype=0
MODEL_PATH - относительный путь до модели нейросети. Находятся по пути web/models
развертывание:
1) git clone https://git.cybercode.pro/roman/liquid.git
2) задаем переменные .env
3) docker-compose up --build
3) проверка драйвера nvidia, если нужно использовать на gpu, командой - nvidia-smi
4) в зависимости от версии выбрать нужный docker-compose
5) для версии cuda 12.8 - docker-compose -f docker-compose-gpu-cuda128-dev.yaml up --build -d
login - user
password - 4dpnJdw8CSqUx7Y

4
dev.env Normal file
View File

@ -0,0 +1,4 @@
SECRET_KEY='django-insecure-dwz6w*m*yl$!))@7v36)u=034$1=41gp9ph5u7!g3x!b0un#)e'
WEBSOCKET_URL='ws://localhost:8000/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'

View File

@ -1,75 +0,0 @@
services:
web:
build: ./web
container_name: liquid-web-2
command: >
sh -c "python manage.py collectstatic --noinput &&
daphne -b 0.0.0.0 -p 8000 app.asgi:application"
volumes:
- .:/app
- ./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
volumes:
- redis_data:/data
ports:
- "6378:6378"
healthcheck:
test: [ "CMD-SHELL", "redis-cli ping | grep PONG" ]
interval: 1s
timeout: 3s
retries: 5
volumes:
redis_data:

View File

@ -1,64 +0,0 @@
services:
web:
container_name: liquid_web
build: ./web
command: >
sh -c "python manage.py collectstatic --noinput &&
daphne -b 0.0.0.0 -p 8106 app.asgi:application"
volumes:
- .:/app
- ./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
# ports:
# - "80:80"
# volumes:
# # - ./nginx/nginx.conf:/etc/nginx/nginx.conf
# - ./nginx/nginx/conf.d/nginx.conf:/etc/nginx/conf.d/nginx.conf
# depends_on:
# - web
# restart: always
redis:
image: redis:alpine
volumes:
- redis_data:/data
ports:
- "6378:6378"
healthcheck:
test: [ "CMD-SHELL", "redis-cli ping | grep PONG" ]
interval: 1s
timeout: 3s
retries: 5
restart: always
volumes:
redis_data:

View File

@ -0,0 +1,36 @@
services:
web:
build:
context: ../web
dockerfile: Dockerfiles/Dockerfile-dev
container_name: liquid-web-dev
command: >
sh -c "python manage.py collectstatic --noinput &&
daphne -b 0.0.0.0 -p 8000 app.asgi:application"
volumes:
- ..:/app
- ../web/media:/app/media
- ../web/staticfiles:/app/web/staticfiles
ports:
- "8000:8000"
depends_on:
- redis
# - vpn
redis:
image: redis:alpine
container_name: liquid-redis-dev
volumes:
- redis_data:/data
ports:
- "6378:6378"
healthcheck:
test: [ "CMD-SHELL", "redis-cli ping | grep PONG" ]
interval: 1s
timeout: 3s
retries: 5
volumes:
redis_data:

View File

@ -0,0 +1,40 @@
version: '3.9'
services:
web:
build:
context: ../web
dockerfile: Dockerfiles/Dockerfile-gpu-cuda126-dev
container_name: liquid-web-gpu-cuda126-dev
command: >
sh -c "python manage.py collectstatic --noinput &&
daphne -b 0.0.0.0 -p 8000 app.asgi:application"
volumes:
- ..:/app
- ../web/media:/app/media
- ../web/staticfiles:/app/web/staticfiles
ports:
- "8000:8000"
depends_on:
- redis
deploy:
resources:
reservations:
devices:
- capabilities: [gpu]
redis:
image: redis:alpine
container_name: liquid-redis-gpu-cuda126-dev
volumes:
- redis_data:/data
ports:
- "6378:6378"
healthcheck:
test: ["CMD-SHELL", "redis-cli ping | grep PONG"]
interval: 1s
timeout: 3s
retries: 5
volumes:
redis_data:

View File

@ -0,0 +1,40 @@
version: '3.9'
services:
web:
build:
context: ../web
dockerfile: Dockerfiles/Dockerfile-gpu-cuda128-dev
container_name: liquid-web-gpu-cuda128-dev
command: >
sh -c "python manage.py collectstatic --noinput &&
daphne -b 0.0.0.0 -p 8000 app.asgi:application"
volumes:
- ..:/app
- ../web/media:/app/media
- ../web/staticfiles:/app/web/staticfiles
ports:
- "8000:8000"
depends_on:
- redis
deploy:
resources:
reservations:
devices:
- capabilities: [gpu]
redis:
image: redis:alpine
container_name: liquid-redis-gpu-cuda128-dev
volumes:
- redis_data:/data
ports:
- "6378:6378"
healthcheck:
test: ["CMD-SHELL", "redis-cli ping | grep PONG"]
interval: 1s
timeout: 3s
retries: 5
volumes:
redis_data:

View File

@ -0,0 +1,38 @@
services:
web:
build:
context: ../web
dockerfile: Dockerfiles/Dockerfile
container_name: liquid_web-2
command: >
sh -c "python manage.py collectstatic --noinput &&
daphne -b 0.0.0.0 -p 8106 app.asgi:application"
volumes:
- ..:/app
- ../web/media:/app/media
- ../web/staticfiles:/app/web/staticfiles
ports:
- "8106:8106"
depends_on:
- redis
restart: always
redis:
image: redis:alpine
container_name: liquid_redis-2
volumes:
- redis_data:/data
ports:
- "6378:6378"
healthcheck:
test: [ "CMD-SHELL", "redis-cli ping | grep PONG" ]
interval: 1s
timeout: 3s
retries: 5
restart: always
volumes:
redis_data:

4
example.env Normal file
View File

@ -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'

View File

@ -19,7 +19,7 @@ WORKDIR /app/web
RUN cd /app/web && mkdir logs
COPY requirements.txt .
COPY requirements/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
COPY models ./models

View File

@ -0,0 +1,24 @@
FROM ubuntu:22.04
# Системные зависимости
RUN apt-get update && apt-get install -y --no-install-recommends \
ffmpeg libgl1 libglib2.0-0 gcc libsm6 libxext6 libxrender-dev \
python3.11 python3.11-venv python3.11-dev python3-pip \
&& rm -rf /var/lib/apt/lists/*
# Python 3.11 по умолчанию
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 && \
python -m pip install --upgrade pip
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app/web
# requirements
COPY requirements/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Копируем всё
# всё из web/ — включая models, app, etc.
COPY . .

View File

@ -0,0 +1,24 @@
FROM nvidia/cuda:12.6.0-cudnn-runtime-ubuntu22.04
# Системные зависимости
RUN apt-get update && apt-get install -y --no-install-recommends \
ffmpeg libgl1 libglib2.0-0 gcc libsm6 libxext6 libxrender-dev \
python3.11 python3.11-venv python3.11-dev python3-pip \
&& rm -rf /var/lib/apt/lists/*
# Python 3.11 по умолчанию
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 && \
python -m pip install --upgrade pip
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app/web
# requirements
COPY requirements/requirements-gpu-cuda126.txt .
RUN pip install --no-cache-dir -r requirements-gpu-cuda126.txt
# Копируем всё
# всё из web/ — включая models, app, etc.
COPY . .

View File

@ -0,0 +1,24 @@
FROM nvidia/cuda:12.8.0-cudnn-runtime-ubuntu22.04
# Системные зависимости
RUN apt-get update && apt-get install -y --no-install-recommends \
ffmpeg libgl1 libglib2.0-0 gcc libsm6 libxext6 libxrender-dev \
python3.11 python3.11-venv python3.11-dev python3-pip \
&& rm -rf /var/lib/apt/lists/*
# Python 3.11 по умолчанию
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 && \
python -m pip install --upgrade pip
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app/web
# requirements
COPY requirements/requirements-gpu-cuda128.txt .
RUN pip install --no-cache-dir -r requirements-gpu-cuda128.txt
# Копируем всё
# всё из web/ — включая models, app, etc.
COPY . .

23
web/app/middleware.py Normal file
View File

@ -0,0 +1,23 @@
from django.conf import settings
from django.shortcuts import redirect
import re
EXEMPT_URLS = [
re.compile(settings.LOGIN_URL.lstrip('/')),
re.compile(r'^admin/login/$'),
re.compile(r'^streaming/login/$'),
re.compile(r'^streaming/$'),
re.compile(r'^static/'),
re.compile(r'^media/'),
]
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
path = request.path_info.lstrip('/')
if not request.user.is_authenticated:
if not any(pattern.match(path) for pattern in EXEMPT_URLS):
return redirect(settings.LOGIN_URL)
return self.get_response(request)

View File

@ -31,7 +31,7 @@ SECRET_KEY = os.getenv("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
DEBUG = True
ALLOWED_HOSTS = ['*']
@ -55,10 +55,15 @@ MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'app.middleware.LoginRequiredMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
LOGIN_URL = '/streaming/login/'
LOGIN_REDIRECT_URL = '/streaming/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
@ -67,7 +72,7 @@ ROOT_URLCONF = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
@ -79,11 +84,18 @@ TEMPLATES = [
},
]
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
CSRF_TRUSTED_ORIGINS = [
'http://192.168.0.169:82',
'http://192.168.0.169:8106'
]
WSGI_APPLICATION = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
@ -129,7 +141,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

View File

@ -16,8 +16,9 @@ Including another URLconf
"""
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views
urlpatterns = [
path('admin/', admin.site.urls),
path('streaming/', include("streaming.urls"))
path('streaming/', include("streaming.urls")),
]

0
web/dataset/__init__.py Normal file
View File

3
web/dataset/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
web/dataset/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class DatasetConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'dataset'

View File

3
web/dataset/models.py Normal file
View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

3
web/dataset/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
web/dataset/views.py Normal file
View File

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -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

View File

@ -0,0 +1,81 @@
asgiref==3.8.1
channels==4.2.2
daphne==4.1.2
Django==5.2
python-dotenv==1.1.0
sqlparse==0.5.3
whitenoise==6.9.0
channels_redis==4.2.0
# WebSocket and async dependencies
autobahn==24.4.2
Automat==25.4.16
constantly==23.10.4
hyperlink==21.0.0
incremental==24.7.2
pyasn1==0.6.1
pyasn1_modules==0.4.2
service-identity==24.2.0
Twisted==24.11.0
txaio==23.1.1
zope.interface==7.2
# Security and networking
certifi==2025.4.26
cffi==1.17.1
charset-normalizer==3.4.2
cryptography==44.0.3
idna==3.10
pyOpenSSL==25.0.0
requests==2.32.3
urllib3==2.4.0
# Data science and visualization
attrs==25.3.0
contourpy==1.3.2
cycler==0.12.1
fonttools==4.57.0
kiwisolver==1.4.8
matplotlib==3.10.1
numpy==2.2.5
pandas==2.2.3
pyparsing==3.2.3
python-dateutil==2.9.0.post0
pytz==2025.2
scipy==1.15.2
seaborn==0.13.2
tzdata==2025.2
# Computer vision and multimedia
av==14.3.0
imageio==2.37.0
imageio-ffmpeg==0.6.0
moviepy==2.1.2
opencv-python-headless==4.11.0.86 # Uncommented and fixed
proglog==0.1.11
# PyTorch and ML
torch==2.7.0+cu126
torchvision==0.22.0+cu126
torchaudio==2.7.0+cu126
--extra-index-url https://download.pytorch.org/whl/cu126
ultralytics==8.3.127
ultralytics-thop==2.0.14
# Utilities
colorama==0.4.6
decorator==5.2.1
filelock==3.18.0
fsspec==2025.3.2
Jinja2==3.1.6
MarkupSafe==3.0.2
mpmath==1.3.0
networkx==3.4.2
packaging==25.0
psutil==7.0.0
py-cpuinfo==9.0.0
PyYAML==6.0.2
six==1.17.0
sympy==1.14.0
tqdm==4.67.1
typing_extensions==4.13.2

View File

@ -0,0 +1,81 @@
asgiref==3.8.1
channels==4.2.2
daphne==4.1.2
Django==5.2
python-dotenv==1.1.0
sqlparse==0.5.3
whitenoise==6.9.0
channels_redis==4.2.0
# WebSocket and async dependencies
autobahn==24.4.2
Automat==25.4.16
constantly==23.10.4
hyperlink==21.0.0
incremental==24.7.2
pyasn1==0.6.1
pyasn1_modules==0.4.2
service-identity==24.2.0
Twisted==24.11.0
txaio==23.1.1
zope.interface==7.2
# Security and networking
certifi==2025.4.26
cffi==1.17.1
charset-normalizer==3.4.2
cryptography==44.0.3
idna==3.10
pyOpenSSL==25.0.0
requests==2.32.3
urllib3==2.4.0
# Data science and visualization
attrs==25.3.0
contourpy==1.3.2
cycler==0.12.1
fonttools==4.57.0
kiwisolver==1.4.8
matplotlib==3.10.1
numpy==2.2.5
pandas==2.2.3
pyparsing==3.2.3
python-dateutil==2.9.0.post0
pytz==2025.2
scipy==1.15.2
seaborn==0.13.2
tzdata==2025.2
# Computer vision and multimedia
av==14.3.0
imageio==2.37.0
imageio-ffmpeg==0.6.0
moviepy==2.1.2
opencv-python-headless==4.11.0.86 # Uncommented and fixed
proglog==0.1.11
# PyTorch and ML
torch==2.7.0+cu128
torchvision==0.22.0+cu128
torchaudio==2.7.0+cu128
--extra-index-url https://download.pytorch.org/whl/cu128
ultralytics==8.3.127
ultralytics-thop==2.0.14
# Utilities
colorama==0.4.6
decorator==5.2.1
filelock==3.18.0
fsspec==2025.3.2
Jinja2==3.1.6
MarkupSafe==3.0.2
mpmath==1.3.0
networkx==3.4.2
packaging==25.0
psutil==7.0.0
py-cpuinfo==9.0.0
PyYAML==6.0.2
six==1.17.0
sympy==1.14.0
tqdm==4.67.1
typing_extensions==4.13.2

View File

@ -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 = 1030, 650, 450, 500
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,56 +149,124 @@ 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"spray {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()
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:
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)
frame_data = base64.b64encode(jpeg.tobytes()).decode('utf-8')
@ -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:

View File

@ -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),
),
]

View File

@ -22,3 +22,20 @@ class AllowedColor(models.Model):
def __str__(self):
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}"

View File

@ -3,4 +3,5 @@ from . import consumer
websocket_urlpatterns = [
re_path(r'ws/stream/$', consumer.VideoConsumer.as_asgi()),
re_path(r'ws/stream$', consumer.VideoConsumer.as_asgi())
]

View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
{% if error %}<p style="color:red;">{{ error }}</p>{% endif %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<label>Username:</label><input type="text" name="username"><br>
<label>Password:</label><input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

View File

@ -1,13 +1,49 @@
<html>
<head>
<title>RTSP Stream</title>
<style>
.history-table-container {
position: absolute;
top: 20px;
right: 20px;
width: 300px;
max-height: 400px;
overflow-y: auto;
background-color: white;
border: 1px solid #ccc;
border-radius: 10px;
padding: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
font-family: Arial, sans-serif;
}
.history-table {
width: 100%;
border-collapse: collapse;
}
.history-table th, .history-table td {
padding: 5px;
text-align: left;
font-size: 14px;
}
.history-table th {
background-color: #f0f0f0;
}
.history-table tr:nth-child(even) {
background-color: #fafafa;
}
</style>
</head>
<style>
#container {
position: relative;
width: 640px;
height: 480px;
width: 1280px;
height: 720px;
}
#video {
position: absolute;
@ -23,16 +59,57 @@
</style>
<div id="container">
<img id="video" width="640" height="480"/>
<canvas id="overlay" width="640" height="480"></canvas>
<img id="video" width="1280" height="720"/>
<canvas id="overlay" width="1280" height="720"></canvas>
</div>
<!-- <div id="history-container">
<h3>История обнаружений</h3>
<table id="history-table" border="1" cellpadding="4" cellspacing="0">
<thead>
<tr>
<th>Дата и время</th>
<th>Статус</th>
</tr>
</thead>
<tbody>
{% for record in history %}
<tr>
<td>{{ record.timestamp|date:"Y-m-d H:i:s" }}</td>
<td>{{ record.get_status_display }}</td>
</tr>
{% empty %}
<tr><td colspan="2">Нет записей</td></tr>
{% endfor %}
</tbody>
</table>
</div> -->
<div class="history-table-container">
<table id="history-table" class="history-table">
<thead>
<tr>
<th>Время</th>
<th>Статус</th>
</tr>
</thead>
<tbody>
{% for item in history %}
<tr>
<td>{{ item.timestamp }}</td>
<td>{{ item.status }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<body>
<!-- <h1>Stream</h1> -->
<!-- <img id="video" width="640" height="480"/> -->
<br>
<button onclick="markGood()">Хорошая жижа</button>
<button onclick="markBad()">Плохая жижа</button>
<button onclick="markGood()">Норма</button>
<button onclick="markBad()">Не норма</button>
<div id="status" style="color:red; font-weight:bold; margin-top:10px;"></div>
<div id="color-status" style="width: 300px; height: 40px; background-color: green; color: white; text-align: center; line-height: 40px; font-weight: bold;">
@ -79,8 +156,8 @@
return;
}
const scaleX = 2560 / 640;
const scaleY = 1440 / 480;
const scaleX = 2560 / 1280;
const scaleY = 1440 / 720;
const cropX = Math.round(Math.min(startX, endX) * scaleX);
const cropY = Math.round(Math.min(startY, endY) * scaleY);
@ -99,26 +176,48 @@
function markBad() { mark("bad"); }
socket.onmessage = event => {
if (event.data === "recording_started") {
statusDiv.innerText = "🔴 Запись идет...";
} else {
document.getElementById("video").src = 'data:image/jpeg;base64,' + event.data;
}
};
// 1) Если старт записи
if (event.data === "recording_started") {
statusDiv.innerText = "🔴 Запись идет…";
return;
}
socket.onmessage = event => {
// 2) Попытаемся распарсить JSON
let data;
try {
const data = JSON.parse(event.data);
if (data.status === "danger") {
document.getElementById("color-status").style.backgroundColor = "red";
document.getElementById("color-status").innerText = data.message;
} else if (data.status === "ok") {
document.getElementById("color-status").style.backgroundColor = "green";
document.getElementById("color-status").innerText = data.message;
}
data = JSON.parse(event.data);
} catch {
// это JPEG‑кадр
document.getElementById("video").src = 'data:image/jpeg;base64,' + event.data;
return;
}
// 3) Обработка статуса
if (data.status === "danger") {
document.getElementById("color-status").style.backgroundColor = "red";
document.getElementById("color-status").innerText = data.message;
} else if (data.status === "ok") {
document.getElementById("color-status").style.backgroundColor = "green";
document.getElementById("color-status").innerText = data.message;
}
// 4) Добавляем в таблицу только "не норма"
if (data.status === "danger") {
const tableBody = document.querySelector('#history-table tbody');
const row = document.createElement('tr');
const now = new Date();
const formatted = now.getFullYear() + '-' +
String(now.getMonth()+1).padStart(2,'0') + '-' +
String(now.getDate()).padStart(2,'0') + ' ' +
String(now.getHours()).padStart(2,'0') + ':' +
String(now.getMinutes()).padStart(2,'0') + ':' +
String(now.getSeconds()).padStart(2,'0');
row.innerHTML = `
<td>${formatted}</td>
<td>Не норма</td>
`;
tableBody.insertBefore(row, tableBody.firstChild);
if (tableBody.rows.length > 20) tableBody.deleteRow(-1);
}
};
@ -142,6 +241,46 @@
// // обработка обычного изображения
// }
// };
// socket.onmessage = event => {
// try {
// const data = JSON.parse(event.data);
// // --- ваш существующий код: обновление color-status и видео ---
// // Если это событие «danger» или «ok» — добавляем в историю
// if (data.status === "danger") {
// const tableBody = document.querySelector('#history-table tbody');
// const row = document.createElement('tr');
// const now = new Date();
// const formatted = now.getFullYear() + '-' +
// String(now.getMonth()+1).padStart(2,'0') + '-' +
// String(now.getDate()).padStart(2,'0') + ' ' +
// String(now.getHours()).padStart(2,'0') + ':' +
// String(now.getMinutes()).padStart(2,'0') + ':' +
// String(now.getSeconds()).padStart(2,'0');
// // Статус: текст и цвет
// const statusText = data.status === "danger" ? "Не норма" : "Норма";
// row.innerHTML = `
// <td>${formatted}</td>
// <td>${statusText}</td>
// `;
// // Вставляем в начало таблицы
// tableBody.insertBefore(row, tableBody.firstChild);
// // При желании, обрезать историю до N записей:
// if (tableBody.rows.length > 20) {
// tableBody.deleteRow(-1);
// }
// }
// } catch {
// // Это, скорее всего, кадр изображения
// document.getElementById("video").src = 'data:image/jpeg;base64,' + event.data;
// }
// };
</script>
</body>
</html>

View File

@ -2,5 +2,7 @@ from django.urls import path
from . import views
urlpatterns = [
path('login/', views.login_view, name='login'),
path('logout/', views.logout_view, name='logout'),
path('', views.stream_view, name='stream'),
]

View File

@ -1,10 +1,36 @@
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.conf import settings
from .models import DetectionHistory
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
@csrf_protect
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user:
login(request, user)
return redirect('stream')
else:
return render(request, 'login.html', {'error': 'Неверный логин или пароль'})
return render(request, 'login.html')
def logout_view(request):
logout(request)
return redirect('login')
@login_required
def stream_view(request):
history = DetectionHistory.objects.all()[:20]
return render(request, 'streaming/stream.html',{
"websocket_url": settings.WEBSOCKET_URL
"websocket_url": settings.WEBSOCKET_URL,
"history": history
})
# @login_required
# def home_view(request):
# return render(request, 'streaming/stream.html')