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
350 lines (320 loc) · 12.8 KB
/
Copy pathlambda_function.py
File metadata and controls
350 lines (320 loc) · 12.8 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
importos
importjson
importtempfile
importshutil
importlogging
importtime
importsubprocess
importcv2
importnumpyasnp
importrandom
importboto3
importbotocore
fromglobimportglob
fromconcurrent.futuresimportThreadPoolExecutor, as_completed
fromtypingimportList, Tuple, Optional, Dict, Any
fromsupabaseimportcreate_client
frombotocore.exceptionsimportClientError
fromloggingimportLoggerAdapter, Filter, StreamHandler, Formatter
fromdotenvimportload_dotenv
# ─── Load & Validate Environment ─────────────────────────────────────────────
load_dotenv()
AWS_REGION=os.getenv('AWS_REGION', 'us-east-1')
S3_BUCKET_VIDEOS=os.getenv('S3_BUCKET_VIDEOS')
S3_BUCKET_FRAMES=os.getenv('S3_BUCKET_FRAMES')
SUPABASE_URL=os.getenv('SUPABASE_URL')
SUPABASE_KEY=os.getenv('SUPABASE_KEY')
ifnotall([S3_BUCKET_VIDEOS, S3_BUCKET_FRAMES, SUPABASE_URL, SUPABASE_KEY]):
raiseRuntimeError("Missing one of required env vars")
# Optional tuning
S3_RETRIES=int(os.getenv('S3_RETRIES', '3'))
S3_RETRY_DELAY_MS=int(os.getenv('S3_RETRY_DELAY', '1000'))
S3_CONNECT_TIMEOUT=int(os.getenv('S3_CONNECT_TIMEOUT', '10'))
S3_READ_TIMEOUT=int(os.getenv('S3_READ_TIMEOUT', '60'))
S3_UPLOAD_THREADS=int(os.getenv('S3_UPLOAD_THREADS', '4'))
MIN_FRAMES=int(os.getenv('MIN_FRAMES', '4'))
SCENE_THRESHOLD=float(os.getenv('SCENE_THRESHOLD', '0.12'))
IMAGE_CROP_TOL=int(os.getenv('IMAGE_CROP_TOL', '10'))
FFMPEG_PATH=os.getenv('FFMPEG_PATH', 'ffmpeg')
CONCURRENCY_LIMIT=int(os.getenv('CONCURRENCY_LIMIT', '2'))
MIN_REMAINING_MS=int(os.getenv('MIN_REMAINING_MS', '60000'))
DEBUG=os.getenv('DEBUG', 'true').lower() =='true'
# ─── Clients & Logging ────────────────────────────────────────────────────────
botocore_cfg=botocore.config.Config(
retries={'max_attempts': S3_RETRIES, 'mode': 'standard'},
connect_timeout=S3_CONNECT_TIMEOUT,
read_timeout=S3_READ_TIMEOUT,
)
s3=boto3.client('s3', region_name=AWS_REGION, config=botocore_cfg)
supabase=create_client(SUPABASE_URL, SUPABASE_KEY)
root=logging.getLogger()
root.setLevel(logging.DEBUGifDEBUGelselogging.INFO)
handler=StreamHandler()
handler.setFormatter(Formatter("%(asctime)s %(levelname)s [%(shortcode)s] %(message)s"))
root.handlers= [handler]
classShortcodeFilter(Filter):
deffilter(self, record):
record.shortcode=getattr(record, 'shortcode', '-')
returnTrue
handler.addFilter(ShortcodeFilter())
defget_logger(code: Optional[str]=None) ->LoggerAdapter:
returnLoggerAdapter(root, {'shortcode': codeor'-'})
# ─── S3 + DB Helpers ──────────────────────────────────────────────────────────
defs3_key_exists(bucket: str, key: str) ->bool:
try:
s3.head_object(Bucket=bucket, Key=key)
returnTrue
exceptClientErrorase:
ife.response['Error']['Code'] in ('404', 'NoSuchKey'):
returnFalse
raise
defdownload_video(platform: str, code: str) ->Optional[str]:
log=get_logger(code)
key=f"{platform}/{code}/video.mp4"
forattemptinrange(1, S3_RETRIES+1):
fd, tmp_path=tempfile.mkstemp(suffix='.mp4')
os.close(fd)
try:
s3.download_file(S3_BUCKET_VIDEOS, key, tmp_path)
log.info(f"Downloaded {key}")
returntmp_path
exceptExceptionase:
log.error(f"Download attempt {attempt} failed: {e}")
ifos.path.exists(tmp_path):
os.remove(tmp_path)
ifattempt<S3_RETRIES:
time.sleep(S3_RETRY_DELAY_MS/1000.0)
log.error(f"All downloads failed for {key}")
returnNone
defupload_frame(path: str, platform: str, code: str, errors: List[str]) ->bool:
key=f"{platform}/{code}/frames/{os.path.basename(path)}"
forattemptinrange(1, S3_RETRIES+1):
try:
s3.upload_file(path, S3_BUCKET_FRAMES, key)
os.remove(path)
returnTrue
exceptExceptionase:
msg=f"Upload error attempt {attempt} for {key}: {e}"
errors.append(msg)
ifattempt<S3_RETRIES:
time.sleep((2**attempt) * (1+random.random()*0.1))
errors.append(f"Failed to upload {key}")
returnFalse
defupdate_db_extracted(code: str, count: int):
supabase.table('insta_content') \
.update({'is_extracted': True, 'frames': count}) \
.eq('code', code) \
.execute()
defrecord_errors(code: str, errors: List[str]):
ifnoterrors:
return
rows= [{'code': code, 'error': e} foreinerrors]
supabase.table('extraction_errors').insert(rows).execute()
# ─── Frame-Extraction Helpers ─────────────────────────────────────────────────
defdetect_image_crop(img: np.ndarray, tol: int=IMAGE_CROP_TOL):
h, w=img.shape[:2]
defis_blank_line(line: np.ndarray) ->bool:
"""All pixels within tol of this line's median color?"""
median_col=np.median(line, axis=0)
diffs=np.abs(line.astype(int) -median_col.astype(int)).sum(axis=1)
returnnp.all(diffs<=tol)
# left
x0=0
forxinrange(w):
ifis_blank_line(img[:, x, :]):
x0+=1
else:
break
# right
x1=w
forxinrange(w-1, -1, -1):
ifis_blank_line(img[:, x, :]):
x1-=1
else:
break
# top
y0=0
foryinrange(h):
ifis_blank_line(img[y, :, :]):
y0+=1
else:
break
# bottom
y1=h
foryinrange(h-1, -1, -1):
ifis_blank_line(img[y, :, :]):
y1-=1
else:
break
# if nothing left, no crop
ifx0>=x1ory0>=y1:
returnNone
return (x0, y0, x1-x0, y1-y0)
defffmpeg_extract_with_pts(video_path: str, out_dir: str, threshold: float):
os.makedirs(out_dir, exist_ok=True)
pattern=os.path.join(out_dir, '%d.jpg')
cmd= [
FFMPEG_PATH, '-hide_banner', '-loglevel', 'error',
'-i', video_path,
'-vf', f"select='gt(scene,{threshold})'",
'-vsync', 'vfr', '-frame_pts', '1', '-q:v', '2',
pattern
]
subprocess.run(cmd, check=True)
imgs= []
forfileinglob(os.path.join(out_dir, '*.jpg')):
frame_no=int(os.path.splitext(os.path.basename(file))[0])
imgs.append((file, frame_no))
imgs.sort(key=lambdax: x[1])
returnimgs
defextract_key_frames(video_path: str, out_dir: str, code: str, errors: List[str]):
log=get_logger(code)
# FFmpeg pass
raw=ffmpeg_extract_with_pts(video_path, out_dir, SCENE_THRESHOLD)
log.info(f"FFmpeg detected {len(raw)} scenes")
# Probe FPS
cap=cv2.VideoCapture(video_path)
fps=cap.get(cv2.CAP_PROP_FPS) or25.0
cap.release()
# Crop, drop fully-blank, rename
saved=0
forold_path, frame_noinraw:
img=cv2.imread(old_path)
ifimgisNone:
os.remove(old_path)
continue
rect=detect_image_crop(img)
ifrect:
x,y,w,h=rect
img=img[y:y+h, x:x+w]
gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ifnp.all(gray==gray[0,0]):
os.remove(old_path)
continue
seconds=frame_no/fps
new=os.path.join(out_dir, f"{saved+1}_{seconds:.2f}.jpg")
cv2.imwrite(new, img)
os.remove(old_path)
saved+=1
# Fallback sampling if too few frames
ifsaved<MIN_FRAMES:
log.info("Fallback to OpenCV sampling")
cap=cv2.VideoCapture(video_path)
total=int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
step=max(1, total//(MIN_FRAMES+1))
foriinrange(1, MIN_FRAMES+1):
ifsaved>=MIN_FRAMES:
break
fn=i*step
cap.set(cv2.CAP_PROP_POS_FRAMES, fn)
ret, frame=cap.read()
ifnotret:
continue
# optional crop
rect=detect_image_crop(frame)
ifrect:
x,y,w,h=rect
frame=frame[y:y+h, x:x+w]
# drop fully-blank
gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ifnp.all(gray==gray[0,0]):
continue
# save
sec=fn/fps
out=os.path.join(out_dir, f"{saved+1}_{sec:.2f}.jpg")
cv2.imwrite(out, frame)
saved+=1
cap.release()
log.info(f"Total after fallback: {saved}")
else:
log.info(f"Kept {saved} frames (>= {MIN_FRAMES})")
# if we STILL got nothing, error out
ifsaved==0:
raiseRuntimeError("No frames extracted (FFmpeg & fallback both failed)")
return [os.path.join(out_dir, f) forfinos.listdir(out_dir) iff.endswith('.jpg')]
# ─── Core Processing ──────────────────────────────────────────────────────────
defprocess_single(item: Dict[str,str], context) ->Dict[str,Any]:
platform, code=item['platform'], item['code']
log=get_logger(code)
errors: List[str] = []
status= {}
# Timeout guard
ifcontextandcontext.get_remaining_time_in_millis() <MIN_REMAINING_MS:
errors.append("Timeout: low remaining time")
status= {'shortcode': code, 'status': 'skipped'}
else:
# Check S3 source
ifnots3_key_exists(S3_BUCKET_VIDEOS, f"{platform}/{code}/video.mp4"):
errors.append("Source video missing")
status= {'shortcode': code, 'status': 'skipped'}
else:
vid=download_video(platform, code)
ifnotvid:
errors.append("Download failed")
status= {'shortcode': code, 'status': 'skipped'}
else:
tmpdir=tempfile.mkdtemp()
try:
frames=extract_key_frames(vid, tmpdir, code, errors)
ok=True
# upload with ThreadPool
withThreadPoolExecutor(max_workers=S3_UPLOAD_THREADS) aspool:
futures= [ pool.submit(upload_frame, p, platform, code, errors) forpinframes ]
forfinas_completed(futures):
ifnotf.result():
ok=False
ifnotok:
raiseRuntimeError("One or more uploads failed")
update_db_extracted(code, len(frames))
status= {'shortcode': code, 'status': 'extracted', 'frames': len(frames)}
exceptExceptionase:
log.error(f"Processing error: {e}")
errors.append(str(e))
status= {'shortcode': code, 'status': 'error', 'message': str(e)}
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
os.remove(vid)
# persist errors
record_errors(code, errors)
returnstatus
deflambda_handler(event, context):
# Support two shapes:
# 1) API-style: { "items": [ { platform, code }, … ] }
# 2) SQS-style: { "Records": [ { body: '{"platform":"…","code":"…"}' }, … ] }
if"items"inevent:
items=event["items"]
elif"Records"inevent:
items= []
forrecinevent["Records"]:
try:
body=rec.get("body", "")
data=json.loads(body)
# if body itself has an "items" array, unpack it; else treat as single item
ifisinstance(data, dict) and"items"indata:
items.extend(data["items"])
else:
items.append(data)
exceptException:
# ignore bad record
continue
else:
items= []
results= []
# Sequential processing (no threads)
foriteminitems:
try:
res=process_single(item, context)
exceptExceptionase:
# Catch any unexpected error so one bad video
# doesn't abort the whole batch
get_logger(item.get('code')).error(f"Unhandled error: {e}")
res= {
'shortcode': item.get('code'),
'status': 'error',
'message': str(e)
}
results.append(res)
return {
'status': 'completed',
'results': results
}