This commit is contained in:
r0mchik 2025-06-03 13:14:25 +07:00
parent 719bebc7c1
commit 7264bdc956
31 changed files with 462 additions and 128 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

@ -7,53 +7,15 @@ services:
daphne -b 0.0.0.0 -p 8000 app.asgi:application" daphne -b 0.0.0.0 -p 8000 app.asgi:application"
volumes: volumes:
- .:/app - .:/app
- ./media:/app/media - ./web/media:/app/media
- ./web/staticfiles:/app/web/staticfiles - ./web/staticfiles:/app/web/staticfiles
# - ./media:/app/media
ports: ports:
- "8000:8000" - "8000:8000"
# expose:
# - 8000
depends_on: depends_on:
- redis - redis
# - vpn # - 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: redis:
image: redis:alpine image: redis:alpine
container_name: liquid-redis-2 container_name: liquid-redis-2

View File

@ -7,32 +7,17 @@ services:
daphne -b 0.0.0.0 -p 8106 app.asgi:application" daphne -b 0.0.0.0 -p 8106 app.asgi:application"
volumes: volumes:
- .:/app - .:/app
- ./media:/app/media - ./web/media:/app/media
- ./web/staticfiles:/app/web/staticfiles - ./web/staticfiles:/app/web/staticfiles
# - ./media:/app/media
ports: ports:
- "8106:8106" - "8106:8106"
#expose:
# - "8106"
depends_on: depends_on:
- redis - redis
# - vpn
# network_mode: "service:vpn"
restart: always 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: # nginx:
# build: ./nginx/dev # build: ./nginx/dev
# # image: nginx:latest # # image: nginx:latest
@ -46,7 +31,6 @@ services:
# restart: always # restart: always
redis: redis:
image: redis:alpine image: redis:alpine
volumes: volumes:
@ -61,4 +45,4 @@ services:
restart: always restart: always
volumes: volumes:
redis_data: 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

@ -129,7 +129,7 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images) # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/ # https://docs.djangoproject.com/en/5.2/howto/static-files/
STATIC_URL = 'staticfiles' STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Default primary key field type # Default primary key field type

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

@ -26,7 +26,7 @@ clients = set()
model = YOLO(MODEL_PATH) 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 минута RECORD_DURATION = 60 # 1 минута
read_task_lock = asyncio.Lock() read_task_lock = asyncio.Lock()
@ -80,11 +80,14 @@ class VideoConsumer(AsyncWebsocketConsumer):
"-an", "-an",
"-vf", crop_filter, "-vf", crop_filter,
"-c:v", "libx264", "-c:v", "libx264",
"-preset", "veryfast", "-preset", "slow",
filename filename
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
await self.send(text_data="recording_started") await self.send(text_data="recording_started")
# используется для classification
# async def send_frames(self): # async def send_frames(self):
# from .models import AllowedColor # from .models import AllowedColor
@ -128,8 +131,13 @@ class VideoConsumer(AsyncWebsocketConsumer):
# except Exception as e: # except Exception as e:
# print(f"[SEND_FRAME ERROR]: {e}") # print(f"[SEND_FRAME ERROR]: {e}")
# await asyncio.sleep(0.04) # await asyncio.sleep(0.04)
# используется для detection
async def send_frames(self): 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: while True:
try: try:
@ -141,55 +149,123 @@ class VideoConsumer(AsyncWebsocketConsumer):
results = model.predict(source=cropped, save=False, verbose=False) results = model.predict(source=cropped, save=False, verbose=False)
detected = False detected = False
annotated_img = img.copy() # Можно заменить на cropped, если хочешь рисовать только в области annotated_img = img.copy()
# annotated_img = cropped # для отображения рабочей области нейронки
for box in results[0].boxes: for box in results[0].boxes:
cls_id = int(box.cls[0]) cls_id = int(box.cls[0])
conf = float(box.conf[0]) conf = float(box.conf[0])
class_name = results[0].names[cls_id] 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": if class_name == "yellow":
detected = True 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.rectangle(annotated_img, (x1, y1), (x2, y2), (0, 255, 255), 2)
cv2.putText( cv2.putText(
annotated_img, annotated_img,
f"{class_name} {conf:.2f}", # f"{class_name} {conf:.2f}",
(x1, y1 - 10), f"quality {conf:.2f}",
cv2.FONT_HERSHEY_SIMPLEX, (x1, y1 - 10),
0.9, cv2.FONT_HERSHEY_SIMPLEX,
(0, 255, 255), 0.9,
2 (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: if detected:
# определяем статус
allowed_color = await asyncio.to_thread( 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: status_key = 'bad' if allowed_color and not allowed_color.allowed else 'good'
await self.send(text_data=json.dumps({
"status": "danger", # сохраняем только 'bad'
"message": "Обнаружен запрещённый цвет" if status_key == 'bad':
})) await asyncio.to_thread(
else: lambda: DetectionHistory.objects.create(status=status_key)
await self.send(text_data=json.dumps({ )
"status": "ok", # if conf <= 30:
"message": "Yellow — разрешён" # await asyncio.to_thread(
})) # lambda
else: # )
# отправляем статус клиенту
await self.send(text_data=json.dumps({ await self.send(text_data=json.dumps({
"status": "ok", "status": "danger" if status_key == 'bad' else "ok",
"message": "Объектов не обнаружено" "message": "внимание" if status_key == 'bad' else "все хорошо"
})) }))
# Кодируем и отправляем кадр # Кодируем и отправляем кадр
_, jpeg = cv2.imencode('.jpg', annotated_img) _, jpeg = cv2.imencode('.jpg', annotated_img)
@ -204,6 +280,13 @@ class VideoConsumer(AsyncWebsocketConsumer):
print(f"[SEND_FRAME ERROR]: {e}") print(f"[SEND_FRAME ERROR]: {e}")
await asyncio.sleep(0.04) await asyncio.sleep(0.04)
async def red_line():
return
async def read_rtsp_stream(): async def read_rtsp_stream():
global read_task global read_task
try: 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

@ -21,4 +21,21 @@ class AllowedColor(models.Model):
allowed = models.BooleanField(default=True) allowed = models.BooleanField(default=True)
def __str__(self): def __str__(self):
return f"{self.name} ({'Разрешён' if self.allowed else 'Запрещён'})" 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

@ -1,13 +1,49 @@
<html> <html>
<head> <head>
<title>RTSP Stream</title> <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> </head>
<style> <style>
#container { #container {
position: relative; position: relative;
width: 640px; width: 1280px;
height: 480px; height: 720px;
} }
#video { #video {
position: absolute; position: absolute;
@ -23,16 +59,57 @@
</style> </style>
<div id="container"> <div id="container">
<img id="video" width="640" height="480"/> <img id="video" width="1280" height="720"/>
<canvas id="overlay" width="640" height="480"></canvas> <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> </div>
<body> <body>
<!-- <h1>Stream</h1> --> <!-- <h1>Stream</h1> -->
<!-- <img id="video" width="640" height="480"/> --> <!-- <img id="video" width="640" height="480"/> -->
<br> <br>
<button onclick="markGood()">Хорошая жижа</button> <button onclick="markGood()">Норма</button>
<button onclick="markBad()">Плохая жижа</button> <button onclick="markBad()">Не норма</button>
<div id="status" style="color:red; font-weight:bold; margin-top:10px;"></div> <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;"> <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; return;
} }
const scaleX = 2560 / 640; const scaleX = 2560 / 1280;
const scaleY = 1440 / 480; const scaleY = 1440 / 720;
const cropX = Math.round(Math.min(startX, endX) * scaleX); const cropX = Math.round(Math.min(startX, endX) * scaleX);
const cropY = Math.round(Math.min(startY, endY) * scaleY); const cropY = Math.round(Math.min(startY, endY) * scaleY);
@ -99,26 +176,48 @@
function markBad() { mark("bad"); } function markBad() { mark("bad"); }
socket.onmessage = event => { socket.onmessage = event => {
if (event.data === "recording_started") { // 1) Если старт записи
statusDiv.innerText = "🔴 Запись идет..."; if (event.data === "recording_started") {
} else { statusDiv.innerText = "🔴 Запись идет…";
document.getElementById("video").src = 'data:image/jpeg;base64,' + event.data; return;
} }
};
socket.onmessage = event => {
try {
const data = JSON.parse(event.data);
if (data.status === "danger") { // 2) Попытаемся распарсить JSON
document.getElementById("color-status").style.backgroundColor = "red"; let data;
document.getElementById("color-status").innerText = data.message; try {
} else if (data.status === "ok") { data = JSON.parse(event.data);
document.getElementById("color-status").style.backgroundColor = "green";
document.getElementById("color-status").innerText = data.message;
}
} catch { } catch {
// это JPEG‑кадр
document.getElementById("video").src = 'data:image/jpeg;base64,' + event.data; 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> </script>
</body> </body>
</html> </html>

View File

@ -1,9 +1,12 @@
from django.shortcuts import render from django.shortcuts import render
from django.conf import settings from django.conf import settings
from .models import DetectionHistory
def stream_view(request): def stream_view(request):
history = DetectionHistory.objects.all()[:20]
return render(request, 'streaming/stream.html',{ return render(request, 'streaming/stream.html',{
"websocket_url": settings.WEBSOCKET_URL "websocket_url": settings.WEBSOCKET_URL,
"history": history
}) })