main.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from fastapi import FastAPI, File, UploadFile, Body
  2. from ultralytics import YOLO
  3. import io
  4. from PIL import Image
  5. app = FastAPI()
  6. # 1. Load your custom trained model
  7. model = YOLO('best.pt')
  8. # 2. Global state for the confidence threshold
  9. # Defaulting to 0.25 (YOLO's internal default)
  10. current_conf = 0.25
  11. @app.get("/get_confidence")
  12. async def get_confidence():
  13. """Returns the current confidence threshold used by the model."""
  14. return {
  15. "status": "success",
  16. "current_confidence": current_conf,
  17. "model_version": "best.pt"
  18. }
  19. @app.post("/set_confidence")
  20. async def set_confidence(threshold: float = Body(..., embed=True)):
  21. """Updates the confidence threshold globally."""
  22. global current_conf
  23. if 0.0 <= threshold <= 1.0:
  24. current_conf = threshold
  25. return {"status": "success", "new_confidence": current_conf}
  26. else:
  27. return {"status": "error", "message": "Threshold must be between 0.0 and 1.0"}
  28. @app.post("/detect")
  29. async def detect_ripeness(file: UploadFile = File(...)):
  30. image_bytes = await file.read()
  31. img = Image.open(io.BytesIO(image_bytes))
  32. # 3. Apply the dynamic threshold to the inference
  33. results = model(img, conf=current_conf)
  34. detections = []
  35. for r in results:
  36. for box in r.boxes:
  37. detections.append({
  38. "class": model.names[int(box.cls)],
  39. "confidence": round(float(box.conf), 2),
  40. "box": box.xyxy.tolist()[0]
  41. })
  42. return {
  43. "status": "success",
  44. "current_threshold": current_conf,
  45. "data": detections
  46. }
  47. if __name__ == "__main__":
  48. import uvicorn
  49. uvicorn.run(app, host="0.0.0.0", port=8000)