Spaces:
Sleeping
Sleeping
Update main.py
Browse files123416 unmodified lines212223242526272 unmodified lines303132333435363738394041424344454647484950515253545556575859603 unmodified lines646566676869705 unmodified lines76777879# main.pyimport ioimport osfrom ultralytics import YOLO16 unmodified linesapp = FastAPI(title="YOLOv8 Weed Detection API", lifespan=lifespan)app.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)model = Nonetry:model_path = os.path.join(os.path.dirname(__file__), 'yolov8x.pt')logger.info(f"Attempting to load model from: {model_path}")if not os.path.exists(model_path):logger.error(f"Model file not found at {model_path}")else:model = YOLO(model_path)logger.info("YOLOv8 model loaded successfully.")except Exception as e:logger.error(f"Error loading YOLOv8 model: {e}", exc_info=True)@app.post("/detect/", tags=["Detection"])async def detect_objects(file: UploadFile = File(...)):if not model:logger.error("Model is not loaded, cannot process request.")return JSONResponse(status_code=500, content={"message": "Model is not loaded."})contents = await file.read()try:image = Image.open(io.BytesIO(contents))except Exception as e:logger.error(f"Invalid image file received: {e}")return JSONResponse(status_code=400, content={"message": f"Invalid image file: {e}"})try:results = model(image)detections = []for result in results:boxes = result.boxes.cpu().numpy()3 unmodified linesconfidence = float(box.conf[0])detections.append({"class_id": class_id,"class_name": model.names[class_id],"bounding_box": r.tolist(),"confidence": confidence})5 unmodified lines@app.get("/", tags=["Health Check"])def read_root():"""Root endpoint for health check."""return {"status": "YOLOv8 API is running."}12316 unmodified lines2021222324252 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263646566673 unmodified lines717273747576775 unmodified lines83848586878889import ioimport osfrom ultralytics import YOLO16 unmodified linesapp = FastAPI(title="YOLOv8 Weed Detection API", lifespan=lifespan)app.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# Lazy load modelmodel = Nonemodel_path = os.path.join(os.path.dirname(__file__), "yolov8x.pt")def get_model():global modelif model is None:if not os.path.exists(model_path):logger.error(f"Model file not found at {model_path}")return Nonetry:logger.info(f"Loading YOLOv8 model from: {model_path}")model = YOLO(model_path)logger.info("YOLOv8 model loaded successfully.")except Exception as e:logger.error(f"Error loading YOLOv8 model: {e}", exc_info=True)return Nonereturn model@app.post("/detect/", tags=["Detection"])async def detect_objects(file: UploadFile = File(...)):model_instance = get_model()if not model_instance:return JSONResponse(status_code=500, content={"message": "Model is not loaded."})contents = await file.read()try:image = Image.open(io.BytesIO(contents))except Exception as e:logger.error(f"Invalid image file received: {e}")return JSONResponse(status_code=400, content={"message": f"Invalid image file: {e}"})try:results = model_instance(image)detections = []for result in results:boxes = result.boxes.cpu().numpy()3 unmodified linesconfidence = float(box.conf[0])detections.append({"class_id": class_id,"class_name": model_instance.names[class_id],"bounding_box": r.tolist(),"confidence": confidence})5 unmodified lines@app.get("/", tags=["Health Check"])def read_root():"""Root endpoint for health check."""return {"status": "YOLOv8 API is running.","model_loaded": model is not None}
main.py+27-17