commit 645e561ebfe33fddef940d305c491d8dc6e6e4ae Author: роман печеркин Date: Mon Apr 14 21:10:08 2025 +0700 update diff --git a/.env b/.env new file mode 100644 index 0000000..154748b --- /dev/null +++ b/.env @@ -0,0 +1,7 @@ +DB_NAME=dbname +DB_USER=username +DB_PASSWORD=urpassword +DB_HOST=localhost +DB_PORT=5432 + +RTSP_URL=C:/kpp/app/images/шлагбаум1.mkv # путь к камере (пока что только видео) \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a9fb302 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +.idea +.ipynb_checkpoints +.mypy_cache +.vscode +__pycache__ +.pytest_cache +htmlcov +dist +site +.coverage* +coverage.xml +.netlify +test.db +log.txt +Pipfile.lock +env3.* +env +docs_build +site_build +venv +docs.zip +archive.zip + +# vim temporary files +*~ +.*.sw? +.cache +# macOS +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e4bc439 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +запуск программы осуществляется при помощи uvicorn + +uvicorn main:app --host 0.0.0.0 --port 8000 + +endpoints : +http://hostname:8000/app/v1/stream \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..448db4d --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,7 @@ +# from ultralytics import YOLO +# from .api import * +# import os +# from .services import * + +# from services import * +# from api import * \ No newline at end of file diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/json/LicensePlateData.json b/app/api/json/LicensePlateData.json new file mode 100644 index 0000000..1cc09da --- /dev/null +++ b/app/api/json/LicensePlateData.json @@ -0,0 +1,137 @@ +[ + { + "Start Time": "2025-04-10T19:43:56.756258", + "End Time": "2025-04-10T19:44:16.830570", + "License Plate": [ + "5691EX3" + ] + }, + { + "Start Time": "2025-04-10T19:44:16.830570", + "End Time": "2025-04-10T19:44:36.902341", + "License Plate": [ + "5691EX3" + ] + }, + { + "Start Time": "2025-04-10T19:44:36.902341", + "End Time": "2025-04-10T19:44:56.978730", + "License Plate": [ + "9121CX7", + "E9121CX7", + "\u76969121CX7" + ] + }, + { + "Start Time": "2025-04-10T19:54:15.838565", + "End Time": "2025-04-10T19:54:35.847936", + "License Plate": [ + "56918X3", + "\u76965691EK3", + "\u76965591EX3", + "9", + "5691EX", + "\u76965691EX3", + "5691EX3", + "5691X3", + "691EX3", + "5591EX3", + "569EX3" + ] + }, + { + "Start Time": "2025-04-11T00:42:20.435220", + "End Time": "2025-04-11T00:42:40.481205", + "License Plate": [ + "9", + "5591EX3", + "5691EX3", + "\u76965691EK3", + "691EX3", + "569EX3", + "\u76965591EX3", + "5691X3", + "56918X3", + "5691EX", + "\u76965691EX3" + ] + }, + { + "Start Time": "2025-04-11T00:47:58.727056", + "End Time": "2025-04-11T00:48:18.912928", + "License Plate": [ + "5691EX", + "569EX3", + "\u76965691EX3", + "5691X3", + "5691EX3", + "5591EX3", + "56918X3", + "\u76965691EK3", + "\u76965591EX3", + "9", + "691EX3" + ] + }, + { + "Start Time": "2025-04-11T00:48:18.912928", + "End Time": "2025-04-11T00:48:39.154114", + "License Plate": [ + "5691EX", + "\u4e2d", + "\u76965691EX3", + "5691EX3", + "5601EX3", + "9", + "5691EX1", + "\u6d595691EX3" + ] + }, + { + "Start Time": "2025-04-11T00:51:08.175327", + "End Time": "2025-04-11T00:51:28.214272", + "License Plate": [ + "9", + "\u76965691EK3", + "5691X3", + "\u76965591EX3", + "56918X3", + "5691EX3", + "569EX3", + "5591EX3", + "5691EX", + "\u76965691EX3", + "691EX3" + ] + }, + { + "Start Time": "2025-04-11T00:51:28.214272", + "End Time": "2025-04-11T00:51:48.479129", + "License Plate": [ + "9", + "5691EX1", + "5691EX3", + "5601EX3", + "\u6d595691EX3", + "\u4e2d", + "5691EX", + "\u76965691EX3" + ] + }, + { + "Start Time": "2025-04-11T00:51:48.479129", + "End Time": "2025-04-11T00:52:08.692791", + "License Plate": [ + "\u8d635691EX3", + "\u76965691EX3", + "5691EX3" + ] + }, + { + "Start Time": "2025-04-11T00:52:08.692791", + "End Time": "2025-04-11T00:52:28.960917", + "License Plate": [ + "5691EX3" + ] + } +] \ No newline at end of file diff --git a/app/api/json/output_20250410191650.json b/app/api/json/output_20250410191650.json new file mode 100644 index 0000000..081ff39 --- /dev/null +++ b/app/api/json/output_20250410191650.json @@ -0,0 +1,7 @@ +{ + "Start Time": "2025-04-10T19:16:30.019158", + "End Time": "2025-04-10T19:16:50.112310", + "License Plate": [ + "5691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250410194416.json b/app/api/json/output_20250410194416.json new file mode 100644 index 0000000..3783045 --- /dev/null +++ b/app/api/json/output_20250410194416.json @@ -0,0 +1,7 @@ +{ + "Start Time": "2025-04-10T19:43:56.756258", + "End Time": "2025-04-10T19:44:16.830570", + "License Plate": [ + "5691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250410194436.json b/app/api/json/output_20250410194436.json new file mode 100644 index 0000000..6ffa06e --- /dev/null +++ b/app/api/json/output_20250410194436.json @@ -0,0 +1,7 @@ +{ + "Start Time": "2025-04-10T19:44:16.830570", + "End Time": "2025-04-10T19:44:36.902341", + "License Plate": [ + "5691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250410194457.json b/app/api/json/output_20250410194457.json new file mode 100644 index 0000000..403e7c4 --- /dev/null +++ b/app/api/json/output_20250410194457.json @@ -0,0 +1,9 @@ +{ + "Start Time": "2025-04-10T19:44:36.902341", + "End Time": "2025-04-10T19:44:56.978730", + "License Plate": [ + "9121CX7", + "E9121CX7", + "\u76969121CX7" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250410195436.json b/app/api/json/output_20250410195436.json new file mode 100644 index 0000000..f4ea997 --- /dev/null +++ b/app/api/json/output_20250410195436.json @@ -0,0 +1,17 @@ +{ + "Start Time": "2025-04-10T19:54:15.838565", + "End Time": "2025-04-10T19:54:35.847936", + "License Plate": [ + "56918X3", + "\u76965691EK3", + "\u76965591EX3", + "9", + "5691EX", + "\u76965691EX3", + "5691EX3", + "5691X3", + "691EX3", + "5591EX3", + "569EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250411004240.json b/app/api/json/output_20250411004240.json new file mode 100644 index 0000000..f444883 --- /dev/null +++ b/app/api/json/output_20250411004240.json @@ -0,0 +1,17 @@ +{ + "Start Time": "2025-04-11T00:42:20.435220", + "End Time": "2025-04-11T00:42:40.481205", + "License Plate": [ + "9", + "5591EX3", + "5691EX3", + "\u76965691EK3", + "691EX3", + "569EX3", + "\u76965591EX3", + "5691X3", + "56918X3", + "5691EX", + "\u76965691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250411004819.json b/app/api/json/output_20250411004819.json new file mode 100644 index 0000000..a816114 --- /dev/null +++ b/app/api/json/output_20250411004819.json @@ -0,0 +1,17 @@ +{ + "Start Time": "2025-04-11T00:47:58.727056", + "End Time": "2025-04-11T00:48:18.912928", + "License Plate": [ + "5691EX", + "569EX3", + "\u76965691EX3", + "5691X3", + "5691EX3", + "5591EX3", + "56918X3", + "\u76965691EK3", + "\u76965591EX3", + "9", + "691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250411004839.json b/app/api/json/output_20250411004839.json new file mode 100644 index 0000000..a4c8c88 --- /dev/null +++ b/app/api/json/output_20250411004839.json @@ -0,0 +1,14 @@ +{ + "Start Time": "2025-04-11T00:48:18.912928", + "End Time": "2025-04-11T00:48:39.154114", + "License Plate": [ + "5691EX", + "\u4e2d", + "\u76965691EX3", + "5691EX3", + "5601EX3", + "9", + "5691EX1", + "\u6d595691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250411005128.json b/app/api/json/output_20250411005128.json new file mode 100644 index 0000000..84229ff --- /dev/null +++ b/app/api/json/output_20250411005128.json @@ -0,0 +1,17 @@ +{ + "Start Time": "2025-04-11T00:51:08.175327", + "End Time": "2025-04-11T00:51:28.214272", + "License Plate": [ + "9", + "\u76965691EK3", + "5691X3", + "\u76965591EX3", + "56918X3", + "5691EX3", + "569EX3", + "5591EX3", + "5691EX", + "\u76965691EX3", + "691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250411005148.json b/app/api/json/output_20250411005148.json new file mode 100644 index 0000000..98155ce --- /dev/null +++ b/app/api/json/output_20250411005148.json @@ -0,0 +1,14 @@ +{ + "Start Time": "2025-04-11T00:51:28.214272", + "End Time": "2025-04-11T00:51:48.479129", + "License Plate": [ + "9", + "5691EX1", + "5691EX3", + "5601EX3", + "\u6d595691EX3", + "\u4e2d", + "5691EX", + "\u76965691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250411005208.json b/app/api/json/output_20250411005208.json new file mode 100644 index 0000000..b6e3d41 --- /dev/null +++ b/app/api/json/output_20250411005208.json @@ -0,0 +1,9 @@ +{ + "Start Time": "2025-04-11T00:51:48.479129", + "End Time": "2025-04-11T00:52:08.692791", + "License Plate": [ + "\u8d635691EX3", + "\u76965691EX3", + "5691EX3" + ] +} \ No newline at end of file diff --git a/app/api/json/output_20250411005229.json b/app/api/json/output_20250411005229.json new file mode 100644 index 0000000..842e917 --- /dev/null +++ b/app/api/json/output_20250411005229.json @@ -0,0 +1,7 @@ +{ + "Start Time": "2025-04-11T00:52:08.692791", + "End Time": "2025-04-11T00:52:28.960917", + "License Plate": [ + "5691EX3" + ] +} \ No newline at end of file diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..3627e11 --- /dev/null +++ b/app/api/v1/__init__.py @@ -0,0 +1 @@ +# from .endpoints.streaming import router as stream_router \ No newline at end of file diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/endpoints/streaming.py b/app/api/v1/endpoints/streaming.py new file mode 100644 index 0000000..03c2310 --- /dev/null +++ b/app/api/v1/endpoints/streaming.py @@ -0,0 +1,193 @@ +from fastapi import APIRouter, WebSocket, WebSocketDisconnect +from fastapi.responses import HTMLResponse +import cv2 +import asyncio +import base64 +from services.ml.stream import stream, rstp_url + +router = APIRouter(prefix="/app/v1", tags=["streaming"]) + +@router.get("/stream", response_class=HTMLResponse) +async def streaming(): + html_content = """ + + + + Car Plate Detection + + + +
+

Система контроля доступа

+ Video Feed +
+
Ожидание номера...
+
Ожидание...
+
+
+ + + + """ + return HTMLResponse(content=html_content) + +@router.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + cap = cv2.VideoCapture(rstp_url) + + if not cap.isOpened(): + await websocket.send_json({ + "frame": "", + "status": "ОШИБКА КАМЕРЫ", + "plate_number": "" + }) + await websocket.close() + return + + try: + while True: + ret, frame = cap.read() + if not ret: + cap.set(cv2.CAP_PROP_POS_FRAMES, 0) + continue + + # Обработка кадра и получение статуса и номера + status, plate_number = stream(frame) + + # Кодирование кадра в JPEG + _, buffer = cv2.imencode(".jpg", frame) + frame_base64 = base64.b64encode(buffer).decode("utf-8") + + # Отправка кадра, статуса и номера через WebSocket + await websocket.send_json({ + "frame": frame_base64, + "status": status, + "plate_number": plate_number + }) + + await asyncio.sleep(0.03) # ~30 FPS + + except WebSocketDisconnect: + print("Client disconnected") + except Exception as e: + print(f"Error in websocket: {e}") + try: + await websocket.send_json({ + "frame": "", + "status": "ОШИБКА СИСТЕМЫ", + "plate_number": "" + }) + except: + pass + finally: + cap.release() + await websocket.close() + diff --git a/app/config/dev.yaml b/app/config/dev.yaml new file mode 100644 index 0000000..d0007c3 --- /dev/null +++ b/app/config/dev.yaml @@ -0,0 +1,7 @@ +database: + postgres: + port: 5432 + dbName: "MyDBName" + hostname: "MyHostname" + user: "MyUser" + password: "MyPassword" \ No newline at end of file diff --git a/app/config/product.yaml b/app/config/product.yaml new file mode 100644 index 0000000..e69de29 diff --git a/app/images/1193769-hd_1920_1080_25fps.mp4 b/app/images/1193769-hd_1920_1080_25fps.mp4 new file mode 100644 index 0000000..a691899 Binary files /dev/null and b/app/images/1193769-hd_1920_1080_25fps.mp4 differ diff --git a/app/images/2034115-hd_1920_1080_30fps.mp4 b/app/images/2034115-hd_1920_1080_30fps.mp4 new file mode 100644 index 0000000..87f737f Binary files /dev/null and b/app/images/2034115-hd_1920_1080_30fps.mp4 differ diff --git a/app/images/2103099-uhd_3840_2160_30fps.mp4 b/app/images/2103099-uhd_3840_2160_30fps.mp4 new file mode 100644 index 0000000..1c574aa Binary files /dev/null and b/app/images/2103099-uhd_3840_2160_30fps.mp4 differ diff --git a/app/images/5cfb746e2b84a15e_jpg.rf.9bcc8b0dcaeea5802d0d91b27d56743b.jpg b/app/images/5cfb746e2b84a15e_jpg.rf.9bcc8b0dcaeea5802d0d91b27d56743b.jpg new file mode 100644 index 0000000..6c8b93b Binary files /dev/null and b/app/images/5cfb746e2b84a15e_jpg.rf.9bcc8b0dcaeea5802d0d91b27d56743b.jpg differ diff --git a/app/images/en_вывеска.jpg b/app/images/en_вывеска.jpg new file mode 100644 index 0000000..678f80b Binary files /dev/null and b/app/images/en_вывеска.jpg differ diff --git a/app/images/images.jpg b/app/images/images.jpg new file mode 100644 index 0000000..7be751d Binary files /dev/null and b/app/images/images.jpg differ diff --git a/app/images/korean_1.jpg b/app/images/korean_1.jpg new file mode 100644 index 0000000..f93de40 Binary files /dev/null and b/app/images/korean_1.jpg differ diff --git a/app/images/ru_plate1.png b/app/images/ru_plate1.png new file mode 100644 index 0000000..0c89fe6 Binary files /dev/null and b/app/images/ru_plate1.png differ diff --git a/app/images/ru_plate2.jpg b/app/images/ru_plate2.jpg new file mode 100644 index 0000000..856e045 Binary files /dev/null and b/app/images/ru_plate2.jpg differ diff --git a/app/images/ru_plate3.png b/app/images/ru_plate3.png new file mode 100644 index 0000000..cba3609 Binary files /dev/null and b/app/images/ru_plate3.png differ diff --git a/app/images/вывеска.jpg b/app/images/вывеска.jpg new file mode 100644 index 0000000..0f74af1 Binary files /dev/null and b/app/images/вывеска.jpg differ diff --git a/app/images/шлагбаум1.mkv b/app/images/шлагбаум1.mkv new file mode 100644 index 0000000..992bee5 Binary files /dev/null and b/app/images/шлагбаум1.mkv differ diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..0cc635b --- /dev/null +++ b/app/main.py @@ -0,0 +1,50 @@ +import json +import cv2 +# from ultralytics import YOLO +import numpy as np +import math +import re +import os +import sqlite3 +from datetime import datetime +# from api.v1.endpoints.streaming import streaming + +from api.v1.endpoints.streaming import router as stream_router +# from .api.v1.endpoints.streaming import router as steam_router - 'ээто работало + +# from paddleocr import PaddleOCR +import uvicorn +from typing import Union + +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +# from pydantic import BaseModel + +# class Item(BaseModel): +# name: str +# price: float +# is_offer: Union[bool, None] = None + + +app = FastAPI(title="Car Plate Detection API") + +# Configure CORS +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Подключаем маршруты +app.include_router(stream_router) + + +@app.get("/") +async def root(): + return {"message": "Welcome to the API"} + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/app/models/kpp/yolo11n 10 epochs/yolo11n_10epochs.onnx b/app/models/kpp/yolo11n 10 epochs/yolo11n_10epochs.onnx new file mode 100644 index 0000000..b003385 Binary files /dev/null and b/app/models/kpp/yolo11n 10 epochs/yolo11n_10epochs.onnx differ diff --git a/app/models/kpp/yolo11n 10 epochs/yolo11n_10epochs.pt b/app/models/kpp/yolo11n 10 epochs/yolo11n_10epochs.pt new file mode 100644 index 0000000..0a5664e Binary files /dev/null and b/app/models/kpp/yolo11n 10 epochs/yolo11n_10epochs.pt differ diff --git a/app/models/kpp/yolo11n 20 eposhs/best.pt b/app/models/kpp/yolo11n 20 eposhs/best.pt new file mode 100644 index 0000000..fc769a1 Binary files /dev/null and b/app/models/kpp/yolo11n 20 eposhs/best.pt differ diff --git a/app/models/kpp/yolo11s 10epochs/myyolo11s.pt b/app/models/kpp/yolo11s 10epochs/myyolo11s.pt new file mode 100644 index 0000000..fb35e39 Binary files /dev/null and b/app/models/kpp/yolo11s 10epochs/myyolo11s.pt differ diff --git a/app/models/kpp/yolo11s 10epochs/yolo11s.onnx b/app/models/kpp/yolo11s 10epochs/yolo11s.onnx new file mode 100644 index 0000000..ef77862 Binary files /dev/null and b/app/models/kpp/yolo11s 10epochs/yolo11s.onnx differ diff --git a/app/models/paddle/en_PP-OCRv3_rec.onnx b/app/models/paddle/en_PP-OCRv3_rec.onnx new file mode 100644 index 0000000..45956f4 Binary files /dev/null and b/app/models/paddle/en_PP-OCRv3_rec.onnx differ diff --git a/app/models/plate/best.pt b/app/models/plate/best.pt new file mode 100644 index 0000000..3b58670 Binary files /dev/null and b/app/models/plate/best.pt differ diff --git a/app/original_plate.jpg b/app/original_plate.jpg new file mode 100644 index 0000000..7e22be7 Binary files /dev/null and b/app/original_plate.jpg differ diff --git a/app/preprocessed_plate.jpg b/app/preprocessed_plate.jpg new file mode 100644 index 0000000..3d89623 Binary files /dev/null and b/app/preprocessed_plate.jpg differ diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000..ab3b695 --- /dev/null +++ b/app/services/__init__.py @@ -0,0 +1,2 @@ +# from .database.database import findCar +# from .ml.stream import stream \ No newline at end of file diff --git a/app/services/database.py b/app/services/database.py new file mode 100644 index 0000000..5fc84d2 --- /dev/null +++ b/app/services/database.py @@ -0,0 +1,118 @@ +# import psycopg2 +# from psycopg2.extras import DictCursor +# import os +# from dotenv import load_dotenv + +# load_dotenv() + +# class Database: +# def __init__(self): +# self.connection_params = { +# 'dbname': os.getenv('DB_NAME', 'kpp_db'), +# 'user': os.getenv('DB_USER', 'postgres'), +# 'password': os.getenv('DB_PASSWORD', ''), +# 'host': os.getenv('DB_HOST', 'localhost'), +# 'port': os.getenv('DB_PORT', '5432') +# } + +# def test_connection(self): +# """Проверка подключения к базе данных""" +# try: +# with self.get_connection() as conn: +# with conn.cursor() as cur: +# # Проверяем существование таблицы +# cur.execute(""" +# SELECT EXISTS ( +# SELECT FROM information_schema.tables +# WHERE table_name = 'license_plates' +# ); +# """) +# table_exists = cur.fetchone()[0] + +# # Проверяем количество записей +# if table_exists: +# cur.execute("SELECT COUNT(*) FROM license_plates;") +# record_count = cur.fetchone()[0] +# return True, f"Подключение успешно. Записей в базе: {record_count}" +# else: +# return True, "Подключение успешно. Таблица 'license_plates' не существует." + +# except Exception as e: +# return False, f"Ошибка подключения: {str(e)}" + +# def get_connection(self): +# return psycopg2.connect(**self.connection_params) + +# def findCar(self, plate_number: str) -> bool: +# try: +# with self.get_connection() as conn: +# with conn.cursor(cursor_factory=DictCursor) as cur: +# cur.execute( +# "SELECT EXISTS(SELECT 1 FROM license_plates WHERE plate_number = %s AND is_active = true)", +# (plate_number,) +# ) +# return cur.fetchone()[0] +# except Exception as e: +# print(f"Database error in findCar: {e}") +# return False + +# def add_car(self, plate_number: str, owner_name: str = None) -> bool: +# try: +# with self.get_connection() as conn: +# with conn.cursor() as cur: +# cur.execute( +# """ +# INSERT INTO license_plates (plate_number, owner_name, is_active) +# VALUES (%s, %s, true) +# ON CONFLICT (plate_number) +# DO UPDATE SET is_active = true, owner_name = EXCLUDED.owner_name +# """, +# (plate_number, owner_name) +# ) +# conn.commit() +# return True +# except Exception as e: +# print(f"Database error in add_car: {e}") +# return False + +# def remove_car(self, plate_number: str) -> bool: +# try: +# with self.get_connection() as conn: +# with conn.cursor() as cur: +# cur.execute( +# "UPDATE license_plates SET is_active = false WHERE plate_number = %s", +# (plate_number,) +# ) +# conn.commit() +# return True +# except Exception as e: +# print(f"Database error in remove_car: {e}") +# return False + +# def init_db(self): +# """Initialize database tables if they don't exist""" +# try: +# with self.get_connection() as conn: +# with conn.cursor() as cur: +# cur.execute(""" +# CREATE TABLE IF NOT EXISTS license_plates ( +# plate_number VARCHAR(20) PRIMARY KEY, +# owner_name VARCHAR(100), +# is_active BOOLEAN DEFAULT true, +# created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, +# updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +# ) +# """) +# conn.commit() +# print("База данных успешно инициализирована") +# except Exception as e: +# print(f"Ошибка инициализации базы данных: {e}") + +# database = Database() + +# # Проверяем подключение при импорте модуля +# success, message = database.test_connection() +# print(f"Проверка базы данных: {message}") + +# if success: +# database.init_db() # Инициализируем таблицы только если подключение успешно \ No newline at end of file diff --git a/app/services/database/__init__.py b/app/services/database/__init__.py new file mode 100644 index 0000000..b810d8f --- /dev/null +++ b/app/services/database/__init__.py @@ -0,0 +1 @@ +# from .database import findCar \ No newline at end of file diff --git a/app/services/database/database.py b/app/services/database/database.py new file mode 100644 index 0000000..54ceb10 --- /dev/null +++ b/app/services/database/database.py @@ -0,0 +1,160 @@ +import psycopg2 +from psycopg2.extras import DictCursor +import os +from dotenv import load_dotenv + +load_dotenv() + +class Database: + def __init__(self): + self.connection_params = { + 'dbname': os.getenv('DB_NAME', 'kpp_db'), + 'user': os.getenv('DB_USER', 'postgres'), + 'password': os.getenv('DB_PASSWORD', ''), + 'host': os.getenv('DB_HOST', 'localhost'), + 'port': os.getenv('DB_PORT', '5432') + } + + def test_connection(self): + """Проверка подключения к базе данных""" + try: + with self.get_connection() as conn: + with conn.cursor() as cur: + # Проверяем существование таблицы + cur.execute(""" + SELECT EXISTS ( + SELECT FROM information_schema.tables + WHERE table_name = 'license_plates' + ); + """) + table_exists = cur.fetchone()[0] + + # Проверяем количество записей + if table_exists: + cur.execute("SELECT COUNT(*) FROM license_plates;") + record_count = cur.fetchone()[0] + return True, f"Подключение успешно. Записей в базе: {record_count}" + else: + return True, "Подключение успешно. Таблица 'license_plates' не существует." + + except Exception as e: + return False, f"Ошибка подключения: {str(e)}" + + def get_connection(self): + return psycopg2.connect(**self.connection_params) + + def findCar(self, plate_number: str) -> bool: + try: + with self.get_connection() as conn: + with conn.cursor(cursor_factory=DictCursor) as cur: + cur.execute( + "SELECT EXISTS(SELECT 1 FROM license_plates WHERE plate_number = %s AND is_active = true)", + (plate_number,) + ) + return cur.fetchone()[0] + except Exception as e: + print(f"Database error in findCar: {e}") + return False + + def add_car(self, plate_number: str, owner_name: str = None) -> bool: + try: + with self.get_connection() as conn: + with conn.cursor() as cur: + cur.execute( + """ + INSERT INTO license_plates (plate_number, owner_name, is_active) + VALUES (%s, %s, true) + ON CONFLICT (plate_number) + DO UPDATE SET is_active = true, owner_name = EXCLUDED.owner_name + """, + (plate_number, owner_name) + ) + conn.commit() + return True + except Exception as e: + print(f"Database error in add_car: {e}") + return False + + def remove_car(self, plate_number: str) -> bool: + try: + with self.get_connection() as conn: + with conn.cursor() as cur: + cur.execute( + "UPDATE license_plates SET is_active = false WHERE plate_number = %s", + (plate_number,) + ) + conn.commit() + return True + except Exception as e: + print(f"Database error in remove_car: {e}") + return False + + def init_db(self): + """Initialize database tables if they don't exist""" + try: + with self.get_connection() as conn: + with conn.cursor() as cur: + cur.execute(""" + CREATE TABLE IF NOT EXISTS license_plates ( + plate_number VARCHAR(20) PRIMARY KEY, + owner_name VARCHAR(100), + is_active BOOLEAN DEFAULT true, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + conn.commit() + print("База данных успешно инициализирована") + except Exception as e: + print(f"Ошибка инициализации базы данных: {e}") + +database = Database() + +# Проверяем подключение при импорте модуля +success, message = database.test_connection() +print(f"Проверка базы данных: {message}") + +if success: + database.init_db() # Инициализируем таблицы только если подключение успешно + + + + +# import psycopg2 + +# connection = None + +# try: +# connection = psycopg2.connect( +# dbname="car", +# user="postgres", +# password="qwerty12Q!", +# host="localhost", +# port="5432" +# ) +# cursor = connection.cursor() + +# except: +# print("Ошибка подключения") + + +# if connection == False: +# print("Соединение не установлено") + +# def addLicensePlate(plate): + +# cursor.execute("INSERT INTO cars plate VALUES %s", plate) + + + +# def findCar(plate_number): + +# # query = "SELECT EXISTS(SELECT * FROM cars WHERE plate = %s)" +# query = "SELECT * FROM cars WHERE plate = %s" +# cursor.execute(query, (plate_number)) +# exists = cursor.fetchone()[0] + +# cursor.close() +# connection.close() + +# return exists diff --git a/app/services/ml/__init__.py b/app/services/ml/__init__.py new file mode 100644 index 0000000..881bb70 --- /dev/null +++ b/app/services/ml/__init__.py @@ -0,0 +1 @@ +# from .stream import stream \ No newline at end of file diff --git a/app/services/ml/stream.py b/app/services/ml/stream.py new file mode 100644 index 0000000..ed05ad9 --- /dev/null +++ b/app/services/ml/stream.py @@ -0,0 +1,464 @@ +import json +import cv2 +from ultralytics import YOLO +import numpy as np +import math +import re +import os +import sqlite3 +from datetime import datetime +from paddleocr import PaddleOCR +from ..database.database import database + + + + +os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" +rstp_url = "C:/kpp/app/images/шлагбаум1.mkv" + +#Create a Video Capture Object +cap = cv2.VideoCapture(rstp_url) +#Initialize the YOLOv10 Model +model = YOLO("C:/kpp/app/models/kpp/yolo11s 10epochs/myyolo11s.pt") + +#Initialize the frame count +count = 0 +#Class Names +className = ["car","plate"] +#Initialize the Paddle OCR with optimized settings +ocr = PaddleOCR(use_angle_cls=True, lang='en', det=True, rec=True, cls=False, use_gpu=False) +# ocr = PaddleOCR( +# use_angle_cls=True, +# lang='en', +# det=True, +# rec=True, +# cls=False, +# use_gpu=False, +# show_log=False, +# rec_algorithm='SVTR_LCNet', +# rec_batch_num=1, +# det_db_thresh=0.3, +# det_db_box_thresh=0.5, +# det_db_unclip_ratio=1.6, +# max_batch_size=10, +# use_mp=True, +# total_process_num=2, +# check_point=False +# ) + +def preprocess_plate_image(plate_img): + try: + # Изменение размера (увеличение для лучшего распознавания) + height = plate_img.shape[0] + target_height = 100 # Уменьшаем высоту для лучшего распознавания + scale = target_height / height + width = int(plate_img.shape[1] * scale) + dim = (width, target_height) + resized = cv2.resize(plate_img, dim, interpolation=cv2.INTER_CUBIC) + + # Преобразование в оттенки серого + gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) + + # Нормализация гистограммы + clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) + normalized = clahe.apply(gray) + + # Увеличение контраста + alpha = 1.3 # Уменьшаем контраст + beta = 30 # Увеличиваем яркость + contrast = cv2.convertScaleAbs(normalized, alpha=alpha, beta=beta) + + # Размытие для уменьшения шума + blurred = cv2.GaussianBlur(contrast, (3, 3), 0) + + # Адаптивная бинаризация + binary = cv2.adaptiveThreshold( + blurred, + 255, + cv2.ADAPTIVE_THRESH_GAUSSIAN_C, + cv2.THRESH_BINARY, + 15, # Уменьшаем размер окна + 5 # Уменьшаем константу + ) + + # Морфологические операции + kernel = np.ones((2,2), np.uint8) + binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel) + + # Добавляем белые поля + padding = 10 + padded = cv2.copyMakeBorder( + binary, + padding, padding, padding, padding, + cv2.BORDER_CONSTANT, + value=255 + ) + + # Сохраняем промежуточный результат для отладки + cv2.imwrite('preprocessed_plate.jpg', padded) + + return padded + + except Exception as e: + print(f"❌ Ошибка предобработки: {e}") + return plate_img + +def clean_plate_text(text): + if not text: + return "" + + # Удаление специальных символов и пробелов + text = re.sub(r'[^A-Za-z0-9А-Яа-я]', '', text) + + # Замена похожих символов (русские на английские и наоборот) + replacements = { + # 'O': '0', + # 'I': '1', + # 'L': '1', + # 'Z': '2', + # 'S': '5', + # 'B': '8', + # 'D': '0', + # 'G': '6', + # # Русские буквы на английские + # 'А': 'A', + # 'В': 'B', + # 'Е': 'E', + # 'К': 'K', + # 'М': 'M', + # 'Н': 'H', + # 'О': 'O', + # 'Р': 'P', + # 'С': 'C', + # 'Т': 'T', + # 'У': 'Y', + # 'Х': 'X', + # # Нижний регистр + # 'a': 'A', + # 'b': 'B', + # 'c': 'C', + # 'd': 'D', + # 'e': 'E', + # 'h': 'H', + # 'k': 'K', + # 'm': 'M', + # 'o': 'O', + # 'p': 'P', + # 't': 'T', + # 'x': 'X', + # 'y': 'Y', + # Удаление специфических символов + '粤': '', + 'u7696': '', + '|': '', + '/': '', + '\\': '', + '_': '', + '-': '', + '.': '', + ' ': '' + } + + # Применяем замены + for old, new in replacements.items(): + text = text.replace(old, new) + + # Приводим к верхнему регистру + text = text.upper() + + # Удаляем все символы кроме букв и цифр + text = re.sub(r'[^A-Z0-9]', '', text) + + # Удаляем повторяющиеся символы (например, '11' -> '1') + text = re.sub(r'(.)\1+', r'\1', text) + + # Проверяем длину и структуру номера + if len(text) >= 3: + # Если номер начинается с буквы, за которой следуют только цифры + if re.match(r'^[A-Z][0-9]+$', text): + return text + # Если номер начинается с цифр, за которыми следуют буквы + elif re.match(r'^[0-9]+[A-Z]+$', text): + return text + # Если номер имеет смешанную структуру (буквы и цифры) + elif re.match(r'^[A-Z0-9]{3,}$', text): + return text + + # Если текст не соответствует ожидаемой структуре, возвращаем пустую строку + return "" + +def paddle_ocr(frame, x1, y1, x2, y2): + try: + # Вырезаем область с номером с дополнительным отступом + height = y2 - y1 + width = x2 - x1 + y1_pad = max(0, y1 - int(height)) + y2_pad = min(frame.shape[0], y2 + int(height)) + x1_pad = max(0, x1 - int(width )) + x2_pad = min(frame.shape[1], x2 + int(width )) + + plate_region = frame[y1_pad:y2_pad, x1_pad:x2_pad] + + # Сохраняем оригинальное изображение для отладки + cv2.imwrite('original_plate.jpg', plate_region) + + # Предварительная обработка изображения + processed_img = preprocess_plate_image(plate_region) + + # Распознавание текста + results = ocr.ocr(processed_img, det=True, rec=True, cls=False) + + print(f"OCR результаты: {results}") + + if not results or not results[0]: + print("❌ Текст не обнаружен") + return "", 0 + + # Собираем все распознанные тексты и их уверенности + texts = [] + confidences = [] + + for line in results[0]: # Берем первый результат из списка + if line: + # В новом формате PaddleOCR возвращает [points, (text, confidence)] + text = line[1][0] # Получаем текст + conf = float(line[1][1]) # Получаем уверенность + + print(f"Найден текст: {text}") + print(f"Уверенность: {conf*100:.1f}%") + + # Очистка и нормализация текста + cleaned_text = clean_plate_text(text) + print(f"Очищенный текст: {cleaned_text}") + + if cleaned_text: + texts.append(cleaned_text) + confidences.append(conf) + print("✅ Текст принят") + else: + print("❌ Текст отклонен (слишком короткий или пустой)") + + if not texts: + print("❌ Нет подходящих вариантов текста") + return "", 0 + + # Выбираем текст с наивысшей уверенностью + best_idx = np.argmax(confidences) + best_text = texts[best_idx] + best_conf = confidences[best_idx] + + print(f"✅ Лучший вариант: {best_text} ({best_conf*100:.1f}%)") + return best_text, best_conf + + except Exception as e: + print(f"❌ Ошибка OCR: {str(e)}") + print(f"Тип ошибки: {type(e).__name__}") + return "", 0 + + + +def save_json(license_plates, startTime, endTime): + #Generate individual JSON files for each 20-second interval + interval_data = { + "Start Time": startTime.isoformat(), + "End Time": endTime.isoformat(), + "License Plate": list(license_plates) + } + interval_file_path = "../../api/json/output_" + datetime.now().strftime("%Y%m%d%H%M%S") + ".json" + with open(interval_file_path, 'w') as f: + json.dump(interval_data, f, indent = 2) + + #Cummulative JSON File + cummulative_file_path = "json/LicensePlateData.json" + if os.path.exists(cummulative_file_path): + with open(cummulative_file_path, 'r') as f: + existing_data = json.load(f) + else: + existing_data = [] + + #Add new intervaal data to cummulative data + existing_data.append(interval_data) + + with open(cummulative_file_path, 'w') as f: + json.dump(existing_data, f, indent = 2) + + #Save data to SQL database + # save_to_database(license_plates, startTime, endTime) + + + +# def save_to_database(license_plates, start_time, end_time): +# conn = sqlite3.connect('licensePlatesDatabase.db') +# cursor = conn.cursor() +# for plate in license_plates: +# cursor.execute(''' +# INSERT INTO LicensePlates(start_time, end_time, license_plate) +# VALUES (?, ?, ?) +# ''', (start_time.isoformat(), end_time.isoformat(), plate)) +# conn.commit() +# conn.close() + + + + +def stream(frame): + try: + status = "НЕТ В СПИСКЕ" + plate_text = "" + + results = model.predict(frame, conf=0.30) # Снижаем порог детекции + + for result in results: + boxes = result.boxes + for box in boxes: + x1, y1, x2, y2 = box.xyxy[0] + x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) + classNameInt = int(box.cls[0]) + conf = math.ceil(box.conf[0] * 100) / 100 + + if className[classNameInt] == "plate" and conf >= 0.30: + print("\n" + "="*70) + print(f"🚗 ОБНАРУЖЕН НОМЕРНОЙ ЗНАК (уверенность детекции: {conf*100:.1f}%)") + + # Сохраняем оригинальные координаты для отрисовки + orig_box = (x1, y1, x2, y2) + + # Увеличиваем область для OCR + height = y2 - y1 + width = x2 - x1 + + # Расширяем область для OCR на 20% + ocr_x1 = max(0, x1 - int(width)) + ocr_y1 = max(0, y1 - int(height)) + ocr_x2 = min(frame.shape[1], x2 + int(width)) + ocr_y2 = min(frame.shape[0], y2 + int(height)) + + # Рисуем рамку по оригинальным координатам + cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) + + # Распознаем текст номера с расширенной областью + text, ocr_confidence = paddle_ocr(frame, ocr_x1, ocr_y1, ocr_x2, ocr_y2) + + print(f"Распознанный текст: {text}") + print(f"Уверенность OCR: {ocr_confidence*100:.1f}%") + + if text and ocr_confidence >= 0.60: + plate_text = text + try: + permission = database.findCar(text) + status = "ПРОЕЗД РАЗРЕШЕН" if permission else "НЕТ В СПИСКЕ" + print(f"Статус: {status}") + + # Настраиваем отображение + text_color = (0, 255, 0) if permission else (0, 0, 255) + font = cv2.FONT_HERSHEY_SIMPLEX + font_scale = 0.7 + thickness = 2 + + # Текст номера над рамкой + plate_label = f"{text} ({int(ocr_confidence * 100)}%)" + text_size = cv2.getTextSize(plate_label, font, font_scale, thickness)[0] + + # Фон для текста номера + cv2.rectangle(frame, + (x1, y1 - text_size[1] - 10), + (x1 + text_size[0], y1), + text_color, -1) + + # Текст номера + cv2.putText(frame, plate_label, + (x1, y1 - 5), + font, font_scale, (255, 255, 255), + thickness, cv2.LINE_AA) + + # Статус под рамкой + status_size = cv2.getTextSize(status, font, font_scale, thickness)[0] + + # Фон для статуса + cv2.rectangle(frame, + (x1, y2), + (x1 + status_size[0], y2 + status_size[1] + 10), + text_color, -1) + + # Текст статуса + cv2.putText(frame, status, + (x1, y2 + status_size[1] + 5), + font, font_scale, (255, 255, 255), + thickness, cv2.LINE_AA) + + except Exception as e: + print(f"❌ Ошибка базы данных: {str(e)}") + status = "ОШИБКА ПРОВЕРКИ" + else: + print("❌ Текст не распознан или низкая уверенность") + + elif className[classNameInt] == "car": + # Рисуем рамку вокруг машины зеленым цветом + cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) + + return status, plate_text + except Exception as e: + print(f"❌ Ошибка обработки: {str(e)}") + return "ОШИБКА ОБРАБОТКИ", "" + + + + +# def stream(frame): + +# startTime = datetime.now() +# license_plates = set() + +# while True: + +# ret, frame = cap.read() + +# if ret: +# currentTime = datetime.now() +# count += 1 +# print(f"Frame Number: {count}") +# results = model.predict(frame, conf = 0.45) + +# for result in results: +# boxes = result.boxes +# for box in boxes: +# x1, y1, x2, y2 = box.xyxy[0] +# x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) +# cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) +# classNameInt = int(box.cls[0]) +# clsName = className[classNameInt] +# conf = math.ceil(box.conf[0]*100)/100 +# #label = f'{clsName}:{conf}' +# label = paddle_ocr(frame, x1, y1, x2, y2) +# if label: +# license_plates.add(label) +# textSize = cv2.getTextSize(label, 0, fontScale=0.5, thickness=2)[0] +# c2 = x1 + textSize[0], y1 - textSize[1] - 3 +# cv2.rectangle(frame, (x1, y1), c2, (255, 0, 0), -1) +# cv2.putText(frame, label, (x1, y1 - 2), 0, 0.5, [255,255,255], thickness=1, lineType=cv2.LINE_AA) + +# if conf >= 70: +# permistion = database.findCar(label) +# if permistion == True: + +# text = "ПРОЕЗД РАЗРЕШЕН" +# return text +# else: + +# text = "НЕТ В СПИСКЕ" +# return text + +# if (currentTime - startTime).seconds >= 20: +# endTime = currentTime +# save_json(license_plates, startTime, endTime) +# startTime = currentTime +# license_plates.clear() + +# cv2.imshow("Video", frame) +# if cv2.waitKey(1) & 0xFF == ord('1'): +# break +# else: +# break + +# cap.release() +# cv2.destroyAllWindows() \ No newline at end of file diff --git a/app/test_db.py b/app/test_db.py new file mode 100644 index 0000000..a5520ea --- /dev/null +++ b/app/test_db.py @@ -0,0 +1,36 @@ +from services.database.database import database # Исправленный путь импорта + +def test_database(): + print("\n=== Тестирование базы данных ===") + + # Проверка подключения + success, message = database.test_connection() + print(f"\n1. Проверка подключения:") + print(f"Результат: {message}") + + if success: + # Тестовые данные + test_plates = [ + ("A123BC", "Test Owner 1"), + ("B456CD", "Test Owner 2"), + ("C789EF", "Test Owner 3") + ] + + print("\n2. Добавление тестовых номеров:") + for plate, owner in test_plates: + if database.add_car(plate, owner): + print(f"Номер {plate} успешно добавлен") + else: + print(f"Ошибка при добавлении номера {plate}") + + print("\n3. Проверка наличия номеров:") + for plate, _ in test_plates: + if database.findCar(plate): + print(f"Номер {plate} найден в базе") + else: + print(f"Номер {plate} не найден в базе") + + print("\n=== Тестирование завершено ===\n") + +if __name__ == "__main__": + test_database() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ea27dbd --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +fastapi==0.104.1 +uvicorn==0.24.0 +opencv-python==4.8.1.78 +numpy==1.26.2 +ultralytics==8.0.208 +paddlepaddle==2.5.2 +paddleocr==2.7.0.3 +psycopg2-binary==2.9.9 +python-dotenv==1.0.0