Files
ProjectIOT/server.py
Stef 5e4b1acca0 Sped up ANPR
Sped up ANPR by only creating one ANPR instance, rather than initializing a new one every function call.
2025-04-25 07:55:49 +02:00

66 lines
1.5 KiB
Python

from flask import request, jsonify
from pyplatex import ANPR # type: ignore
from ultralytics.nn.tasks import DetectionModel # type: ignore
import os
import torch
import asyncio
from application import app, db
from models import LoggedItem, AllowedPlate
from datetime import datetime
torch.serialization.add_safe_globals( # type: ignore
{"DetectionModel": DetectionModel} # type: ignore
)
anpr = ANPR()
# Saving images locally
UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Default app route
@app.route("/")
def home():
return "Hello, World!"
# API to process vehicle
@app.route("/api", methods=["POST"])
def data():
data = request.data
with open("image.jpg", "wb") as f:
f.write(data)
status = asyncio.run(process_image(file="image.jpg", anpr=anpr))
return jsonify(
{
"message": "Image sent succesfully",
"status": status,
}
)
async def process_image(file: str, anpr: ANPR) -> bool:
print("Processing image")
anpr_info = await anpr.detect(file) # type: ignore
number_plate = anpr_info["plate_number"]
if number_plate:
allowed = (
AllowedPlate.query.filter_by(plate=number_plate).first()
is not None
)
db.session.add(
LoggedItem(
plate=number_plate, allowed=allowed, datetime=datetime.now()
)
)
db.session.commit()
return allowed
return False
if __name__ == "__main__":
app.run(host="192.168.137.1", port=2222, debug=True)