6
0

ResultAsCrop.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os
  2. from flask import abort
  3. from flask import send_from_directory
  4. from flask.views import View
  5. from pycs.database.Result import Result
  6. from pycs.util import file_ops
  7. class ResultAsCrop(View):
  8. """
  9. return the image crop defined by the result.
  10. """
  11. # pylint: disable=arguments-differ
  12. methods = ['GET']
  13. def dispatch_request(self, result_id: int, max_width: int = 2**24, max_height: int = 2**24):
  14. # find result
  15. result = Result.get_or_404(result_id)
  16. if result.file.type != "image":
  17. abort(400, f"Currently only supporting images!")
  18. if result.type != "bounding-box":
  19. abort(400, f"The type of the queried result was not \"bounding-box\"! It was {result.type}")
  20. data = result.data
  21. if result.data is None:
  22. abort(400, "The data of the result was None!")
  23. xywh = [data.get(attr, -1) for attr in "xywh"]
  24. if -1 in xywh:
  25. abort(400, f"The data of the result is not correct: {data}!")
  26. x, y, w, h = xywh
  27. crop_path, crop_fname = file_ops.crop_file(result.file.id, x, y, w, h)
  28. parts = os.path.splitext(crop_fname)
  29. crop_new_fname = f"{parts[0]}_{max_width}_{max_height}.{parts[1]}"
  30. resized = file_ops.resize_image(
  31. os.path.join(crop_path, crop_fname),
  32. os.path.join(crop_path, crop_new_fname),
  33. max_width,
  34. max_height
  35. )
  36. if resized:
  37. crop_fname = crop_new_fname
  38. return send_from_directory(crop_path, crop_fname)