Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
Latest commit
161 lines (139 loc) · 5.37 KB
/
Copy pathlambda_function.py
File metadata and controls
161 lines (139 loc) · 5.37 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
importboto3
importos
fromPILimportImage, ImageOps
importsubprocess
s3_client=boto3.client('s3')
thumbnail_bucket=os.environ.get('THUMBNAIL_BUCKET')
IMG_EXT_LIST= ["jpg","jpeg","png","jfif","bmp","webp"]
VDO_EXT_LIST= ["mp4","mov"]
FFMPEG_BIN="/opt/bin/ffmpeg"
defcreate_video_thumbnail_image(download_path, resized_path, quality=70):
"""
비디오에서 첫 번째 프레임을 추출하여 썸네일 생성
예외 발생 시 상위 함수에서 처리
"""
cmd= [
FFMPEG_BIN,
"-i", download_path,
"-vframes", "1",
"-q:v", str(quality),
resized_path
]
subprocess.run(cmd, check=True, capture_output=True, text=True)
create_thumbnail_image(resized_path, resized_path)
defcreate_thumbnail_image(image_path, resized_path, size=256, quality=30):
"""
썸네일용 이미지 리사이징 (비율 유지, 짧은 변 최대 길이 thumb_size 제한, 256 * 256 크기로 crop), WebP 포맷
"""
withImage.open(image_path) asimage:
image=ImageOps.exif_transpose(image)
# 긴 변 기준 리사이즈 (비율 유지)
width, height=image.size
scale=size/min(width, height)
new_width=int(width*scale)
new_height=int(height*scale)
image=image.resize((new_width, new_height), Image.LANCZOS)
# 중앙 기준 crop
left= (new_width-size) //2
top= (new_height-size) //2
right=left+size
bottom=top+size
image=image.crop((left, top, right, bottom))
# WebP 포맷으로 저장 (품질 30%, 최적화 옵션 적용)
image.save(resized_path, format='WEBP', quality=quality, optimize=True)
defdelete_existing_thumbnails(bucket, prefix):
"""prefix 경로에 있는 모든 객체 삭제"""
response=s3_client.list_objects_v2(Bucket=bucket, Prefix=prefix)
if'Contents'inresponse:
objects_to_delete= [{'Key': obj['Key']} forobjinresponse['Contents']]
ifobjects_to_delete:
s3_client.delete_objects(
Bucket=bucket,
Delete={'Objects': objects_to_delete}
)
deflambda_handler(event, context):
"""
event 예시 구조:
{
"bucket": "원본 이미지가 저장된 버킷",
"key": "원본 이미지의 키 (S3 경로)"
}
"""
download_path=None
upload_path=None
filename=None
try:
bucket=event['bucket']
key=event['key']
post_id=key.split('/')[1]
ifnotpost_id.isdigit():
error_msg=f"Post id not in format: {key}"
print(error_msg)
return {
"statusCode": 400,
"body": error_msg
}
filename=os.path.basename(key)
base_name=filename.rsplit('.', 1)[0]
ext=filename.lower().rsplit('.', 1)[-1]
thumb_filename=f"thumbnail-{base_name}.webp"
download_path=f'/tmp/{filename}'
upload_path=f'/tmp/{thumb_filename}'
# 기존 썸네일 삭제
thumbnail_prefix=f'post-thumbnail/{post_id}/'
delete_existing_thumbnails(thumbnail_bucket, thumbnail_prefix)
print(f"Deleted existing thumbnails under {thumbnail_prefix}")
iffilename=="":
# 빈 파일명 - 썸네일 삭제 성공 (최적화 작업이 아니므로 SQS 전송 안함)
return {
"statusCode": 200,
"body": "Thumbnail deleted successfully."
}
else:
# 원본 이미지 다운로드
s3_client.download_file(bucket, key, download_path)
print(f"Downloaded original image {key} from bucket {bucket}")
# 썸네일 생성
ifextinIMG_EXT_LIST:
create_thumbnail_image(download_path, upload_path)
elifextinVDO_EXT_LIST:
create_video_thumbnail_image(download_path, upload_path)
else:
error_msg=f"Attachment extension {ext} unsupported: {filename}"
return {
"statusCode": 400,
"body": error_msg
}
print(f"Thumbnail created at {upload_path}")
# 썸네일 업로드
thumb_key=f'post-thumbnail/{post_id}/{thumb_filename}'
withopen(upload_path, 'rb') asf:
s3_client.upload_fileobj(
f,
thumbnail_bucket,
thumb_key,
ExtraArgs={
'ContentType': 'image/webp',
'ACL': 'public-read',
'CacheControl': 'public, max-age=31536000'
}
)
print(f"Uploaded thumbnail to {thumbnail_bucket}/{thumb_key}")
return {
"statusCode": 200,
"body": f"Thumbnail created successfully: {thumb_key}"
}
exceptExceptionase:
print(f"Error processing {key}: {e}")
return {
"statusCode": 500,
"body": f"Failed to create thumbnail: {str(e)}"
}
finally:
forpathin [download_path, upload_path]:
try:
ifpathandos.path.exists(path):
os.remove(path)
except:
# 파일 삭제 오류 무시
pass