ResultAsCrop.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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.type != "bounding-box":
  17. abort(400, f"The type of the queried result was not \"bounding-box\"! It was {result.type}")
  18. file = result.file
  19. if file.type != "image":
  20. abort(400, f"Currently only supporting images!")
  21. data = result.data
  22. if data is None:
  23. abort(400, "The data of the result was None!")
  24. xywh = [data.get(attr, -1) for attr in "xywh"]
  25. if -1 in xywh:
  26. abort(400, f"The data of the result is not correct: {data}!")
  27. x, y, w, h = xywh
  28. crop_path, crop_fname = file_ops.crop_file(file, file.project.root_folder, x, y, w, h)
  29. parts = os.path.splitext(crop_fname)
  30. crop_new_fname = f"{parts[0]}_{max_width}_{max_height}.{parts[1]}"
  31. resized = file_ops.resize_image(
  32. os.path.join(crop_path, crop_fname),
  33. os.path.join(crop_path, crop_new_fname),
  34. max_width,
  35. max_height
  36. )
  37. if resized:
  38. crop_fname = crop_new_fname
  39. return send_from_directory(crop_path, crop_fname)