http заменен на redis
This commit is contained in:
parent
594074a0f2
commit
b1843f1d69
16
.env
16
.env
@ -1,12 +1,10 @@
|
||||
DB_NAME=kpp_db
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=qwerty12Q!
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
|
||||
RTSP_URL=rtsp://192.168.31.56:8554/cam
|
||||
|
||||
YOLO_MODEL=C:\project\kpp\app\ml\models\kpp\yolo11n 10 epochs\yolo11n_10epochs.pt
|
||||
# MODEL_NAME=kpp\yolo11n 10epochs\yolo11n_10epochs.pt
|
||||
MODEL_NAME=C:\project\kpp\app\ml\models\kpp\yolo11n 10 epochs\yolo11n_10epochs.pt
|
||||
|
||||
token=MyToken
|
||||
ip_addr_web=MyIpAddr
|
||||
WEB_IP_ADDR=192.168.31.56:8000
|
||||
WEB_TOKEN=local-test-key
|
||||
|
||||
REDIS_HOST=192.168.31.56
|
||||
REDIS_PORT=6379
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@ -14,7 +14,7 @@ test.db
|
||||
log.txt
|
||||
Pipfile.lock
|
||||
env3.*
|
||||
env
|
||||
.env
|
||||
docs_build
|
||||
site_build
|
||||
venv
|
||||
|
||||
10
app/.dockerignore
Normal file
10
app/.dockerignore
Normal file
@ -0,0 +1,10 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
|
||||
*.log
|
||||
.tmp
|
||||
|
||||
.env
|
||||
.local
|
||||
@ -0,0 +1,56 @@
|
||||
###########
|
||||
# BUILDER #
|
||||
###########
|
||||
|
||||
# pull official base image
|
||||
FROM python:3.10 as builder
|
||||
|
||||
# set work directory
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
# set environment variables
|
||||
ENV PYTHONDONTWRITEBYTECODE 1
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
|
||||
# install system dependencies
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends gcc
|
||||
|
||||
# install python dependencies
|
||||
COPY ./requirements.txt .
|
||||
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt
|
||||
|
||||
|
||||
#########
|
||||
# FINAL #
|
||||
#########
|
||||
|
||||
# pull official base image
|
||||
FROM python:3.10
|
||||
|
||||
# create directory for the app user
|
||||
RUN mkdir -p /home/app
|
||||
|
||||
# create the app user
|
||||
RUN addgroup --system app && adduser --system --group app
|
||||
|
||||
# create the appropriate directories
|
||||
ENV HOME=/home/app
|
||||
RUN mkdir $HOME
|
||||
WORKDIR $HOME
|
||||
|
||||
# install dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends netcat-traditional
|
||||
COPY --from=builder /usr/src/app/wheels /wheels
|
||||
COPY --from=builder /usr/src/app/requirements.txt .
|
||||
RUN pip install --upgrade pip
|
||||
RUN pip install --no-cache /wheels/*
|
||||
|
||||
# copy project
|
||||
COPY . $HOME
|
||||
|
||||
RUN chown -R app:app $HOME
|
||||
|
||||
USER app
|
||||
|
||||
ENV YOLO_MODEL=$HOME/ml/models/$MODEL_NAME
|
||||
@ -1,26 +0,0 @@
|
||||
class Car():
|
||||
def __init__(self, x1, y1, x2, y2):
|
||||
|
||||
self.x1 = x1
|
||||
self.y1 = y1
|
||||
self.x2 = x2
|
||||
self.y2 = y2
|
||||
|
||||
@property
|
||||
def width(self) -> float:
|
||||
|
||||
return self.x2 - self.x1
|
||||
|
||||
@property
|
||||
def height(self) -> float:
|
||||
|
||||
return self.y2 - self.y1
|
||||
|
||||
@property
|
||||
def area(self) -> float:
|
||||
|
||||
return self.width * self.height
|
||||
|
||||
def get_center(self) -> tuple[float, float]:
|
||||
|
||||
return ((self.x1 + self.x2) / 2, (self.y1 + self.y2) / 2)
|
||||
@ -1,6 +1,6 @@
|
||||
class Plate():
|
||||
def __init__(self, number: str, x1, y1, x2, y2):
|
||||
self.number = number
|
||||
class BaseData:
|
||||
def __init__(self, x1, y1, x2, y2):
|
||||
|
||||
self.x1 = x1
|
||||
self.y1 = y1
|
||||
self.x2 = x2
|
||||
@ -23,4 +23,12 @@ class Plate():
|
||||
|
||||
def get_center(self) -> tuple[float, float]:
|
||||
|
||||
return ((self.x1 + self.x2) / 2, (self.y1 + self.y2) / 2)
|
||||
return ((self.x1 + self.x2) / 2, (self.y1 + self.y2) / 2)
|
||||
|
||||
class Plate(BaseData):
|
||||
def __init__(self, number: str, x1, y1, x2, y2):
|
||||
self.number = number
|
||||
super().__init__(x1, y1, x2, y2)
|
||||
|
||||
class Car(BaseData):
|
||||
pass
|
||||
@ -8,19 +8,30 @@ import re
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
from Car import Car
|
||||
from Plate import Plate
|
||||
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')
|
||||
yolo_model= os.getenv('YOLO_MODEL', r'C:\project\kpp\app\ml\models\kpp\yolo11n 20 eposhs\best.pt')
|
||||
|
||||
token= os.getenv('token')
|
||||
token= os.getenv('WEB_TOKEN')
|
||||
|
||||
ip_addr_web= os.getenv('ip_addr_web')
|
||||
ip_addr_web= os.getenv('WEB_IP_ADDR')
|
||||
|
||||
# Загрузка YOLO-модели
|
||||
model = YOLO(yolo_model)
|
||||
@ -86,79 +97,63 @@ def paddle_ocr(frame, x1, y1, x2, y2):
|
||||
print(f"❌ Ошибка OCR: {str(e)}")
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def send_car_data(pts, car: Car, plate: Plate ):
|
||||
|
||||
def json_packer(type, data: BaseData):
|
||||
try:
|
||||
url = f"http://{ip_addr_web}/recieve_data_from_ai"
|
||||
|
||||
car_data = {
|
||||
"coordinates" : [
|
||||
car.x1,
|
||||
car.x2
|
||||
],
|
||||
"widht" : car.width,
|
||||
"hight" : car.height
|
||||
|
||||
}
|
||||
|
||||
plate_data = {
|
||||
"coordinates" : [
|
||||
plate.x1,
|
||||
plate.x2
|
||||
],
|
||||
"widht" : plate.width,
|
||||
"hight" : plate.height
|
||||
}
|
||||
|
||||
data = {
|
||||
"pts": pts,
|
||||
"plate_number": plate.number,
|
||||
"car": car_data,
|
||||
"plate": plate_data
|
||||
|
||||
'type': type,
|
||||
"coordinates" : [
|
||||
data.x1,
|
||||
data.y1
|
||||
],
|
||||
"width" : data.width,
|
||||
"height" : data.height
|
||||
}
|
||||
|
||||
payload = json.dumps(data)
|
||||
|
||||
headers = {
|
||||
'Authorization': f'{token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
# для тестирования
|
||||
# response = f"""
|
||||
# POST,
|
||||
# url: {url},
|
||||
# headers: {headers},
|
||||
# data: {[payload]}
|
||||
# """
|
||||
|
||||
return {
|
||||
"POST"
|
||||
"sent_data": data,
|
||||
"response": {
|
||||
"status_code": response.status_code,
|
||||
"text": response.text
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return data
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Ошибка при отправке данных: {str(e)}"
|
||||
error_msg = f"Ошибка при формировании данных: {str(e)}"
|
||||
print(f"\n❌ {error_msg}")
|
||||
return {
|
||||
"error": error_msg
|
||||
}
|
||||
|
||||
plate_text = ""
|
||||
|
||||
def server_ping():
|
||||
try:
|
||||
print(data)
|
||||
url = f"http://{ip_addr_web}/api/recieve/"
|
||||
|
||||
headers = {
|
||||
'Authorization': f'{token}',
|
||||
'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)
|
||||
redis_con.lpush(key, value)
|
||||
if redis_con.llen(key)%100==0:
|
||||
server_ping()
|
||||
|
||||
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)
|
||||
|
||||
@ -177,7 +172,6 @@ video = container.demux(video=0)
|
||||
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():
|
||||
|
||||
if 'start_time' not in locals():
|
||||
start_time = time.time()
|
||||
start_read = frame.time
|
||||
@ -185,36 +179,34 @@ for packet in container.demux(video_stream):
|
||||
if (time.time()-start_time)-(frame.time-start_read)>.3:
|
||||
continue # пропуск кадров при отставании от real time
|
||||
|
||||
pts = frame.pts # PTS в тактах (time_base)
|
||||
pts = time.time()
|
||||
img = frame.to_ndarray(format='bgr24')
|
||||
results = model.predict(img)
|
||||
|
||||
data = {'pts': pts,
|
||||
'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.4:
|
||||
x1, y1, x2, y2 = map(int,box.xyxy[0])
|
||||
|
||||
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'].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)
|
||||
# cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
|
||||
|
||||
# выводит данные о классе 'car'
|
||||
elif box.cls == 1 and box.conf >= 0.70:
|
||||
x1, y1, x2, y2 = map(int, box.xyxy[0])
|
||||
elif box.cls == 1 and box.conf >= 0.50:
|
||||
car = Car(x1, y1, x2, y2)
|
||||
|
||||
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
|
||||
data['content'].append(json_packer(int(box.cls), car))
|
||||
# cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
|
||||
|
||||
# print(send_car_data(pts, car, plate))
|
||||
|
||||
cv2.imshow('frame', img)
|
||||
if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||
cv2.destroyAllWindows()
|
||||
container.close()
|
||||
break
|
||||
data_upload_redis(data)
|
||||
# cv2.imshow('frame', img)
|
||||
# if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||
# cv2.destroyAllWindows()
|
||||
# container.close()
|
||||
# break
|
||||
|
||||
@ -1,10 +1,8 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn==0.24.0
|
||||
opencv-python==4.8.1.78
|
||||
opencv-python-headless==4.11.0.86
|
||||
numpy==1.26.2
|
||||
ultralytics==8.3.111
|
||||
paddlepaddle==2.5.2
|
||||
paddleocr==2.7.0.3
|
||||
psycopg2-binary==2.9.9
|
||||
paddleocr==3.0.0
|
||||
python-dotenv==1.0.0
|
||||
pyav==14.2.1
|
||||
pyav==14.2.1
|
||||
redis==5.2.1
|
||||
0
docker-compose.yml
Normal file
0
docker-compose.yml
Normal file
Loading…
x
Reference in New Issue
Block a user