"""Isolated decoder/encoder. No network or credentials; bounded by parent timeout.""" import hashlib import json from pathlib import Path import resource import sys import warnings from PIL import Image, ImageOps # Address space bound complements the whole-container cgroup memory cap. resource.setrlimit(resource.RLIMIT_AS, (640*1024**2,640*1024**2)) Image.MAX_IMAGE_PIXELS = 40000000 warnings.simplefilter('error', Image.DecompressionBombWarning) def fit(image, cap): w,h=image.size ratio=min(1,cap/w,cap/h) return image.resize((max(1,int(w*ratio)),max(1,int(h*ratio))), Image.Resampling.LANCZOS) def main(): source,target=Path(sys.argv[1]),Path(sys.argv[2]) version=int(sys.argv[3]) if len(sys.argv)>3 else 1 jpeg_quality,webp_quality=(85,80) if version==1 else (90,85) with Image.open(source,formats=['PNG','JPEG']) as im: if im.width*im.height>40000000: raise ValueError('pixels') im.load() image=ImageOps.exif_transpose(im).convert('RGBA') white=Image.new('RGBA',image.size,'white') white.alpha_composite(image) rgb=white.convert('RGB') variants=[] for name,content_type,output in ( ('thumbnail','image/jpeg',fit(rgb,256)), ('crop','image/jpeg',ImageOps.fit(rgb,(128,128),method=Image.Resampling.LANCZOS,centering=(.5,.5))), ('optimized','image/webp',fit(rgb,1280))): path=target/name # Explicit empty EXIF; encoder gets a fresh image without source metadata. clean=Image.new('RGB',output.size);clean.paste(output) clean.save(path,format='WEBP' if name=='optimized' else 'JPEG',quality=webp_quality if name=='optimized' else jpeg_quality,exif=b'') payload=path.read_bytes() variants.append(dict(name=name,content_type=content_type,width=output.width,height=output.height, size_bytes=len(payload),sha256=hashlib.sha256(payload).hexdigest())) (target/'manifest.json').write_text(json.dumps(variants)) if __name__=='__main__': try: main() except MemoryError: sys.exit(3) except Exception: # Deliberately no decoder traceback or client-controlled payload in logs. sys.exit(2)