Advertisement
kopyl

Untitled

Jun 12th, 2023
698
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. import json
  2.  
  3. import numpy as np
  4. import cv2
  5. import onnxruntime
  6. import urllib.request
  7. import json
  8. from flask import Flask, request, jsonify
  9. import logging
  10.  
  11.  
  12. app = Flask(__name__)
  13. log = logging.getLogger("werkzeug")
  14. log.setLevel(logging.ERROR)
  15.  
  16.  
  17. model = "model_fp16.onnx"
  18. session = onnxruntime.InferenceSession(model, None)
  19. input_name = session.get_inputs()[0].name
  20. output_name = session.get_outputs()[0].name
  21.  
  22.  
  23. def predict_single_image(image_url, session=session):
  24.     req = urllib.request.Request(image_url, headers={"User-Agent": "Mozilla/5.0"})
  25.     with urllib.request.urlopen(req) as url:
  26.         image_contents = url.read()
  27.  
  28.     arr = np.asarray(bytearray(image_contents), dtype=np.uint8)
  29.     img = cv2.imdecode(arr, -1)
  30.  
  31.     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  32.  
  33.     resized_image = cv2.resize(img, (300, 300))
  34.     image_for_prediction = resized_image.transpose(2, 0, 1)
  35.     image_for_prediction = image_for_prediction.astype("float16") / 255.0
  36.     image_for_prediction = image_for_prediction[np.newaxis, :]
  37.  
  38.     data = json.dumps({"data": image_for_prediction.tolist()})
  39.     data = np.array(json.loads(data)["data"]).astype("float16")
  40.  
  41.     result = session.run([output_name], {input_name: data})
  42.     prediction = int(np.argmax(np.array(result).squeeze(), axis=0))
  43.  
  44.     probabilities = np.exp(result) / np.sum(np.exp(result))
  45.     score = np.max(probabilities)
  46.     score = float(score)
  47.  
  48.     return {
  49.         "prediction": prediction,
  50.         "score": score,
  51.     }
  52.  
  53.  
  54. def test_image(image_url):
  55.     return predict_single_image(image_url)
  56.  
  57.  
  58. @app.route("/", methods=["POST"])
  59. def home():
  60.     data = request.get_json()
  61.     image_url = data.get("image_url")
  62.  
  63.     if not image_url:
  64.         return jsonify({"result": "No image_url"}), 400
  65.     token = request.headers.get("Authorization")
  66.     if token != "8Jw1kj5Woa4SDHtD%hH!7v%NBox0!47^WL4-1;:":
  67.         return jsonify({"result": "Invalid token"}), 401
  68.     print(image_url)
  69.     result = test_image(image_url)
  70.  
  71.     if data.get("return_version"):
  72.         result["version"] = "1.0.0"
  73.  
  74.     return jsonify(result), 200
  75.  
  76.  
  77. @app.route("/", methods=["GET"])
  78. def home_get():
  79.     return "Hello World!"
  80.  
  81.  
  82. if __name__ == "__main__":
  83.     app.run(debug=True, host="0.0.0.0", port=80)
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement