resructured

This commit is contained in:
роман печеркин 2025-04-16 20:50:19 +07:00
parent 05ffea3e04
commit 652ff89124
32 changed files with 98 additions and 82 deletions

12
.env
View File

@ -1,7 +1,11 @@
DB_NAME=dbname
DB_USER=username
DB_PASSWORD=urpassword
DB_NAME=kpp_db
DB_USER=postgres
DB_PASSWORD=qwerty12Q!
DB_HOST=localhost
DB_PORT=5432
RTSP_URL=C:/kpp/app/images/шлагбаум1.mkv # путь к камере (пока что только видео)
RTSP_URL=C:/kpp/app/images/шлагбаум1.mkv # путь к камере (пока что только видео)
token=MyToken
ip_addr_web=MyIpAddr

View File

@ -173,7 +173,6 @@ async def websocket_endpoint(websocket: WebSocket):
"plate_number": plate_number
})
await asyncio.sleep(0.03) # ~30 FPS
except WebSocketDisconnect:
print("Client disconnected")

View File

@ -1,7 +0,0 @@
database:
postgres:
port: 5432
dbName: "MyDBName"
hostname: "MyHostname"
user: "MyUser"
password: "MyPassword"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 655 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

View File

@ -1,30 +1,12 @@
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")

View File

@ -5,12 +5,22 @@ import numpy as np
import math
import re
import os
import sqlite3
import requests
from datetime import datetime
from paddleocr import PaddleOCR
from dotenv import load_dotenv
load_dotenv()
token = os.getenv('token', 'MyToken')
ip_addr_web = os.getenv('ip_addr_web', 'MyAddr')
rstp_url = os.getenv("RTSP_URL", "C:/kpp/шлагбаум1.mkv")
# from services.database.database import database
# os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
rstp_url = "C:/kpp/app/images/шлагбаум1.mkv"
# Создаем объект видеозахвата
cap = cv2.VideoCapture(rstp_url)
@ -27,6 +37,8 @@ className = ["car", "plate"]
# Инициализируем PaddleOCR с оптимизированными параметрами
#Initialize the Paddle OCR
ocr = PaddleOCR(use_angle_cls = True, use_gpu = False)
#настройки для PaddleOCR
# ocr = PaddleOCR(
# use_angle_cls=True,
# lang='ch', # Используем 'ch' как базовый, но с кастомной моделью для мультиязычности
@ -113,11 +125,15 @@ def clean_plate_text(text):
allowed_chars = set('ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ0123456789')
text = ''.join(c for c in text.upper() if c in allowed_chars)
# Проверяем минимальную длину номера
if len(text) < 4:
return ""
# Проверяем типичные форматы номеров
# Российский формат: А123БВ456 или 123АБ456
ru_pattern = r'^[А-Я][0-9]{3}[А-Я]{2}[0-9]{2,3}$|^[0-9]{3}[А-Я]{2}[0-9]{2,3}$'
# Общий формат: минимум 3 символа букв и цифр
general_pattern = r'^[A-ZА-Я0-9]{3,}$'
# Общий формат: минимум 4 символа букв и цифр
general_pattern = r'^[A-ZА-Я0-9]{4,}$'
if re.match(ru_pattern, text) or re.match(general_pattern, text):
return text
@ -189,6 +205,62 @@ def paddle_ocr(frame, x1, y1, x2, y2):
print(f"❌ Ошибка OCR: {str(e)}")
return "", 0
def send_car_data(plate_text, x1, y1, x2, y2):
"""Отправка данных об автомобиле на сервер"""
try:
url = f"http://{ip_addr_web}/recieve_data_from_ai"
# Вычисляем ширину и высоту
width = x2 - x1
height = y2 - y1
# Формируем данные для отправки
data = {
"plate_number": plate_text,
"coordinates": [
x1, # Левая координата X
y1 # Верхняя координата Y
],
"width": width,
"height": height
}
payload = json.dumps(data)
headers = {
'Authorization': f'{token}',
'Content-Type': 'application/json'
}
print("\n=== Отправка данных на сервер ===")
print(f"URL: {url}")
print(f"Номер: {plate_text}")
print(f"Координаты: x={x1}, y={y1}")
print(f"Размеры: {width}x{height}")
print("================================")
response = requests.request("POST", url, headers=headers, data=payload)
print("\n=== Ответ сервера ===")
print(f"Статус: {response.status_code}")
print(f"Ответ: {response.text}")
print("====================")
return {
"sent_data": data,
"response": {
"status_code": response.status_code,
"text": response.text
}
}
except Exception as e:
error_msg = f"Ошибка при отправке данных: {str(e)}"
print(f"\n❌ {error_msg}")
return {
"error": error_msg
}
def save_json(license_plates, startTime, endTime):
interval_data = {
"Start Time": startTime.isoformat(),
@ -210,13 +282,11 @@ def save_json(license_plates, startTime, endTime):
json.dump(existing_data, f, indent=2, ensure_ascii=False)
def stream(frame):
try:
status = "НЕТ В СПИСКЕ"
plate_text = ""
results = model.predict(frame, conf=0.80) # Снижаем порог для лучшей детекции
results = model.predict(frame, conf=0.90)
for result in results:
boxes = result.boxes
@ -226,7 +296,7 @@ def stream(frame):
classNameInt = int(box.cls[0])
conf = math.ceil(box.conf[0] * 100) / 100
if className[classNameInt] == "plate" and conf >= 0.50:
if className[classNameInt] == "plate" and conf >= 0.90:
print("\n" + "="*70)
print(f"🚗 Номерной знак обнаружен (уверенность: {conf*100:.1f}%)")
@ -238,13 +308,18 @@ def stream(frame):
print(f"Распознанный текст: {text} ({ocr_confidence*100:.1f}%)")
if text and ocr_confidence >= 0.70: # Снижаем порог уверенности
if text and ocr_confidence >= 0.70:
plate_text = text
# Здесь должна быть проверка в базе данных
# permission = database.findCar(text)
permission = False # Заглушка
# permission = database.findCar(str(plate_text))
# TODO: реализовать проверку в базе данных
permission = False
status = "ПРОЕЗД РАЗРЕШЕН" if permission else "НЕТ В СПИСКЕ"
# Отправляем данные о номере и координатах
send_car_data(text, x1, y1, x2, y2)
text_color = (0, 255, 0) if permission else (0, 0, 255)
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.7
@ -278,6 +353,8 @@ def stream(frame):
elif className[classNameInt] == "car":
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
return status, plate_text
except Exception as e:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

View File

@ -1,2 +0,0 @@
# from .database.database import findCar
# from .ml.stream import stream

View File

@ -1 +0,0 @@
# from .database import findCar

View File

@ -1,36 +0,0 @@
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()