-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
84 lines (68 loc) · 2.4 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import boto3
import filetype
import json
import os
import re
import urllib.parse
import uuid
s3_client = boto3.client('s3')
def lambda_handler(event, context):
bucketName = event['Records'][0]['s3']['bucket']['name']
InputFile = urllib.parse.unquote_plus(
event['Records'][0]['s3']['object']['key'], encoding='utf-8')
fileToThumbnail(InputFile, bucketName)
def fileToThumbnail(InputFileName, bucketName):
print("Process file: " + InputFileName)
ThumbnailFileName = os.path.splitext(
InputFileName)[0] + os.getenv('EXTENSION')
print("Output file: " + ThumbnailFileName)
fileExtension = os.path.splitext(InputFileName)[1]
print("file extension: " + fileExtension)
downloadFilePath = '/tmp/' + str(uuid.uuid4()) + fileExtension
s3_client.download_file(bucketName, InputFileName, downloadFilePath)
fileType = filetype.guess(downloadFilePath).mime
print("file type: " + fileType)
uploadFilePath = '/tmp/' + ThumbnailFileName
processed = True
if "application/pdf" in fileType:
print("Process pdf file: " + downloadFilePath)
os.system(
"/opt/bin/convert -density " +
os.getenv('THUMB_WIDTH') +
" " +
downloadFilePath +
"[0] -quality 90 " +
uploadFilePath)
elif "image/" in fileType:
print("Process image file: " + downloadFilePath)
os.system(
"/opt/bin/convert " +
downloadFilePath +
" -quiet -resize " +
str(int( os.getenv('THUMB_WIDTH') ) * 2) +
"x " +
uploadFilePath)
elif "video/" in fileType:
print("Process video file: " + downloadFilePath)
os.system(
"/opt/bin/ffmpeg " +
"-loglevel error -y -i " +
downloadFilePath +
" -vf thumbnail,scale=" +
str(int( os.getenv('THUMB_WIDTH') ) * 2) +
":-1 -frames:v 1 " +
uploadFilePath)
else:
processed = False
print("This file extension is not supported.")
if processed:
s3_client.upload_file(
uploadFilePath,
os.getenv('OUTPUT_BUCKET'),
ThumbnailFileName)
clearTmpFiles(uploadFilePath, downloadFilePath)
else:
os.remove(downloadFilePath)
def clearTmpFiles(uploadFileName, downloadFileName):
os.remove(uploadFileName)
os.remove(downloadFileName)