forked from mtusi2026/mtusi2026lab5
lab5 na4
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
"""Bounded subprocess: validate original or produce pipeline v1 variants.
|
||||
|
||||
No credentials, network access or client-controlled output paths are used here.
|
||||
Exit codes: 2 invalid image, 3 resource limit. Unexpected failures are retryable.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import resource
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
limit = int(os.environ.get('IMAGE_MEMORY_MB', '384')) * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (20, 21))
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
|
||||
|
||||
def fit_size(size, edge):
|
||||
w, h = size
|
||||
if max(w, h) <= edge:
|
||||
return size
|
||||
return max(1, w * edge // max(w, h)), max(1, h * edge // max(w, h))
|
||||
|
||||
|
||||
def run():
|
||||
mode, source = sys.argv[1:3]
|
||||
if os.path.getsize(source) > 10 * 1024 * 1024:
|
||||
raise MemoryError()
|
||||
with Image.open(source) as im:
|
||||
if im.format not in ('PNG', 'JPEG'):
|
||||
raise ValueError('format')
|
||||
if im.width * im.height > Image.MAX_IMAGE_PIXELS:
|
||||
raise MemoryError()
|
||||
im.verify()
|
||||
with Image.open(source) as im:
|
||||
im.load()
|
||||
if mode == 'validate':
|
||||
return
|
||||
out = sys.argv[3]
|
||||
im = ImageOps.exif_transpose(im)
|
||||
rgba = im.convert('RGBA')
|
||||
rgb = Image.new('RGB', rgba.size, 'white')
|
||||
rgb.paste(rgba, mask=rgba.getchannel('A'))
|
||||
del rgba, im
|
||||
thumb = rgb.resize(fit_size(rgb.size, 256), Image.Resampling.LANCZOS)
|
||||
crop = ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS, centering=(0.5, 0.5))
|
||||
optimized = rgb.resize(fit_size(rgb.size, 1280), Image.Resampling.LANCZOS)
|
||||
variants = []
|
||||
for name, image, fmt in [('thumbnail', thumb, 'JPEG'), ('crop', crop, 'JPEG'), ('optimized', optimized, 'WEBP')]:
|
||||
image.info.clear()
|
||||
options = dict(quality=85, optimize=True) if fmt == 'JPEG' else dict(quality=80, method=4)
|
||||
image.save(os.path.join(out, name), fmt, **options)
|
||||
variants.append(dict(name=name, width=image.width, height=image.height,
|
||||
content_type='image/jpeg' if fmt == 'JPEG' else 'image/webp'))
|
||||
print(json.dumps(variants))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
run()
|
||||
except (MemoryError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
sys.exit(3)
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
sys.exit(2)
|
||||
Reference in New Issue
Block a user