-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
82 lines (67 loc) · 2.16 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import time
from fastapi import FastAPI, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from config import Settings
from predictor import Predictor
from utils import bytes_to_ndarray
settings = Settings()
app = FastAPI()
origins = [
"https://buuz.app",
"https://api.buuz.app",
"http://localhost:3000",
"http://127.0.0.1:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
predictor = Predictor(
model_path=settings.model_path,
overlap_threshold=settings.overlap_threshold,
confidence_threshold=settings.confidence_threshold,
)
class BoxResult(BaseModel):
box: tuple[float, float, float, float]
confidence: float
class PredictionResult(BaseModel):
count: int
message: str
boxes: list[BoxResult]
@app.get("/")
async def root():
return {"message": "Hello! I'm Buuz App."}
@app.post("/predict")
async def predict(file: UploadFile) -> PredictionResult:
if file.content_type != "image/jpeg" and file.content_type != "image/png":
raise HTTPException(
status_code=415, detail="Only JPEG or PNG images are supported"
)
if file.size is not None and file.size > settings.file_size_limit:
raise HTTPException(status_code=413, detail="File size too large")
start = time.time()
image = bytes_to_ndarray(await file.read())
if image.shape[2] == 4:
image = image[:, :, :3]
boxes, w, h, pad_horizontal, pad_vertical = predictor.predict(image)
objects = []
for box in boxes:
x1, y1, x2, y2, cnf, cls = box
objects.append(
BoxResult(
box=(
(x1 - pad_horizontal) / w,
(y1 - pad_vertical) / h,
(x2 - pad_horizontal) / w,
(y2 - pad_vertical) / h,
),
confidence=cnf,
)
)
print(f"Found {len(objects)} objects")
print(f"Process took {(time.time() - start)*1000:.3f}ms")
return PredictionResult(count=len(objects), message="Ok", boxes=objects)