diff --git a/app/__init__.py b/app/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/app/__pycache__/__init__.cpython-311.pyc b/app/__pycache__/__init__.cpython-311.pyc deleted file mode 100644 index 1e61a46..0000000 Binary files a/app/__pycache__/__init__.cpython-311.pyc and /dev/null differ diff --git a/app/__pycache__/asgi.cpython-311.pyc b/app/__pycache__/asgi.cpython-311.pyc deleted file mode 100644 index b67cde3..0000000 Binary files a/app/__pycache__/asgi.cpython-311.pyc and /dev/null differ diff --git a/app/__pycache__/settings.cpython-311.pyc b/app/__pycache__/settings.cpython-311.pyc deleted file mode 100644 index 671c8b3..0000000 Binary files a/app/__pycache__/settings.cpython-311.pyc and /dev/null differ diff --git a/app/__pycache__/urls.cpython-311.pyc b/app/__pycache__/urls.cpython-311.pyc deleted file mode 100644 index 5cd6a02..0000000 Binary files a/app/__pycache__/urls.cpython-311.pyc and /dev/null differ diff --git a/app/__pycache__/wsgi.cpython-311.pyc b/app/__pycache__/wsgi.cpython-311.pyc deleted file mode 100644 index 0bb13b0..0000000 Binary files a/app/__pycache__/wsgi.cpython-311.pyc and /dev/null differ diff --git a/app/asgi.py b/app/asgi.py deleted file mode 100644 index 2cc5d5f..0000000 --- a/app/asgi.py +++ /dev/null @@ -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 - ) - ), -}) \ No newline at end of file diff --git a/app/settings.py b/app/settings.py deleted file mode 100644 index 11d9d86..0000000 --- a/app/settings.py +++ /dev/null @@ -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' diff --git a/app/urls.py b/app/urls.py deleted file mode 100644 index 2e7e304..0000000 --- a/app/urls.py +++ /dev/null @@ -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")) -] diff --git a/app/wsgi.py b/app/wsgi.py deleted file mode 100644 index 121dd78..0000000 --- a/app/wsgi.py +++ /dev/null @@ -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() diff --git a/streaming/__init__.py b/streaming/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/streaming/__pycache__/__init__.cpython-311.pyc b/streaming/__pycache__/__init__.cpython-311.pyc deleted file mode 100644 index 1c268ef..0000000 Binary files a/streaming/__pycache__/__init__.cpython-311.pyc and /dev/null differ diff --git a/streaming/__pycache__/admin.cpython-311.pyc b/streaming/__pycache__/admin.cpython-311.pyc deleted file mode 100644 index 4b51d1c..0000000 Binary files a/streaming/__pycache__/admin.cpython-311.pyc and /dev/null differ diff --git a/streaming/__pycache__/apps.cpython-311.pyc b/streaming/__pycache__/apps.cpython-311.pyc deleted file mode 100644 index 89bb4e8..0000000 Binary files a/streaming/__pycache__/apps.cpython-311.pyc and /dev/null differ diff --git a/streaming/__pycache__/consumer.cpython-311.pyc b/streaming/__pycache__/consumer.cpython-311.pyc deleted file mode 100644 index 2a3b857..0000000 Binary files a/streaming/__pycache__/consumer.cpython-311.pyc and /dev/null differ diff --git a/streaming/__pycache__/models.cpython-311.pyc b/streaming/__pycache__/models.cpython-311.pyc deleted file mode 100644 index aa2dbb1..0000000 Binary files a/streaming/__pycache__/models.cpython-311.pyc and /dev/null differ diff --git a/streaming/__pycache__/routing.cpython-311.pyc b/streaming/__pycache__/routing.cpython-311.pyc deleted file mode 100644 index 638c236..0000000 Binary files a/streaming/__pycache__/routing.cpython-311.pyc and /dev/null differ diff --git a/streaming/__pycache__/tasks.cpython-311.pyc b/streaming/__pycache__/tasks.cpython-311.pyc deleted file mode 100644 index 6f1ea65..0000000 Binary files a/streaming/__pycache__/tasks.cpython-311.pyc and /dev/null differ diff --git a/streaming/__pycache__/urls.cpython-311.pyc b/streaming/__pycache__/urls.cpython-311.pyc deleted file mode 100644 index ed39e52..0000000 Binary files a/streaming/__pycache__/urls.cpython-311.pyc and /dev/null differ diff --git a/streaming/__pycache__/views.cpython-311.pyc b/streaming/__pycache__/views.cpython-311.pyc deleted file mode 100644 index 3e388cd..0000000 Binary files a/streaming/__pycache__/views.cpython-311.pyc and /dev/null differ diff --git a/streaming/admin.py b/streaming/admin.py deleted file mode 100644 index 582e961..0000000 --- a/streaming/admin.py +++ /dev/null @@ -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',) \ No newline at end of file diff --git a/streaming/apps.py b/streaming/apps.py deleted file mode 100644 index e288979..0000000 --- a/streaming/apps.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.apps import AppConfig - - -class StreamingConfig(AppConfig): - default_auto_field = 'django.db.models.BigAutoField' - name = 'streaming' diff --git a/streaming/consumer.py b/streaming/consumer.py deleted file mode 100644 index 182fcde..0000000 --- a/streaming/consumer.py +++ /dev/null @@ -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}") \ No newline at end of file diff --git a/streaming/migrations/0001_initial.py b/streaming/migrations/0001_initial.py deleted file mode 100644 index bba57f7..0000000 --- a/streaming/migrations/0001_initial.py +++ /dev/null @@ -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)), - ], - ), - ] diff --git a/streaming/migrations/__init__.py b/streaming/migrations/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/streaming/migrations/__pycache__/0001_initial.cpython-311.pyc b/streaming/migrations/__pycache__/0001_initial.cpython-311.pyc deleted file mode 100644 index b87f639..0000000 Binary files a/streaming/migrations/__pycache__/0001_initial.cpython-311.pyc and /dev/null differ diff --git a/streaming/migrations/__pycache__/__init__.cpython-311.pyc b/streaming/migrations/__pycache__/__init__.cpython-311.pyc deleted file mode 100644 index fa4af22..0000000 Binary files a/streaming/migrations/__pycache__/__init__.cpython-311.pyc and /dev/null differ diff --git a/streaming/models.py b/streaming/models.py deleted file mode 100644 index 2dcec3f..0000000 --- a/streaming/models.py +++ /dev/null @@ -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 'Запрещён'})" \ No newline at end of file diff --git a/streaming/routing.py b/streaming/routing.py deleted file mode 100644 index a09d071..0000000 --- a/streaming/routing.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.urls import re_path -from . import consumer - -websocket_urlpatterns = [ - re_path(r'ws/stream/$', consumer.VideoConsumer.as_asgi()), -] \ No newline at end of file diff --git a/streaming/tasks.py b/streaming/tasks.py deleted file mode 100644 index 5bbb83f..0000000 --- a/streaming/tasks.py +++ /dev/null @@ -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)) \ No newline at end of file diff --git a/streaming/templates/streaming/stream.html b/streaming/templates/streaming/stream.html deleted file mode 100644 index 9fab271..0000000 --- a/streaming/templates/streaming/stream.html +++ /dev/null @@ -1,146 +0,0 @@ - - - RTSP Stream - - - - -
- - -
- - - - -
- - - -
-
- Всё хорошо -
- - - \ No newline at end of file diff --git a/streaming/tests.py b/streaming/tests.py deleted file mode 100644 index 7ce503c..0000000 --- a/streaming/tests.py +++ /dev/null @@ -1,3 +0,0 @@ -from django.test import TestCase - -# Create your tests here. diff --git a/streaming/urls.py b/streaming/urls.py deleted file mode 100644 index 0899db6..0000000 --- a/streaming/urls.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.urls import path -from . import views - -urlpatterns = [ - path('', views.stream_view, name='stream'), -] \ No newline at end of file diff --git a/streaming/views.py b/streaming/views.py deleted file mode 100644 index 52e4a95..0000000 --- a/streaming/views.py +++ /dev/null @@ -1,4 +0,0 @@ -from django.shortcuts import render - -def stream_view(request): - return render(request, 'streaming/stream.html') \ No newline at end of file