import os from flask import abort from flask import send_from_directory from flask.views import View from pycs.database.Database import Database from pycs.util import file_ops class ResultAsCrop(View): """ return the image crop defined by the result. """ # pylint: disable=arguments-differ methods = ['GET'] def __init__(self, db: Database): # pylint: disable=invalid-name self.db = db def dispatch_request(self, result_id: int, max_width: int = 2**24, max_height: int = 2**24): # find result result = self.db.result(result_id) if result is None: abort(404) if result.type != "bounding-box": abort(400, f"The type of the queried result was not \"bounding-box\"! It was {result.type}") file = result.file() if file.type != "image": abort(400, f"Currently only supporting images!") data = result.data if 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 project = file.project() crop_path, crop_fname = file_ops.crop_file(file, project.root_folder, 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)