kpp/app/ml/streaming.py

213 lines
6.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import av
import json
from ultralytics import YOLO
from paddleocr import PaddleOCR
import cv2
import numpy as np
import re
import os
from dotenv import load_dotenv
import requests
from data_models import Car, Plate, BaseData
import time
import redis
from urllib.parse import urlparse
load_dotenv()
redis_host = os.getenv('REDIS_HOST', 'localhost')
redis_port = int(os.getenv('REDIS_PORT', '6379'))
redis_con = redis.Redis(
host=redis_host,
port=redis_port,
decode_responses=True
)
rstp_url= os.getenv('RTSP_URL')
#лучший вариант kpp\app\ml\models\kpp\yolo11s 10epochs\myyolo11s.pt
yolo_model= os.getenv('YOLO_MODEL', r'C:\project\kpp\app\ml\models\kpp\yolo11n 20 eposhs\best.pt')
token= os.getenv('WEB_TOKEN')
ip_addr_web= os.getenv('WEB_IP_ADDR')
# Загрузка YOLO-модели
model = YOLO(yolo_model)
# Инициализация PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=False)
classNames = ["car", "plate"]
def clean_plate_text(text):
if not text:
return ""
text = re.sub(r'[^\w\s]', '', text)
allowed_chars = set('ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ0123456789')
text = ''.join(c for c in text.upper() if c in allowed_chars)
if len(text) < 4:
return ""
ru_pattern = r'^([A-ZА-Я])\s?([0-9]{3})\s?([A-ZА-Я]{2})\s?([0-9]{2,3})$'
general_pattern = r'^[A-ZА-Я0-9]{4,}$'
if re.match(ru_pattern, text) or re.match(general_pattern, 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]
if plate_region.size == 0:
print("❌ Пустая область номера")
return ""
results = ocr.ocr(plate_region, det=True, rec=True, cls=False)
if not results or not results[0]:
print("❌ Текст не обнаружен")
return ""
full_text = ""
for line in results[0]:
if line:
text = line[1][0]
conf = line[1][1]
print(f"Найден текст: {text} (уверенность: {conf*100:.1f}%)")
full_text += " " + text # Склеиваем все куски текста через пробел
full_text = full_text.strip()
print(f"📦 Собранный текст перед очисткой: {full_text}")
cleaned_text = clean_plate_text(full_text)
if cleaned_text:
print(f"✅ Очищенный текст: {cleaned_text}")
return cleaned_text
else:
print("❌ Текст отклонен после объединения")
return ""
except Exception as e:
print(f"❌ Ошибка OCR: {str(e)}")
return ""
def json_packer(type, data: BaseData):
try:
data = {
'type': type,
"coordinates" : [
data.x1,
data.y1
],
"width" : data.width,
"height" : data.height
}
return data
except Exception as e:
error_msg = f"Ошибка при формировании данных: {str(e)}"
print(f"\n❌ {error_msg}")
return {
"error": error_msg
}
def server_ping():
try:
url = f"http://{ip_addr_web}/start_recieve"
headers = {
'Authorization': f'',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers)
except Exception as e:
error_msg = f"Ошибка при формировании данных: {str(e)}"
print(f"\n❌ {error_msg}")
return {
"error": error_msg
}
def data_upload_redis(value, key='ai_recieve'):
try:
value = json.dumps(value)
print(value)
redis_con.lpush(key, value)
except Exception as e:
error_msg = f"Ошибка {str(e)}"
print(f"\n❌ {error_msg}")
return {
"error": error_msg
}
plate = Plate("", 0, 0, 0, 0)
car = Car(0,0,0,0)
container = av.open(
rstp_url, 'r',
options={
'rtsp_transport': 'tcp', # при udp теряются пакеты
'fflags': 'nobuffer', # отключаем буферизацию
'flags': 'low_delay', # оставшиеся настройки для снижения задержки
'stimeout': '100000',
'max_delay': '100000',
}
)
video = container.demux(video=0)
video_stream = next(s for s in container.streams if s.type == 'video')
server_ping()
for packet in container.demux(video_stream):
for frame in packet.decode():
if 'start_time' not in locals():
start_time = time.time()
start_read = frame.time
if (time.time()-start_time)-(frame.time-start_read)>.3:
continue # пропуск кадров при отставании от real time
pts = time.time()
img = frame.to_ndarray(format='bgr24')
results = model.predict(img)
data = {'pts': pts,
'content': {'content': []},
'plate_text': []}
for result in results:
for box in result.boxes:
x1, y1, x2, y2 = map(int,box.xyxy[0])
# выводит данные о классе 'plate'
if box.cls == 0 and box.conf >= 0.2:
text = paddle_ocr(img, x1, y1, x2, y2)
plate = Plate(text, x1, y1, x2, y2)
data['content']['content'].append(json_packer(int(box.cls), plate))
data['plate_text'].append(text)
# cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
# выводит данные о классе 'car'
elif box.cls == 1 and box.conf >= 0.50:
car = Car(x1, y1, x2, y2)
data['content']['content'].append(json_packer(int(box.cls), car))
# cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
data_upload_redis(data)
# cv2.imshow('frame', img)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# cv2.destroyAllWindows()
# container.close()
# break