"""This lambda responds for image transcoding.""" from __future__ import print_function import os import uuid from PIL import Image import boto3 s3_client = boto3.client('s3') def transcode_images(image_path, result_paths): """Open image and save in given formats. Args: image_path: (str): Path to downloaded file. result_paths: (list(dict)): List of paths for tmp directory and s3. """ with Image.open(image_path) as image: for path in result_paths: image.save(path['tmp_path']) def generate_paths(key): """Generate output paths. Args: key: (str): Path to file in s3. """ file_name, ext = os.path.splitext(key) return [ { 'output': 'img/jpg/{}.jpg'.format(file_name), 'tmp_path': '/tmp/{}{}.jpg'.format(uuid.uuid4(), file_name) }, { 'output': 'img/tiff/{}.tiff'.format(file_name), 'tmp_path': '/tmp/{}{}.tiff'.format(uuid.uuid4(), file_name) } ] def handler(event, context): """Lambda handler. Args: event: (dict): Information about uploaded file. context: (dict): Environment state. Returns: dict: Dict with transcoding results. """ input_bucket = event['bucket'] output_backet = os.environ.get('OUTPUT_BUCKET') key = event['key'] download_path = '/tmp/{}{}'.format(uuid.uuid4(), key) try: s3_client.download_file(input_bucket, key, download_path) output_paths = generate_paths(key) transcode_images(download_path, output_paths) for path in output_paths: s3_client.upload_file(path['tmp_path'], output_backet, path['output']) except Exception as e: print("Can't transcode image.") return {'status': 'Error', 'message': str(e.args)} return {'status': 'OK', 'message': ''}