166 lines
5.3 KiB
Python
166 lines
5.3 KiB
Python
import io
|
|
import multiprocessing
|
|
import time
|
|
|
|
from PIL import Image, ImageFile, ImageOps, UnidentifiedImageError
|
|
|
|
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
|
|
|
THUMBNAIL_BOX = 256
|
|
CROP_SIDE = 128
|
|
OPTIMIZED_BOX = 1280
|
|
|
|
_VARIANT_ORDER = ("thumbnail", "crop", "optimized")
|
|
|
|
|
|
def _without_metadata(image: Image.Image) -> Image.Image:
|
|
bare = Image.new("RGB", image.size)
|
|
bare.paste(image)
|
|
return bare
|
|
|
|
|
|
def _to_rgb(image: Image.Image) -> Image.Image:
|
|
oriented = ImageOps.exif_transpose(image)
|
|
if oriented.mode == "RGB":
|
|
return _without_metadata(oriented)
|
|
if oriented.mode in {"RGBA", "LA"} or (oriented.mode == "P" and "transparency" in oriented.info):
|
|
rgba = oriented.convert("RGBA")
|
|
base = Image.new("RGB", rgba.size, (255, 255, 255))
|
|
base.paste(rgba, mask=rgba.getchannel("A"))
|
|
return base
|
|
return _without_metadata(oriented.convert("RGB"))
|
|
|
|
|
|
def _fit_within(image: Image.Image, box: int) -> Image.Image:
|
|
width, height = image.size
|
|
scale = min(box / width, box / height, 1.0)
|
|
new_width = max(1, int(width * scale))
|
|
new_height = max(1, int(height * scale))
|
|
if new_width == width and new_height == height:
|
|
return image
|
|
return image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
|
|
|
|
def _center_square(image: Image.Image, side: int) -> Image.Image:
|
|
width, height = image.size
|
|
source = min(width, height)
|
|
left = (width - source) // 2
|
|
top = (height - source) // 2
|
|
cropped = image.crop((left, top, left + source, top + source))
|
|
if cropped.size != (side, side):
|
|
cropped = cropped.resize((side, side), Image.Resampling.LANCZOS)
|
|
return cropped
|
|
|
|
|
|
def _jpeg_bytes(image: Image.Image, quality: int) -> bytes:
|
|
buffer = io.BytesIO()
|
|
image.save(buffer, format="JPEG", quality=quality, optimize=True)
|
|
return buffer.getvalue()
|
|
|
|
|
|
def _webp_bytes(image: Image.Image, quality: int, method: int) -> bytes:
|
|
buffer = io.BytesIO()
|
|
image.save(buffer, format="WEBP", quality=quality, method=method)
|
|
return buffer.getvalue()
|
|
|
|
|
|
def _fail(code: str, permanent: bool) -> dict:
|
|
return {"ok": False, "code": code, "permanent": permanent}
|
|
|
|
|
|
def render_variants(
|
|
data: bytes,
|
|
max_pixels: int,
|
|
memory_budget: int,
|
|
jpeg_quality: int,
|
|
webp_quality: int,
|
|
webp_method: int,
|
|
) -> dict:
|
|
Image.MAX_IMAGE_PIXELS = max_pixels
|
|
try:
|
|
with Image.open(io.BytesIO(data)) as source:
|
|
width, height = source.size
|
|
if width < 1 or height < 1:
|
|
return _fail("invalid_image", True)
|
|
if width * height > max_pixels or width * height * 4 > memory_budget:
|
|
return _fail("payload_too_large", True)
|
|
source.load()
|
|
rgb = _to_rgb(source)
|
|
thumbnail = _fit_within(rgb, THUMBNAIL_BOX)
|
|
crop = _center_square(rgb, CROP_SIDE)
|
|
optimized = _fit_within(rgb, OPTIMIZED_BOX)
|
|
variants = {
|
|
"thumbnail": {
|
|
"content_type": "image/jpeg",
|
|
"width": thumbnail.size[0],
|
|
"height": thumbnail.size[1],
|
|
"data": _jpeg_bytes(thumbnail, jpeg_quality),
|
|
},
|
|
"crop": {
|
|
"content_type": "image/jpeg",
|
|
"width": crop.size[0],
|
|
"height": crop.size[1],
|
|
"data": _jpeg_bytes(crop, jpeg_quality),
|
|
},
|
|
"optimized": {
|
|
"content_type": "image/webp",
|
|
"width": optimized.size[0],
|
|
"height": optimized.size[1],
|
|
"data": _webp_bytes(optimized, webp_quality, webp_method),
|
|
},
|
|
}
|
|
return {"ok": True, "variants": variants}
|
|
except Image.DecompressionBombError:
|
|
return _fail("payload_too_large", True)
|
|
except MemoryError:
|
|
return _fail("payload_too_large", True)
|
|
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
|
return _fail("invalid_image", True)
|
|
|
|
|
|
def _spawn_render(queue, data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method, stall_seconds) -> None:
|
|
if stall_seconds > 0:
|
|
time.sleep(stall_seconds)
|
|
queue.put(render_variants(data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method))
|
|
|
|
|
|
def render_in_process(
|
|
data: bytes,
|
|
max_pixels: int,
|
|
memory_budget: int,
|
|
jpeg_quality: int,
|
|
webp_quality: int,
|
|
webp_method: int,
|
|
timeout_seconds: float,
|
|
stall_seconds: float = 0,
|
|
) -> dict:
|
|
context = multiprocessing.get_context("spawn")
|
|
queue = context.Queue(maxsize=1)
|
|
process = context.Process(
|
|
target=_spawn_render,
|
|
args=(queue, data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method, stall_seconds),
|
|
)
|
|
process.start()
|
|
process.join(timeout_seconds)
|
|
try:
|
|
if process.is_alive():
|
|
process.terminate()
|
|
process.join(5)
|
|
if process.is_alive():
|
|
process.kill()
|
|
process.join(2)
|
|
return _fail("processing_failed", False)
|
|
if process.exitcode != 0:
|
|
return _fail("processing_failed", False)
|
|
try:
|
|
return queue.get_nowait()
|
|
except Exception:
|
|
return _fail("processing_failed", False)
|
|
finally:
|
|
queue.close()
|
|
queue.cancel_join_thread()
|
|
|
|
|
|
def variant_names() -> tuple[str, ...]:
|
|
return _VARIANT_ORDER
|