File size: 2,114 Bytes
25a5326 | 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 83 84 | 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
)
|