FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
feast/sdk/python/feast/embedder.py at v0.63.0 · feast-dev/feast · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
feast-dev
/
feast
Public
Notifications
You must be signed in to change notification settings
Fork
1.4k
Star
7.2k
Code
Issues
215
Pull requests
190
Discussions
Actions
Security and quality
1
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Security and quality
Insights
Expand file tree
Breadcrumbs
feast
/
sdk
/
python
/
feast
/
embedder.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
241 lines (190 loc) · 7.67 KB
Breadcrumbs
feast
/
sdk
/
python
/
feast
/
embedder.py
Copy path
File metadata and controls
241 lines (190 loc) · 7.67 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
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
from
abc
import
ABC
,
abstractmethod
from
dataclasses
import
dataclass
from
typing
import
TYPE_CHECKING
,
Any
,
Callable
,
List
,
Optional
if
TYPE_CHECKING
:
import
numpy
as
np
import
pandas
as
pd
@
dataclass
class
EmbeddingConfig
:
batch_size
:
int
=
64
show_progress
:
bool
=
True
class
BaseEmbedder
(
ABC
):
"""
Abstract base class for embedding generation.
Supports multiple modalities via routing.
Users can register custom modality handlers.
"""
def
__init__
(
self
,
config
:
Optional
[
EmbeddingConfig
]
=
None
):
self
.
config
=
config
or
EmbeddingConfig
()
# Registry: modality -> embedding function
self
.
_modality_handlers
:
dict
[
str
,
Callable
[[
List
[
Any
]],
"np.ndarray"
]]
=
{}
# Register default modalities (subclass can override)
self
.
_register_default_modalities
()
def
_register_default_modalities
(
self
)
->
None
:
"""Override in subclass to register default modality handlers."""
pass
def
register_modality
(
self
,
modality
:
str
,
handler
:
Callable
[[
List
[
Any
]],
"np.ndarray"
],
)
->
None
:
"""
Register a handler for a modality.
Args:
modality: Name of modality ("text", "image", "video", etc.)
handler: Function that takes list of inputs and returns embeddings.
"""
self
.
_modality_handlers
[
modality
]
=
handler
@
property
def
supported_modalities
(
self
)
->
List
[
str
]:
"""Return list of supported modalities."""
return
list
(
self
.
_modality_handlers
.
keys
())
def
get_embedding_dim
(
self
,
modality
:
str
)
->
Optional
[
int
]:
"""
Return the embedding dimension for a given modality.
Subclasses should override this to return the actual dimension
so that auto-generated FeatureView schemas use the correct vector_length.
Args:
modality: The modality to query (e.g. "text", "image").
Returns:
The embedding dimension, or None if unknown.
"""
return
None
@
abstractmethod
def
embed
(
self
,
inputs
:
List
[
Any
],
modality
:
str
)
->
"np.ndarray"
:
"""
Generate embeddings for inputs of a given modality.
Args:
inputs: List of inputs.
modality: Type of content ("text", "image", "video", etc.)
Returns:
numpy array of shape (len(inputs), embedding_dim)
"""
pass
def
embed_dataframe
(
self
,
df
:
pd
.
DataFrame
,
column_mapping
:
dict
[
str
,
tuple
[
str
,
str
]],
)
->
pd
.
DataFrame
:
"""
Add embeddings for multiple columns with modality routing.
Args:
df: Input DataFrame.
column_mapping: Dict mapping source_column -> (modality, output_column).
Example: {
"text": ("text", "text_embedding"),
"image_path": ("image", "image_embedding"),
"video_path": ("video", "video_embedding"),
}
"""
df
=
df
.
copy
()
for
source_column
, (
modality
,
output_column
)
in
column_mapping
.
items
():
inputs
=
df
[
source_column
].
tolist
()
embeddings
=
self
.
embed
(
inputs
,
modality
)
df
[
output_column
]
=
pd
.
Series
(
[
emb
.
tolist
()
for
emb
in
embeddings
],
dtype
=
object
,
index
=
df
.
index
)
return
df
class
MultiModalEmbedder
(
BaseEmbedder
):
"""
Multi-modal embedder with built-in support for common modalities.
Supports: text, image, video (extensible)
"""
def
__init__
(
self
,
text_model
:
str
=
"all-MiniLM-L6-v2"
,
image_model
:
str
=
"openai/clip-vit-base-patch32"
,
config
:
Optional
[
EmbeddingConfig
]
=
None
,
):
self
.
text_model_name
=
text_model
self
.
image_model_name
=
image_model
# Lazy-loaded models
self
.
_text_model
=
None
self
.
_image_model
=
None
self
.
_image_processor
=
None
super
().
__init__
(
config
)
def
_register_default_modalities
(
self
)
->
None
:
"""Register built-in modality handlers."""
self
.
register_modality
(
"text"
,
self
.
_embed_text
)
self
.
register_modality
(
"image"
,
self
.
_embed_image
)
# Future: add more as needed
# self.register_modality("video", self._embed_video)
# self.register_modality("audio", self._embed_audio)
def
embed
(
self
,
inputs
:
List
[
Any
],
modality
:
str
)
->
"np.ndarray"
:
"""Route to appropriate handler based on modality."""
if
modality
not
in
self
.
_modality_handlers
:
raise
ValueError
(
f"Unsupported modality: '
{
modality
}
'. "
f"Supported:
{
self
.
supported_modalities
}
"
)
handler
=
self
.
_modality_handlers
[
modality
]
return
handler
(
inputs
)
def
get_embedding_dim
(
self
,
modality
:
str
)
->
Optional
[
int
]:
"""
Return the embedding dimension for a given modality.
For "text", this queries the SentenceTransformer model's dimension
(which triggers lazy model loading).
Args:
modality: The modality to query (e.g. "text", "image").
Returns:
The embedding dimension, or None if unknown.
"""
if
modality
==
"text"
:
return
self
.
text_model
.
get_sentence_embedding_dimension
()
elif
modality
==
"image"
:
return
self
.
image_model
.
config
.
vision_config
.
hidden_size
return
None
# Text Embedding
@
property
def
text_model
(
self
):
if
self
.
_text_model
is
None
:
from
sentence_transformers
import
SentenceTransformer
self
.
_text_model
=
SentenceTransformer
(
self
.
text_model_name
)
return
self
.
_text_model
def
_embed_text
(
self
,
inputs
:
List
[
str
])
->
"np.ndarray"
:
return
self
.
text_model
.
encode
(
inputs
,
batch_size
=
self
.
config
.
batch_size
,
show_progress_bar
=
self
.
config
.
show_progress
,
)
# Image Embedding
@
property
def
image_model
(
self
):
if
self
.
_image_model
is
None
:
from
transformers
import
CLIPModel
self
.
_image_model
=
CLIPModel
.
from_pretrained
(
self
.
image_model_name
)
return
self
.
_image_model
@
property
def
image_processor
(
self
):
if
self
.
_image_processor
is
None
:
from
transformers
import
CLIPProcessor
self
.
_image_processor
=
CLIPProcessor
.
from_pretrained
(
self
.
image_model_name
)
return
self
.
_image_processor
def
_embed_image
(
self
,
inputs
:
List
[
Any
])
->
"np.ndarray"
:
from
pathlib
import
Path
import
numpy
as
np
from
PIL
import
Image
all_embeddings
:
List
[
"np.ndarray"
]
=
[]
batch_size
=
self
.
config
.
batch_size
for
start
in
range
(
0
,
len
(
inputs
),
batch_size
):
batch
=
inputs
[
start
:
start
+
batch_size
]
images
=
[]
opened
:
List
[
Image
.
Image
]
=
[]
try
:
for
inp
in
batch
:
if
isinstance
(
inp
, (
str
,
Path
)
):
# If the input string path is too large that It gives error and we could not open the image.
img
=
Image
.
open
(
inp
)
opened
.
append
(
img
)
images
.
append
(
img
)
else
:
images
.
append
(
inp
)
processed
=
self
.
image_processor
(
images
=
images
,
return_tensors
=
"pt"
)
finally
:
for
opened_img
in
opened
:
opened_img
.
close
()
embeddings
=
self
.
image_model
.
get_image_features
(
**
processed
)
embeddings
=
embeddings
/
embeddings
.
norm
(
p
=
2
,
dim
=
-
1
,
keepdim
=
True
)
all_embeddings
.
append
(
embeddings
.
detach
().
numpy
())
return
np
.
concatenate
(
all_embeddings
,
axis
=
0
)
Back
|
FazBrowse Home
|
New Git URL