Hompimpaa / app.py
moordgg's picture
awal
25a5326 verified
Raw History Blame Contribute Delete
2.11 kB
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List
from ultralytics import YOLO
from PIL import Image
import io
app = FastAPI(
title="Realtime Object Detection API",
version="1.0.0",
description="API praktikum Computer Vision - AI in Production"
)
# ==== CORS: izinkan diakses dari Vercel / lainnya ====
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # untuk praktikum boleh *, production sebaiknya spesifik domain
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ==== Load model YOLO sekali di awal ====
# Pastikan file yolov8n.pt ada di folder yang sama
model = YOLO("yolov8n.pt")
class Detection(BaseModel):
class_name: str
confidence: float
x1: float
y1: float
x2: float
y2: float
class PredictResponse(BaseModel):
width: int
height: int
detections: List[Detection]
@app.get("/health")
def health_check():
return {"status": "ok", "message": "API is healthy"}
@app.post("/predict", response_model=PredictResponse)
async def predict(file: UploadFile = File(...)):
# Baca bytes gambar
image_bytes = await file.read()
# Konversi ke PIL Image (RGB)
img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
width, height = img.size
# Jalankan inferensi YOLO
results = model(img)[0] # ambil result pertama
detections = []
for box in results.boxes:
x1, y1, x2, y2 = box.xyxy[0].tolist()
conf = float(box.conf[0])
cls_id = int(box.cls[0])
cls_name = model.names[cls_id]
detections.append(
Detection(
class_name=cls_name,
confidence=conf,
x1=float(x1),
y1=float(y1),
x2=float(x2),
y2=float(y2),
)
)
return PredictResponse(
width=width,
height=height,
detections=detections
)