You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.3KB

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Run a Flask REST API exposing a YOLOv5s model
  4. """
  5. import argparse
  6. import io
  7. import torch
  8. from flask import Flask, request
  9. from PIL import Image
  10. app = Flask(__name__)
  11. DETECTION_URL = "/v1/object-detection/yolov5s"
  12. @app.route(DETECTION_URL, methods=["POST"])
  13. def predict():
  14. if not request.method == "POST":
  15. return
  16. if request.files.get("image"):
  17. image_file = request.files["image"]
  18. image_bytes = image_file.read()
  19. img = Image.open(io.BytesIO(image_bytes))
  20. results = model(img, size=640) # reduce size=320 for faster inference
  21. return results.pandas().xyxy[0].to_json(orient="records")
  22. if __name__ == "__main__":
  23. parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model")
  24. parser.add_argument("--port", default=5000, type=int, help="port number")
  25. opt = parser.parse_args()
  26. # Fix known issue urllib.error.HTTPError 403: rate limit exceeded https://github.com/ultralytics/yolov5/pull/7210
  27. torch.hub._validate_not_a_forked_repo = lambda a, b, c: True
  28. model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache
  29. app.run(host="0.0.0.0", port=opt.port) # debug=True causes Restarting with stat