Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
FramesEmbeddingsExtractor-lambda/lambda_function.py at main · orianexxx/FramesEmbeddingsExtractor-lambda · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Uh oh!
There was an error while loading.
Please reload this page
.
orianexxx
/
FramesEmbeddingsExtractor-lambda
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Files
Expand file tree
main
Breadcrumbs
FramesEmbeddingsExtractor-lambda
/
lambda_function.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
159 lines (140 loc) · 6.77 KB
main
Breadcrumbs
FramesEmbeddingsExtractor-lambda
/
lambda_function.py
Copy path
Top
File metadata and controls
Code
Blame
159 lines (140 loc) · 6.77 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#!/usr/bin/env python
"""
Serverless-compatible Lambda for embedding videos → OpenSearch
• Idempotent via logical _id
• No delete_by_query
• Bulk with refresh=False, then one final refresh
"""
import
os
,
json
,
base64
,
logging
,
pathlib
,
boto3
,
numpy
as
np
from
concurrent
.
futures
import
ThreadPoolExecutor
,
as_completed
from
typing
import
List
from
dotenv
import
load_dotenv
from
opensearchpy
import
OpenSearch
,
helpers
,
RequestsHttpConnection
from
requests_aws4auth
import
AWS4Auth
from
supabase
import
create_client
load_dotenv
()
# ─── 1. CONFIG ─────────────────────────────────────────────────────────
S3_BUCKET_FRAMES
=
os
.
getenv
(
"S3_BUCKET_FRAMES"
,
"oriane-contents"
)
MODEL_ID
=
os
.
getenv
(
"MODEL_ID"
,
"amazon.titan-embed-image-v1"
)
AWS_REGION
=
os
.
getenv
(
"AWS_REGION"
,
"us-east-1"
)
EMB_DIM
=
int
(
os
.
getenv
(
"EMB_DIM"
,
"1024"
))
MAX_BATCH
=
int
(
os
.
getenv
(
"MAX_FRAMES_PER_BATCH"
,
"20"
))
CONCURRENCY_LIMIT
=
int
(
os
.
getenv
(
"CONCURRENCY_LIMIT"
,
"4"
))
SUPABASE_URL
=
os
.
getenv
(
"SUPABASE_URL"
)
SUPABASE_KEY
=
os
.
getenv
(
"SUPABASE_KEY"
)
OS_ENDPOINT
=
os
.
getenv
(
"OS_ENDPOINT"
)
LOG_LEVEL
=
os
.
getenv
(
"LOG_LEVEL"
,
"INFO"
).
upper
()
for
var
in
(
"SUPABASE_URL"
,
"SUPABASE_KEY"
,
"OS_ENDPOINT"
):
if
not
globals
()[
var
]:
raise
RuntimeError
(
f"
{
var
}
is required"
)
# ─── 2. LOGGING & CLIENTS ───────────────────────────────────────────────
logging
.
basicConfig
(
level
=
LOG_LEVEL
,
format
=
"%(asctime)s %(levelname)s %(message)s"
)
def
get_log
(
code
:
str
):
lg
=
logging
.
getLogger
(
f"embed[
{
code
}
]"
)
if
not
lg
.
handlers
:
h
=
logging
.
StreamHandler
()
h
.
setFormatter
(
logging
.
Formatter
(
"%(asctime)s %(levelname)s [%(name)s] %(message)s"
))
lg
.
addHandler
(
h
)
lg
.
setLevel
(
LOG_LEVEL
)
return
lg
session
=
boto3
.
Session
(
region_name
=
AWS_REGION
)
s3
=
session
.
client
(
"s3"
)
bedrock
=
session
.
client
(
"bedrock-runtime"
)
supabase
=
create_client
(
SUPABASE_URL
,
SUPABASE_KEY
)
creds
=
session
.
get_credentials
()
auth
=
AWS4Auth
(
creds
.
access_key
,
creds
.
secret_key
,
AWS_REGION
,
"aoss"
,
session_token
=
creds
.
token
)
host
=
OS_ENDPOINT
.
split
(
"://"
,
1
)[
-
1
].
rstrip
(
"/"
)
os_client
=
OpenSearch
(
hosts
=
[{
"host"
:
host
,
"port"
:
443
}],
http_auth
=
auth
,
use_ssl
=
True
,
verify_certs
=
True
,
connection_class
=
RequestsHttpConnection
,
)
# ─── 3. HELPERS ─────────────────────────────────────────────────────────
def
list_frame_keys
(
platform
:
str
,
code
:
str
)
->
List
[
str
]:
pfx
=
f"
{
platform
}
/
{
code
}
/frames/"
pages
=
s3
.
get_paginator
(
"list_objects_v2"
).
paginate
(
Bucket
=
S3_BUCKET_FRAMES
,
Prefix
=
pfx
)
return
[
o
[
"Key"
]
for
pg
in
pages
for
o
in
pg
.
get
(
"Contents"
,[])
if
o
[
"Key"
].
endswith
(
".jpg"
)]
def
titan_embed
(
b64s
:
List
[
str
])
->
List
[
List
[
float
]]:
out
=
[]
for
b64
in
b64s
:
body
=
json
.
dumps
({
"inputImage"
:
b64
,
"embeddingConfig"
: {
"outputEmbeddingLength"
:
EMB_DIM
}})
rsp
=
bedrock
.
invoke_model
(
modelId
=
MODEL_ID
,
body
=
body
,
accept
=
"application/json"
,
contentType
=
"application/json"
)
emb
=
json
.
loads
(
rsp
[
"body"
].
read
())[
"embedding"
]
out
.
append
(
emb
)
return
out
def
bulk_gen
(
idx
:
str
,
docs
:
List
[
dict
]):
for
d
in
docs
:
yield
{
"index"
: {
"_index"
:
idx
,
"_id"
:
d
[
"_id"
]}}
yield
d
def
mark_video
(
code
:
str
,
**
fields
):
supabase
.
table
(
"insta_content"
).
update
(
fields
).
eq
(
"code"
,
code
).
execute
()
# ─── 4. PER-VIDEO EMBED ─────────────────────────────────────────────────
def
embed_video
(
platform
:
str
,
code
:
str
):
log
=
get_log
(
code
)
log
.
info
(
"Starting embedding"
)
keys
=
list_frame_keys
(
platform
,
code
)
if
not
keys
:
raise
RuntimeError
(
f"No frames for
{
code
}
"
)
video_id
=
f"
{
platform
}
.
{
code
}
"
frame_docs
,
vecs
=
[], []
for
i
in
range
(
0
,
len
(
keys
),
MAX_BATCH
):
chunk
=
keys
[
i
:
i
+
MAX_BATCH
]
try
:
b64s
=
[
base64
.
b64encode
(
s3
.
get_object
(
Bucket
=
S3_BUCKET_FRAMES
,
Key
=
k
)[
"Body"
].
read
()).
decode
()
for
k
in
chunk
]
embeds
=
titan_embed
(
b64s
)
except
Exception
as
e
:
for
k
in
chunk
:
idx
=
int
(
pathlib
.
Path
(
k
).
stem
)
supabase
.
table
(
"embedding_errors"
).
insert
({
"code"
:
code
,
"frame"
:
idx
,
"error"
:
str
(
e
)}).
execute
()
raise
for
k
,
v
in
zip
(
chunk
,
embeds
):
fno
=
int
(
pathlib
.
Path
(
k
).
stem
)
frame_docs
.
append
({
"_id"
:
f"
{
video_id
}
#
{
fno
}
"
,
"video_id"
:
video_id
,
"vector"
:
v
,
"platform"
:
platform
,
"code"
:
code
,
"frame"
:
fno
,
})
vecs
.
append
(
v
)
# upsert frames batch
helpers
.
bulk
(
os_client
,
bulk_gen
(
"video_frames"
,
frame_docs
),
refresh
=
False
)
# upsert summary
summary
=
{
"_id"
:
video_id
,
"video_id"
:
video_id
,
"vector"
:
np
.
mean
(
vecs
,
axis
=
0
).
tolist
(),
"platform"
:
platform
,
"code"
:
code
,
"frames"
:
len
(
vecs
),
}
helpers
.
bulk
(
os_client
,
bulk_gen
(
"videos"
, [
summary
]),
refresh
=
False
)
mark_video
(
code
,
is_embedded
=
True
)
log
.
info
(
"Indexed %d frames"
,
len
(
vecs
))
# ─── 5. RECORD HANDLER ───────────────────────────────────────────────────
def
already_embedded
(
code
:
str
)
->
bool
:
res
=
supabase
.
table
(
"insta_content"
).
select
(
"is_embedded"
).
eq
(
"code"
,
code
).
maybe_single
().
execute
()
return
bool
(
res
.
data
and
res
.
data
.
get
(
"is_embedded"
))
def
process_record
(
rec
:
dict
):
body
=
json
.
loads
(
rec
.
get
(
"body"
,
"{}"
))
platform
,
code
=
body
.
get
(
"platform"
),
body
.
get
(
"code"
)
if
not
platform
or
not
code
:
return
{
"code"
:
None
,
"status"
:
"invalid"
}
if
already_embedded
(
code
):
return
{
"code"
:
code
,
"status"
:
"skipped"
}
embed_video
(
platform
,
code
)
return
{
"code"
:
code
,
"status"
:
"done"
}
# ─── 6. LAMBDA HANDLER ──────────────────────────────────────────────────
def
lambda_handler
(
event
,
_
):
results
=
[]
with
ThreadPoolExecutor
(
max_workers
=
CONCURRENCY_LIMIT
)
as
pool
:
for
fut
in
as_completed
([
pool
.
submit
(
process_record
,
r
)
for
r
in
event
.
get
(
"Records"
,[])]):
results
.
append
(
fut
.
result
())
# one final refresh
os_client
.
indices
.
refresh
(
"video_frames"
)
os_client
.
indices
.
refresh
(
"videos"
)
return
{
"status"
:
"completed"
,
"results"
:
results
}
You can’t perform that action at this time.