Spaces:
Sleeping
Sleeping
File size: 2,111 Bytes
b03c074 44c4212 5cc4bfa 44c4212 5cc4bfa 44c4212 5cc4bfa 44c4212 b03c074 44c4212 b03c074 52b3dfe b03c074 f66d891 b03c074 f66d891 b03c074 f66d891 44c4212 b03c074 | 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 | from fastapi import FastAPI
import uvicorn
import base64
import cv2
import numpy as np
from ultralytics import YOLO
from datetime import datetime
from pydantic import BaseModel
app = FastAPI()
model = YOLO("yolo_modeln11_1502.pt")
class ImageRequest(BaseModel):
image: str
@app.get("/")
async def root():
current_time = datetime.now().isoformat()
return {"message": "PCB Defects API works", "time": current_time}
@app.post("/predict")
async def predict(request: ImageRequest):
# Check if the image string is empty
if not request.image:
return {"error": "Invalid Image"}
try:
# Attempt to decode Base64 string to bytes
image_bytes = base64.b64decode(request.image, validate=True)
except Exception as e:
return {"error": "Invalid Image"}
# Ensure the decoded bytes are not empty
if not image_bytes:
return {"error": "Invalid Image"}
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]
# Response
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())
# Counting occurrences of each defect
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, "detections": json_result}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)
|