-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
271 lines (210 loc) · 7.27 KB
/
__init__.py
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
"""Hugging Face Transformers plugin.
| Copyright 2017-2024, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
import importlib
import fiftyone as fo
import fiftyone.core.utils as fou
import fiftyone.operators as foo
import fiftyone.operators.types as types
import fiftyone.zoo as foz
hfh = fou.lazy_import("huggingface_hub")
transformers = fou.lazy_import("transformers")
task_map = {
"Image Classification": ["ForImageClassification"],
"Object Detection": ["ForObjectDetection"],
"Depth Estimation": ["ForDepthEstimation"],
"Image Segmentation": [
"ForSemanticSegmentation",
"ForInstanceSegmentation",
"ForSegmentation",
"ForUniversalSegmentation",
],
}
task_to_zoo_map = {
"Image Classification": "classification-transformer-torch",
"Object Detection": "detection-transformer-torch",
"Depth Estimation": "depth-estimation-transformer-torch",
"Image Segmentation": "segmentation-transformer-torch",
}
def _get_model_arch_for_pattern(task_pattern):
all_models = dir(transformers.models)
architecture_strings = []
for model_name in all_models:
try:
# Dynamically import the module
module = importlib.import_module(
f"transformers.models.{model_name}"
)
attrs = dir(module)
for attr in attrs:
if attr.endswith(task_pattern) and not attr.startswith(
"AutoModel"
):
architecture_strings.append(attr)
except:
continue
return architecture_strings
def get_model_architectures(task):
task_patterns = task_map[task]
all_architectures = []
for task_pattern in task_patterns:
architectures = _get_model_arch_for_pattern(task_pattern)
all_architectures.extend(architectures)
return sorted(list(set(all_architectures)))
def get_model_names(architecture_string):
model_class = getattr(transformers, architecture_string)
model_name = model_class.base_model_prefix.replace("_", "-")
api = hfh.HfApi()
models = api.list_models(model_name=model_name, limit=25)
model_names = [model.modelId for model in models]
return model_names
def _execution_mode(ctx, inputs):
delegate = ctx.params.get("delegate", False)
if delegate:
description = "Uncheck this box to execute the operation immediately"
else:
description = "Check this box to delegate execution of this task"
inputs.bool(
"delegate",
default=False,
required=True,
label="Delegate execution?",
description=description,
view=types.CheckboxView(),
)
if delegate:
inputs.view(
"notice",
types.Notice(
label=(
"You've chosen delegated execution. Note that you must "
"have a delegated operation service running in order for "
"this task to be processed. See "
"https://docs.voxel51.com/plugins/index.html#operators "
"for more information"
)
),
)
def _get_fields_with_type(view, type):
if issubclass(type, fo.Field):
return list(view.get_field_schema(ftype=type).keys())
return list(view.get_field_schema(embedded_doc_type=type).keys())
def _apply_transformer_model_inputs(ctx, inputs):
task_group = types.RadioGroup()
for task in task_map.keys():
task_group.add_choice(task, label=task)
inputs.enum(
"task",
task_group.values(),
label="Task",
description="Select the task for which you want to apply the model",
view=types.DropdownView(),
required=False,
)
task = ctx.params.get("task", None)
if task is None:
inputs.str("no_task", required=True, view=types.HiddenView())
return inputs
architectures = get_model_architectures(task)
arch_group = types.RadioGroup()
for arch in architectures:
arch_group.add_choice(arch, label=arch)
inputs.enum(
"architecture",
arch_group.values(),
label="Architecture",
description="Select the architecture of the model",
view=types.DropdownView(),
required=False,
)
arch = ctx.params.get("architecture", None)
if arch is None:
inputs.str(
"no_model_architecture", required=True, view=types.HiddenView()
)
return inputs
model_names = get_model_names(arch)
model_group = types.RadioGroup()
for model in model_names:
model_group.add_choice(model, label=model)
inputs.enum(
"model_name",
model_group.values(),
label="Model Name",
description="Select the model name",
view=types.DropdownView(),
required=False,
)
model_name = ctx.params.get("model_name", None)
if model_name is None:
inputs.str("no_model_name", required=True, view=types.HiddenView())
return inputs
inputs.view_target(ctx)
target_view = ctx.target_view()
label_field_choices = types.AutocompleteView()
for field in _get_fields_with_type(target_view, fo.Label):
label_field_choices.add_choice(field, label=field)
inputs.str(
"label_field",
required=True,
label="Label field",
description=(
"The name of a new or existing field in which to store the "
"predictions"
),
view=label_field_choices,
)
inputs.int(
"batch_size",
label="Batch size",
description="Batch size to use when applying the model",
required=False,
)
inputs.bool(
"skip_failures",
label="Skip failures",
description="Whether to gracefully continue without raising an error if predictions cannot be generated for a sample",
default=True,
)
return inputs
def _apply_transformer_model(ctx):
target_view = ctx.target_view()
label_field = ctx.params.get("label_field", None)
task = ctx.params.get("task")
zoo_name = task_to_zoo_map[task]
name_or_path = ctx.params.get("model_name")
batch_size = ctx.params.get("batch_size", None)
skip_failures = ctx.params.get("skip_failures", True)
delegate = ctx.params.get("delegate", False)
num_workers = None if delegate else 0
model = foz.load_zoo_model(zoo_name, name_or_path=name_or_path)
target_view.apply_model(
model,
label_field=label_field,
batch_size=batch_size,
num_workers=num_workers,
skip_failures=skip_failures,
)
ctx.ops.reload_dataset()
class ApplyTransformerModel(foo.Operator):
@property
def config(self):
_config = foo.OperatorConfig(
name="apply_transformer_model",
label="🤗 Apply Transformer model 🤗",
dynamic=True,
)
return _config
def resolve_input(self, ctx):
inputs = types.Object()
_apply_transformer_model_inputs(ctx, inputs)
_execution_mode(ctx, inputs)
return types.Property(inputs)
def execute(self, ctx):
_apply_transformer_model(ctx)
def resolve_delegation(self, ctx):
return ctx.params.get("delegate", False)
def register(plugin):
plugin.register(ApplyTransformerModel)