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_function2.py
More file actions
Latest commit
329 lines (289 loc) · 12.9 KB
/
Copy pathlambda_function2.py
File metadata and controls
329 lines (289 loc) · 12.9 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
importos
importjson
importtempfile
importshutil
importlogging
importtime
importcv2
importrandom
importboto3
importbotocore
frombotocore.exceptionsimportClientError
fromconcurrent.futuresimportThreadPoolExecutor, as_completed
fromtypingimportList, Tuple, Optional, Dict, Any
fromscenedetectimportopen_video, SceneManager
fromscenedetect.detectorsimportContentDetector
fromsupabaseimportcreate_client
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: "
"S3_BUCKET_VIDEOS, S3_BUCKET_FRAMES, SUPABASE_URL, SUPABASE_KEY")
# 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', '3'))
SCENE_THRESHOLD=float(os.getenv('SCENE_THRESHOLD', '27.0'))
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'
DEBUG_DEEP=os.getenv('DEBUG_DEEP', 'false').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_client=boto3.client('s3', region_name=AWS_REGION, config=botocore_cfg)
supabase=create_client(SUPABASE_URL, SUPABASE_KEY)
root_logger=logging.getLogger()
ifDEBUG_DEEP:
root_logger.setLevel(logging.DEBUG)
elifDEBUG:
root_logger.setLevel(logging.INFO)
else:
root_logger.setLevel(logging.WARNING)
classShortcodeFilter(Filter):
deffilter(self, record):
record.shortcode=getattr(record, 'shortcode', '-')
returnTrue
handler=StreamHandler()
handler.addFilter(ShortcodeFilter())
handler.setFormatter(Formatter("%(asctime)s %(levelname)s [%(shortcode)s] %(message)s"))
root_logger.handlers= [handler]
defget_logger(shortcode: Optional[str] =None) ->LoggerAdapter:
returnLoggerAdapter(root_logger, {'shortcode': shortcodeor'-'})
# ─── Supabase Helpers ─────────────────────────────────────────────────────────
deffetch_video_info(code: str) ->Tuple[bool, bool]:
log=get_logger(code)
try:
resp= (supabase.table('insta_content')
.select('is_downloaded,is_extracted')
.eq('code', code)
.maybe_single()
.execute())
row=resp.data
ifnotrow:
log.info("No record found")
returnFalse, False
returnbool(row['is_downloaded']), bool(row['is_extracted'])
exceptExceptionase:
log.error(f"Supabase fetch error: {e}")
returnFalse, False
defupdate_supabase_extracted(code: str, frame_count: int) ->None:
log=get_logger(code)
try:
supabase.table('insta_content') \
.update({'is_extracted': True, 'frames': frame_count}) \
.eq('code', code) \
.execute()
log.info(f"Marked is_extracted, frames={frame_count}")
exceptExceptionase:
log.error(f"Error marking extracted: {e}")
# ─── S3 Helpers ───────────────────────────────────────────────────────────────
defs3_video_exists(platform: str, code: str) ->bool:
key=f"{platform}/{code}/video.mp4"
try:
s3_client.head_object(Bucket=S3_BUCKET_VIDEOS, 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, local_path=tempfile.mkstemp(suffix='.mp4')
os.close(fd)
try:
s3_client.download_file(S3_BUCKET_VIDEOS, key, local_path)
log.info(f"Downloaded {key} (attempt {attempt})")
returnlocal_path
exceptExceptionase:
log.error(f"Download attempt {attempt} failed: {e}")
ifos.path.exists(local_path):
os.remove(local_path)
ifattempt<S3_RETRIES:
time.sleep(S3_RETRY_DELAY_MS/1000.0)
log.error(f"All download attempts failed for {key}")
returnNone
defupload_frames(paths: List[str], platform: str, code: str, record_error) ->bool:
log=get_logger(code)
def_upload(path: str) ->bool:
name=os.path.basename(path)
key=f"{platform}/{code}/frames/{name}"
backoff=1.0
ifnotos.path.exists(path) oros.path.getsize(path) ==0:
msg=f"Local frame missing or empty: {path}"
record_error(msg)
returnFalse
forattemptinrange(1, S3_RETRIES+1):
try:
s3_client.upload_file(path, S3_BUCKET_FRAMES, key)
os.remove(path)
log.info(f"Uploaded {key} (attempt {attempt})")
returnTrue
exceptExceptionase:
msg=f"S3 upload error on attempt {attempt}: {e}"
log.error(msg)
record_error(msg)
ifattempt<S3_RETRIES:
sleep=backoff* (1+random.random()*0.1)
time.sleep(sleep)
backoff*=2
record_error(f"Failed all {S3_RETRIES} uploads for {key}")
returnFalse
withThreadPoolExecutor(max_workers=S3_UPLOAD_THREADS) aspool:
results=pool.map(_upload, paths)
returnall(results)
# ─── Frame Extraction ────────────────────────────────────────────────────────
defdetect_scenes(video_path: str) ->List[Tuple[Any,Any]]:
manager=SceneManager()
manager.add_detector(ContentDetector(threshold=SCENE_THRESHOLD))
manager.detect_scenes(open_video(video_path))
returnmanager.get_scene_list()
defextract_key_frames(
video_path: str,
out_dir: str,
context,
code: str,
record_error
) ->List[str]:
log=get_logger(code)
# Timeout guard
ifcontextandcontext.get_remaining_time_in_millis() <MIN_REMAINING_MS:
record_error("Aborted: low remaining time")
return []
cap=cv2.VideoCapture(video_path)
ifnotcap.isOpened():
record_error("Cannot open video")
return []
try:
scenes=detect_scenes(video_path)
exceptExceptionase:
record_error(f"Scene detection failed: {e}")
cap.release()
return []
total_frames=int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
indices= [
(s.get_frames()+e.get_frames())//2
fors,einscenes
]
iflen(indices) <MIN_FRAMES:
step=max(1, total_frames// (MIN_FRAMES+1))
fallback= [i*stepforiinrange(1, MIN_FRAMES+1)]
indices=sorted(set(indices+fallback))
os.makedirs(out_dir, exist_ok=True)
saved= []
foridx, frame_noinenumerate(indices):
ifframe_no<0orframe_no>=total_frames:
record_error(f"Frame {frame_no} out of bounds")
continue
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_no)
ret, frame=cap.read()
ifnotretorframeisNone:
record_error(f"Failed to read frame at {frame_no}")
continue
path=os.path.join(out_dir, f"{idx}.jpg")
ifnotcv2.imwrite(path, frame):
record_error(f"cv2.imwrite failed at frame {frame_no}")
continue
saved.append(path)
cap.release()
log.info(f"Extracted {len(saved)} frames")
returnsaved
# ─── Record Processing ───────────────────────────────────────────────────────
defprocess_record(record, context):
# now each record.body = '{"items":[{"platform":"instagram","code":"ABC123"},…]}'
batch=json.loads(record.get('body','{}')).get('items', [])
results= []
foriteminbatch:
results.append(process_single(item['platform'], item['code'], context))
returnresults
defprocess_single(platform: str, code: str, context) ->Dict[str,Any]:
log=get_logger(code)
errors: List[str] = []
defrecord_error(msg: str):
errors.append(msg)
# 1) Quick timeout bail-out
ifcontextandcontext.get_remaining_time_in_millis() <MIN_REMAINING_MS:
record_error("Skipped: low remaining time at start")
status= {'status':'skipped','shortcode':code}
else:
# 2) Check S3
try:
ifnots3_video_exists(platform, code):
record_error("Video not found in S3")
supabase.table('insta_content') \
.update({'is_downloaded': False}) \
.eq('code', code).execute()
status= {'status':'skipped','shortcode':code}
else:
# 3) Download
path=download_video(platform, code)
ifnotpath:
record_error("Download failed")
status= {'status':'skipped','shortcode':code}
else:
# 4) DB state
downloaded, extracted=fetch_video_info(code)
ifextracted:
record_error("Already extracted")
status= {'status':'skipped','shortcode':code}
else:
# 5) Extract & upload
tmp=tempfile.mkdtemp()
try:
frames=extract_key_frames(path, tmp, context, code, record_error)
ifnotframesornotupload_frames(frames, platform, code, record_error):
raiseRuntimeError("Extraction/upload failure")
update_supabase_extracted(code, len(frames))
status= {'status':'extracted','shortcode':code,'frames':len(frames)}
exceptExceptionase:
record_error(str(e))
status= {'status':'error','shortcode':code,'message':str(e)}
finally:
shutil.rmtree(tmp, ignore_errors=True)
os.remove(path)
exceptExceptionase:
record_error(f"Unexpected error: {e}")
status= {'status':'error','shortcode':code,'message':str(e)}
# 6) Persist all errors
iferrors:
try:
supabase.table('extraction_errors') \
.insert([{'code':code,'error':msg} formsginerrors]) \
.execute()
exceptExceptionase:
log.error(f"Failed to persist errors: {e}")
returnstatus
# ─── Lambda Entry Point ─────────────────────────────────────────────────────
deflambda_handler(event, context):
raw=event.get('Records', [])
results= []
withThreadPoolExecutor(max_workers=CONCURRENCY_LIMIT) aspool:
futures= []
forrecinraw:
try:
body=json.loads(rec.get('body','{}'))
items=body.get('items', [])
foritinitems:
futures.append(
pool.submit(process_single, it.get('platform',''), it.get('code',''), context)
)
exceptExceptionase:
get_logger().error(f"Bad SQS payload: {e}")
forfinas_completed(futures):
results.append(f.result())
return {'status':'completed', 'results': results}