Spaces:
Sleeping
Sleeping
File size: 2,450 Bytes
dc00e54 887bc13 dc00e54 887bc13 dc00e54 887bc13 dc00e54 887bc13 dc00e54 887bc13 dc00e54 887bc13 dc00e54 887bc13 dc00e54 887bc13 dc00e54 887bc13 dc00e54 887bc13 dc00e54 | 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
from pydantic import BaseModel
import uvicorn
import base64
import cv2
import numpy as np
from ultralytics import YOLO
from datetime import datetime
app = FastAPI(title="PCB Component Detection API")
model = YOLO("pcb_component_detection_best.pt")
class ImageRequest(BaseModel):
"""Request model for image processing endpoint."""
image: str
@app.get("/")
async def root():
"""Root endpoint to verify API status."""
current_time = datetime.now().isoformat()
return {
"message": "PCB Components API works",
"time": current_time
}
@app.post("/predict")
async def predict(request: ImageRequest):
"""
Process an image to detect PCB components.
Args:
request: Contains base64 encoded image
Returns:
JSON with detection statistics and bounding boxes
"""
# Validate image input
if not request.image:
return {"error": "Invalid Image"}
try:
image_bytes = base64.b64decode(request.image, validate=True)
np_arr = np.frombuffer(image_bytes, np.uint8)
image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
if image is None:
return {"error": "Invalid image"}
results = model.predict(image)
result = results[0]
json_result = {}
class_counters = {}
for box in result.boxes:
class_id = int(box.cls[0])
class_name = result.names[class_id]
x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
if class_name in class_counters:
class_counters[class_name] += 1
else:
class_counters[class_name] = 1
key = f"{class_name}{class_counters[class_name]}" if class_counters[class_name] > 1 else class_name
json_result[key] = [x1, y1, x2, y2]
if hasattr(result, "summary") and isinstance(result.summary, dict):
statistics_summary = result.summary
else:
statistics_summary = {name: count for name, count in class_counters.items()}
return {
"statistics": statistics_summary,
"components": json_result
}
except Exception as e:
return {"error": f"Invalid Image: {str(e)}"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)
|