import os from flask import abort from flask import send_from_directory from flask.views import View from pycs.database.Result import Result from pycs.util import file_ops class ResultAsCrop(View): """ return the image crop defined by the result. """ # pylint: disable=arguments-differ methods = ['GET'] def dispatch_request(self, result_id: int, max_width: int = 2**24, max_height: int = 2**24): # find result result = Result.get_or_404(result_id) if result.file.type != "image": abort(400, f"Currently only supporting images!") if result.type != "bounding-box": abort(400, f"The type of the queried result was not \"bounding-box\"! It was {result.type}") data = result.data if result.data is None: abort(400, "The data of the result was None!") xywh = [data.get(attr, -1) for attr in "xywh"] if -1 in xywh: abort(400, f"The data of the result is not correct: {data}!") x, y, w, h = xywh crop_path, crop_fname = file_ops.crop_file(result.file.id, x, y, w, h) parts = os.path.splitext(crop_fname) crop_new_fname = f"{parts[0]}_{max_width}_{max_height}.{parts[1]}" resized = file_ops.resize_image( os.path.join(crop_path, crop_fname), os.path.join(crop_path, crop_new_fname), max_width, max_height ) if resized: crop_fname = crop_new_fname return send_from_directory(crop_path, crop_fname)