Views
No views yet





ultralytics dan huggingface_hub:pip install ultralytics huggingface_hub opencv-python1from fastapi import FastAPI, File, UploadFile, HTTPException
2from fastapi.middleware.cors import CORSMiddleware
3from ultralytics import YOLO
4from huggingface_hub import hf_hub_download
5from PIL import Image
6import io
7import base64
8
9app = FastAPI(title="OpenPath - License Plate Detection API")
10
11# Allow CORS
12app.add_middleware(
13 CORSMiddleware,
14 allow_origins=["*"],
15 allow_credentials=True,
16 allow_methods=["*"],
17 allow_headers=["*"],
18)
19
20# Load Model OpenPath
21print("Loading OpenPath Model from Hugging Face...")
22MODEL_PATH = hf_hub_download(
23 repo_id="OpenPathAI/YOLO-detection-vehcile-plate-2287",
24 filename="weights/best.pt"
25)
26model = YOLO(MODEL_PATH)
27print("✅ Model OpenPath Ready!")
28
29@app.get("/")
30def root():
31 return {"status": "online", "message": "OpenPath License Plate Detection Server Ready"}
32
33@app.post("/detect")
34async def detect_license_plate(file: UploadFile = File(...)):
35 if not file.content_type.startswith("image/"):
36 raise HTTPException(status_code=400, detail="File harus berupa gambar")
37
38 contents = await file.read()
39 image = Image.open(io.BytesIO(contents)).convert("RGB")
40
41 results = model(image, conf=0.4)
42 detections = []
43
44 for result in results:
45 for box in result.boxes:
46 x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
47 confidence = float(box.conf[0])
48
49 cropped_plate = image.crop((x1, y1, x2, y2))
50
51 buffered = io.BytesIO()
52 cropped_plate.save(buffered, format="JPEG")
53 crop_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
54
55 detections.append({
56 "confidence": round(confidence, 2),
57 "box": {"x1": x1, "y1": y1, "x2": x2, "y2": y2},
58 "crop_base64": f"data:image/jpeg;base64,{crop_base64}"
59 })
60
61 return {
62 "success": True,
63 "total_plates_found": len(detections),
64 "detections": detections
65 }