удалил из корня лишнее

This commit is contained in:
r0mchik 2025-05-19 11:16:03 +07:00
parent a07a752141
commit dc556ddc2b
34 changed files with 0 additions and 543 deletions

View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,25 +0,0 @@
"""
ASGI config for app project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/
"""
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
import streaming.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
streaming.routing.websocket_urlpatterns
)
),
})

View File

@ -1,124 +0,0 @@
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 5.2.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
RTSP_URL = "rtsp://192.168.1.247:554/rtsp/streaming?channel=1&subtype=A"
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-dwz6w*m*yl$!))@7v36)u=034$1=41gp9ph5u7!g3x!b0un#)e'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'streaming',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

View File

@ -1,23 +0,0 @@
"""
URL configuration for app project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('streaming/', include("streaming.urls"))
]

View File

@ -1,16 +0,0 @@
"""
WSGI config for app project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
application = get_wsgi_application()

View File

View File

@ -1,8 +0,0 @@
from django.contrib import admin
from .models import AllowedColor
@admin.register(AllowedColor)
class AllowedColorAdmin(admin.ModelAdmin):
list_display = ('name', 'allowed')
list_editable = ('allowed',)
list_filter = ('allowed',)

View File

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

View File

@ -1,119 +0,0 @@
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 disconnect(self, close_code):
clients.discard(self)
try:
self.send_task.cancel()
await self.send_task
except Exception:
pass
async def send_frames(self):
from .models import AllowedColor
while True:
try:
jpeg_data = await video_frame_queue.get()
img = cv2.imdecode(np.frombuffer(jpeg_data, dtype=np.uint8), cv2.IMREAD_COLOR)
# Обработка нейросетью
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:
await self.send(text_data=json.dumps({
"status": "danger",
"message": f"Запрещённый цвет: {predicted_class}"
}))
else:
await self.send(text_data=json.dumps({
"status": "ok",
"message": "Всё хорошо"
}))
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(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')
for packet in container.demux(video_stream):
for frame in packet.decode():
img = frame.to_ndarray(format='bgr24')
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)
except Exception as e:
print(f"[RTSP ERROR] {e}")

View File

@ -1,22 +0,0 @@
# Generated by Django 5.2 on 2025-05-07 12:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AllowedColor',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(choices=[('red', 'Красный'), ('green', 'Зелёный'), ('blue', 'Синий'), ('yellow', 'Жёлтый'), ('orange', 'Оранжевый'), ('black', 'Чёрный'), ('white', 'Белый')], max_length=50, unique=True)),
('allowed', models.BooleanField(default=True)),
],
),
]

View File

@ -1,21 +0,0 @@
from django.db import models
# Create your models here.
class AllowedColor(models.Model):
COLOR_CHOICES = [
('red', 'Красный'),
('green', 'Зелёный'),
('blue', 'Синий'),
('yellow', 'Жёлтый'),
('orange', 'Оранжевый'),
('black', 'Чёрный'),
('white', 'Белый'),
('woter', 'Вода'),
# добавь нужные цвета
]
name = models.CharField(max_length=50, choices=COLOR_CHOICES, unique=True)
allowed = models.BooleanField(default=True)
def __str__(self):
return f"{self.name} ({'Разрешён' if self.allowed else 'Запрещён'})"

View File

@ -1,6 +0,0 @@
from django.urls import re_path
from . import consumer
websocket_urlpatterns = [
re_path(r'ws/stream/$', consumer.VideoConsumer.as_asgi()),
]

View File

@ -1,14 +0,0 @@
import moviepy as mp
import os
from datetime import datetime
CLIPS_DIR = "media/clips"
os.makedirs(CLIPS_DIR, exist_ok=True)
def save_video_clip(source_path, start_time: datetime, end_time: datetime):
video = mp.VideoFileClip(source_path)
delta_start = (start_time - datetime.fromtimestamp(video.start)).total_seconds()
delta_end = (end_time - datetime.fromtimestamp(video.start)).total_seconds()
clip = video.subclip(delta_start, delta_end)
filename = f"clip_{start_time.strftime('%H%M%S')}_{end_time.strftime('%H%M%S')}.mp4"
clip.write_videofile(os.path.join(CLIPS_DIR, filename))

View File

@ -1,146 +0,0 @@
<html>
<head>
<title>RTSP Stream</title>
</head>
<style>
#container {
position: relative;
width: 640px;
height: 480px;
}
#video {
position: absolute;
top: 0;
left: 0;
}
#overlay {
position: absolute;
top: 0;
left: 0;
cursor: crosshair;
}
</style>
<div id="container">
<img id="video" width="640" height="480"/>
<canvas id="overlay" width="640" height="480"></canvas>
</div>
<body>
<!-- <h1>Stream</h1> -->
<!-- <img id="video" width="640" height="480"/> -->
<br>
<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;">
Всё хорошо
</div>
<script>
let socket = new WebSocket("ws://localhost:8000/ws/stream/");
let statusDiv = document.getElementById("status");
let startX, startY, endX, endY;
let isDrawing = false;
const canvas = document.getElementById('overlay');
const ctx = canvas.getContext('2d');
canvas.onmousedown = e => {
isDrawing = true;
startX = e.offsetX;
startY = e.offsetY;
};
canvas.onmousemove = e => {
if (!isDrawing) return;
endX = e.offsetX;
endY = e.offsetY;
const width = endX - startX;
const height = endY - startY;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = 'lime';
ctx.lineWidth = 2;
ctx.strokeRect(startX, startY, width, height);
};
canvas.onmouseup = () => {
isDrawing = false;
};
function mark(type) {
if (startX == null || endX == null) {
alert("Сначала выделите область!");
return;
}
const scaleX = 2560 / 640;
const scaleY = 1440 / 480;
const cropX = Math.round(Math.min(startX, endX) * scaleX);
const cropY = Math.round(Math.min(startY, endY) * scaleY);
const cropW = Math.round(Math.abs(endX - startX) * scaleX);
const cropH = Math.round(Math.abs(endY - startY) * scaleY);
socket.send(JSON.stringify({type, cropX, cropY, cropW, cropH}));
statusDiv.innerText = "🔴 Запись идет...";
setTimeout(() => {
statusDiv.innerText = "";
}, 1 * 60 * 1000); // 10 минут
}
function markGood() { mark("good"); }
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;
}
};
socket.onmessage = event => {
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;
}
} catch {
document.getElementById("video").src = 'data:image/jpeg;base64,' + event.data;
}
};
// socket.onmessage = function(event) {
// const data = event.data;
// try {
// const parsed = JSON.parse(data);
// if (parsed.alert) {
// // Показываем уведомление
// const notification = document.getElementById('notification');
// notification.textContent = parsed.alert;
// notification.style.display = 'block';
// // Скрываем через 3 секунды
// setTimeout(() => {
// notification.style.display = 'none';
// }, 3000);
// } else {
// // обработка кадра
// }
// } catch (e) {
// // обработка обычного изображения
// }
// };
</script>
</body>
</html>

View File

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

View File

@ -1,6 +0,0 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.stream_view, name='stream'),
]

View File

@ -1,4 +0,0 @@
from django.shortcuts import render
def stream_view(request):
return render(request, 'streaming/stream.html')