6
0

ResultAsCrop.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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.Database import Database
  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 __init__(self, db: Database):
  14. # pylint: disable=invalid-name
  15. self.db = db
  16. def dispatch_request(self, result_id: int, max_width: int = 2**24, max_height: int = 2**24):
  17. # find result
  18. result = self.db.result(result_id)
  19. if result is None:
  20. abort(404)
  21. if result.type != "bounding-box":
  22. abort(400, f"The type of the queried result was not \"bounding-box\"! It was {result.type}")
  23. file = result.file()
  24. if file.type != "image":
  25. abort(400, f"Currently only supporting images!")
  26. data = result.data
  27. if data is None:
  28. abort(400, "The data of the result was None!")
  29. xywh = [data.get(attr, -1) for attr in "xywh"]
  30. if -1 in xywh:
  31. abort(400, f"The data of the result is not correct: {data}!")
  32. x, y, w, h = xywh
  33. project = file.project()
  34. crop_path, crop_fname = file_ops.crop_file(file, project.root_folder, x, y, w, h)
  35. parts = os.path.splitext(crop_fname)
  36. crop_new_fname = f"{parts[0]}_{max_width}_{max_height}.{parts[1]}"
  37. resized = file_ops.resize_image(
  38. os.path.join(crop_path, crop_fname),
  39. os.path.join(crop_path, crop_new_fname),
  40. max_width,
  41. max_height
  42. )
  43. if resized:
  44. crop_fname = crop_new_fname
  45. return send_from_directory(crop_path, crop_fname)