clarifai 10.8.4__py3-none-any.whl → 10.8.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. clarifai/__init__.py +1 -1
  2. clarifai/client/dataset.py +9 -3
  3. clarifai/constants/dataset.py +1 -1
  4. clarifai/datasets/upload/base.py +6 -3
  5. clarifai/datasets/upload/features.py +10 -0
  6. clarifai/datasets/upload/image.py +22 -13
  7. clarifai/datasets/upload/multimodal.py +70 -0
  8. clarifai/datasets/upload/text.py +8 -5
  9. clarifai/utils/misc.py +6 -0
  10. {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/METADATA +2 -1
  11. {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/RECORD +15 -58
  12. clarifai/models/model_serving/README.md +0 -158
  13. clarifai/models/model_serving/__init__.py +0 -14
  14. clarifai/models/model_serving/cli/__init__.py +0 -12
  15. clarifai/models/model_serving/cli/_utils.py +0 -53
  16. clarifai/models/model_serving/cli/base.py +0 -14
  17. clarifai/models/model_serving/cli/build.py +0 -79
  18. clarifai/models/model_serving/cli/clarifai_clis.py +0 -33
  19. clarifai/models/model_serving/cli/create.py +0 -171
  20. clarifai/models/model_serving/cli/example_cli.py +0 -34
  21. clarifai/models/model_serving/cli/login.py +0 -26
  22. clarifai/models/model_serving/cli/upload.py +0 -183
  23. clarifai/models/model_serving/constants.py +0 -21
  24. clarifai/models/model_serving/docs/cli.md +0 -161
  25. clarifai/models/model_serving/docs/concepts.md +0 -229
  26. clarifai/models/model_serving/docs/dependencies.md +0 -11
  27. clarifai/models/model_serving/docs/inference_parameters.md +0 -139
  28. clarifai/models/model_serving/docs/model_types.md +0 -19
  29. clarifai/models/model_serving/model_config/__init__.py +0 -16
  30. clarifai/models/model_serving/model_config/base.py +0 -369
  31. clarifai/models/model_serving/model_config/config.py +0 -312
  32. clarifai/models/model_serving/model_config/inference_parameter.py +0 -129
  33. clarifai/models/model_serving/model_config/model_types_config/multimodal-embedder.yaml +0 -25
  34. clarifai/models/model_serving/model_config/model_types_config/text-classifier.yaml +0 -19
  35. clarifai/models/model_serving/model_config/model_types_config/text-embedder.yaml +0 -20
  36. clarifai/models/model_serving/model_config/model_types_config/text-to-image.yaml +0 -19
  37. clarifai/models/model_serving/model_config/model_types_config/text-to-text.yaml +0 -19
  38. clarifai/models/model_serving/model_config/model_types_config/visual-classifier.yaml +0 -22
  39. clarifai/models/model_serving/model_config/model_types_config/visual-detector.yaml +0 -32
  40. clarifai/models/model_serving/model_config/model_types_config/visual-embedder.yaml +0 -19
  41. clarifai/models/model_serving/model_config/model_types_config/visual-segmenter.yaml +0 -19
  42. clarifai/models/model_serving/model_config/output.py +0 -133
  43. clarifai/models/model_serving/model_config/triton/__init__.py +0 -14
  44. clarifai/models/model_serving/model_config/triton/serializer.py +0 -136
  45. clarifai/models/model_serving/model_config/triton/triton_config.py +0 -182
  46. clarifai/models/model_serving/model_config/triton/wrappers.py +0 -281
  47. clarifai/models/model_serving/repo_build/__init__.py +0 -14
  48. clarifai/models/model_serving/repo_build/build.py +0 -198
  49. clarifai/models/model_serving/repo_build/static_files/_requirements.txt +0 -2
  50. clarifai/models/model_serving/repo_build/static_files/base_test.py +0 -169
  51. clarifai/models/model_serving/repo_build/static_files/inference.py +0 -26
  52. clarifai/models/model_serving/repo_build/static_files/sample_clarifai_config.yaml +0 -25
  53. clarifai/models/model_serving/repo_build/static_files/test.py +0 -40
  54. clarifai/models/model_serving/repo_build/static_files/triton/model.py +0 -75
  55. clarifai/models/model_serving/utils.py +0 -31
  56. {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/LICENSE +0 -0
  57. {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/WHEEL +0 -0
  58. {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/entry_points.txt +0 -0
  59. {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/top_level.txt +0 -0
@@ -1,182 +0,0 @@
1
- # Copyright 2023 Clarifai, Inc.
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- """ Model Config classes."""
14
- from __future__ import annotations # isort: skip
15
-
16
- from copy import deepcopy
17
- from dataclasses import dataclass, field
18
- from typing import Any, List, Union
19
-
20
- from ...constants import IMAGE_TENSOR_NAME, MAX_HW_DIM
21
-
22
-
23
- ### Triton Model Config classes.###
24
- @dataclass
25
- class DType:
26
- """
27
- Triton Model Config data types.
28
- """
29
- # https://github.com/triton-inference-server/common/blob/main/protobuf/model_config.proto
30
- TYPE_UINT8: int = 2
31
- TYPE_INT8: int = 6
32
- TYPE_INT16: int = 7
33
- TYPE_INT32: int = 8
34
- TYPE_INT64: int = 9
35
- TYPE_FP16: int = 10
36
- TYPE_FP32: int = 11
37
- TYPE_STRING: int = 13
38
- KIND_GPU: int = 1
39
- KIND_CPU: int = 2
40
-
41
-
42
- @dataclass
43
- class InputConfig:
44
- """
45
- Triton Input definition.
46
- Params:
47
- -------
48
- name: input name
49
- data_type: input data type
50
- dims: Pre-defined input data shape(s).
51
-
52
- Returns:
53
- --------
54
- InputConfig
55
- """
56
- name: str
57
- data_type: int
58
- dims: List = field(default_factory=list)
59
- optional: bool = False
60
-
61
-
62
- @dataclass
63
- class OutputConfig:
64
- """
65
- Triton Output definition.
66
- Params:
67
- -------
68
- name: output name
69
- data_type: output data type
70
- dims: Pre-defined output data shape(s).
71
- labels (bool): If labels file is required for inference.
72
-
73
- Returns:
74
- --------
75
- OutputConfig
76
- """
77
- name: str
78
- data_type: int
79
- dims: List = field(default_factory=list)
80
- label_filename: str = ""
81
-
82
-
83
- @dataclass
84
- class Device:
85
- """
86
- Triton instance_group.
87
- Define the type of inference device and number of devices to use.
88
- Params:
89
- -------
90
- count: number of devices
91
- use_gpu: whether to use cpu or gpu.
92
-
93
- Returns:
94
- --------
95
- Device object
96
- """
97
- count: int = 1
98
- use_gpu: bool = True
99
-
100
- def __post_init__(self):
101
- if self.use_gpu:
102
- self.kind: str = DType.KIND_GPU
103
- else:
104
- self.kind: str = DType.KIND_CPU
105
-
106
-
107
- @dataclass
108
- class DynamicBatching:
109
- """
110
- Triton dynamic_batching config.
111
- Params:
112
- -------
113
- preferred_batch_size: batch size
114
- max_queue_delay_microseconds: max queue delay for a request batch
115
-
116
- Returns:
117
- --------
118
- DynamicBatching object
119
- """
120
- #preferred_batch_size: List[int] = [1] # recommended not to set
121
- max_queue_delay_microseconds: int = 500
122
-
123
-
124
- @dataclass
125
- class TritonModelConfig:
126
- """
127
- Triton Model Config base.
128
- Params:
129
- -------
130
- name: triton inference model name
131
- input: a list of an InputConfig field
132
- output: a list of OutputConfig fields/dicts
133
- instance_group: Device. see Device
134
- dynamic_batching: Triton dynamic batching settings.
135
- max_batch_size: max request batch size
136
- backend: Triton Python Backend. Constant
137
- image_shape: List of Height and Width of input image. *
138
-
139
- (*): This attribute won't be serialized in config.pbtxt
140
-
141
- Returns:
142
- --------
143
- TritonModelConfig
144
- """
145
- #model_type: str
146
- model_name: str = ""
147
- model_version: str = "1"
148
- input: List[InputConfig] = field(default_factory=list)
149
- output: List[OutputConfig] = field(default_factory=list)
150
- instance_group: Device = field(default_factory=Device)
151
- dynamic_batching: DynamicBatching = field(default_factory=DynamicBatching)
152
- max_batch_size: int = 1
153
- backend: str = "python"
154
- image_shape: tuple[Union[int, float], Union[int, float]] = field(
155
- default_factory=lambda: [-1, -1]) #(H, W)
156
-
157
- def __setattr__(self, __name: str, __value: Any) -> None:
158
- if __name == "image_shape":
159
- __value = self._check_and_assign_image_shape_value(__value)
160
-
161
- super().__setattr__(__name, __value)
162
-
163
- def _check_and_assign_image_shape_value(self, value):
164
- _has_image = False
165
- for each in self.input:
166
- if IMAGE_TENSOR_NAME in each.name:
167
- _has_image = True
168
- if len(value) != 2:
169
- raise ValueError(
170
- f"image_shape takes 2 values, Height and Width. Got {len(value)} values instead.")
171
- if value[0] > MAX_HW_DIM or value[1] > MAX_HW_DIM:
172
- raise ValueError(
173
- f"H and W each have a maximum value of {MAX_HW_DIM}. Got H: {value[0]}, W: {value[1]}"
174
- )
175
- image_dims = deepcopy(value)
176
- image_dims.append(3) # add channel dim
177
- each.dims = image_dims
178
-
179
- if not _has_image and self.input:
180
- return [-1, -1]
181
- else:
182
- return value
@@ -1,281 +0,0 @@
1
- # Copyright 2023 Clarifai, Inc.
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- """
14
- Parse inference model predictions to triton inference responses
15
- per model type.
16
- """
17
-
18
- from functools import wraps
19
- from itertools import zip_longest
20
- from typing import Callable, Dict
21
- import numpy as np
22
-
23
- try:
24
- import triton_python_backend_utils as pb_utils
25
- except ModuleNotFoundError:
26
- pass
27
-
28
-
29
- def visual_detector(func: Callable):
30
- """
31
- Visual detector type output parser.
32
- """
33
-
34
- @wraps(func)
35
- def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
36
- """
37
- Format predictions and return clarifai compatible output.
38
- """
39
- out_bboxes = []
40
- out_labels = []
41
- out_scores = []
42
-
43
- # input_data passed as list of images
44
- preds = func(self, list(input_data[:]), *args, **kwargs)
45
- for pred in preds:
46
- out_bboxes.append(pred.predicted_bboxes)
47
- out_labels.append(pred.predicted_labels)
48
- out_scores.append(pred.predicted_scores)
49
-
50
- if len(out_bboxes) < 1 or len(out_labels) < 1:
51
- out_tensor_bboxes = pb_utils.Tensor("predicted_bboxes", np.zeros((0, 4), dtype=np.float32))
52
- out_tensor_labels = pb_utils.Tensor("predicted_labels", np.zeros((0, 1), dtype=np.int32))
53
- out_tensor_scores = pb_utils.Tensor("predicted_scores", np.zeros((0, 1), dtype=np.float32))
54
- else:
55
- out_tensor_bboxes = pb_utils.Tensor("predicted_bboxes",
56
- np.asarray(out_bboxes, dtype=np.float32))
57
- out_tensor_labels = pb_utils.Tensor("predicted_labels",
58
- np.asarray(out_labels, dtype=np.int32))
59
- out_tensor_scores = pb_utils.Tensor("predicted_scores",
60
- np.asarray(out_scores, dtype=np.float32))
61
-
62
- inference_response = pb_utils.InferenceResponse(
63
- output_tensors=[out_tensor_bboxes, out_tensor_labels, out_tensor_scores])
64
-
65
- return inference_response
66
-
67
- return parse_predictions
68
-
69
-
70
- def visual_classifier(func: Callable):
71
- """
72
- Visual classifier type output parser.
73
- """
74
-
75
- @wraps(func)
76
- def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
77
- """
78
- Format predictions and return clarifai compatible output.
79
- """
80
- out_scores = []
81
- # input_data passed as list of images
82
- preds = func(self, list(input_data[:]), *args, **kwargs)
83
-
84
- for pred in preds:
85
- out_scores.append(pred.predicted_scores)
86
-
87
- out_tensor_scores = pb_utils.Tensor("softmax_predictions",
88
- np.asarray(out_scores, dtype=np.float32))
89
- inference_response = pb_utils.InferenceResponse(output_tensors=[out_tensor_scores])
90
-
91
- return inference_response
92
-
93
- return parse_predictions
94
-
95
-
96
- def text_classifier(func: Callable):
97
- """
98
- Text classifier type output parser.
99
- """
100
-
101
- @wraps(func)
102
- def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
103
- """
104
- Format predictions and return clarifai compatible output.
105
- """
106
- out_scores = []
107
- input_data = [in_elem[0].decode() for in_elem in input_data]
108
- preds = func(self, input_data, *args, **kwargs)
109
-
110
- for pred in preds:
111
- out_scores.append(pred.predicted_scores)
112
-
113
- out_tensor_scores = pb_utils.Tensor("softmax_predictions",
114
- np.asarray(out_scores, dtype=np.float32))
115
- inference_response = pb_utils.InferenceResponse(output_tensors=[out_tensor_scores])
116
-
117
- return inference_response
118
-
119
- return parse_predictions
120
-
121
-
122
- def text_to_text(func: Callable):
123
- """
124
- Text to text type output parser.
125
- Convert a sequence of text into another e.g. text generation,
126
- summarization or translation.
127
- """
128
-
129
- @wraps(func)
130
- def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
131
- """
132
- Format predictions and return clarifai compatible output.
133
- """
134
- out_text = []
135
- input_data = [in_elem[0].decode() for in_elem in input_data]
136
- preds = func(self, input_data, *args, **kwargs)
137
-
138
- for pred in preds:
139
- out_text.append(pred.predicted_text)
140
-
141
- out_text_tensor = pb_utils.Tensor("text", np.asarray(out_text, dtype=object))
142
- inference_response = pb_utils.InferenceResponse(output_tensors=[out_text_tensor])
143
-
144
- return inference_response
145
-
146
- return parse_predictions
147
-
148
-
149
- def text_embedder(func: Callable):
150
- """
151
- Text embedder type output parser.
152
- Generates embeddings for an input text.
153
- """
154
-
155
- @wraps(func)
156
- def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
157
- """
158
- Format predictions and return clarifai compatible output.
159
- """
160
- out_embeddings = []
161
- input_data = [in_elem[0].decode() for in_elem in input_data]
162
- preds = func(self, input_data, *args, **kwargs)
163
-
164
- for pred in preds:
165
- out_embeddings.append(pred.embedding_vector)
166
-
167
- out_embed_tensor = pb_utils.Tensor("embeddings", np.asarray(out_embeddings, dtype=np.float32))
168
- inference_response = pb_utils.InferenceResponse(output_tensors=[out_embed_tensor])
169
-
170
- return inference_response
171
-
172
- return parse_predictions
173
-
174
-
175
- def visual_embedder(func: Callable):
176
- """
177
- Visual embedder type output parser.
178
- Generates embeddings for an input image.
179
- """
180
-
181
- @wraps(func)
182
- def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
183
- """
184
- Format predictions and return clarifai compatible output.
185
- """
186
- out_embeddings = []
187
- # input_data passed as list of images
188
- preds = func(self, list(input_data[:]), *args, **kwargs)
189
-
190
- for pred in preds:
191
- out_embeddings.append(pred.embedding_vector)
192
-
193
- out_embed_tensor = pb_utils.Tensor("embeddings", np.asarray(out_embeddings, dtype=np.float32))
194
- inference_response = pb_utils.InferenceResponse(output_tensors=[out_embed_tensor])
195
-
196
- return inference_response
197
-
198
- return parse_predictions
199
-
200
-
201
- def visual_segmenter(func: Callable):
202
- """
203
- Visual segmenter type output parser.
204
- """
205
-
206
- @wraps(func)
207
- def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
208
- """
209
- Format predictions and return clarifai compatible output.
210
- """
211
- masks = []
212
- # input_data passed as list of images
213
- preds = func(self, list(input_data[:]), *args, **kwargs)
214
-
215
- for pred in preds:
216
- masks.append(pred.predicted_mask)
217
-
218
- out_mask_tensor = pb_utils.Tensor("predicted_mask", np.asarray(masks, dtype=np.int64))
219
- inference_response = pb_utils.InferenceResponse(output_tensors=[out_mask_tensor])
220
-
221
- return inference_response
222
-
223
- return parse_predictions
224
-
225
-
226
- def text_to_image(func: Callable):
227
- """
228
- Text to image type output parser.
229
- """
230
-
231
- @wraps(func)
232
- def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
233
- """
234
- Format predictions and return clarifai compatible output.
235
- """
236
- gen_images = []
237
- input_data = [in_elem[0].decode() for in_elem in input_data]
238
- preds = func(self, input_data, *args, **kwargs)
239
-
240
- for pred in preds:
241
- gen_images.append(pred.image)
242
-
243
- out_image_tensor = pb_utils.Tensor("image", np.asarray(gen_images, dtype=np.uint8))
244
- inference_response = pb_utils.InferenceResponse(output_tensors=[out_image_tensor])
245
-
246
- return inference_response
247
-
248
- return parse_predictions
249
-
250
-
251
- def multimodal_embedder(func: Callable):
252
- """
253
- Multimodal embedder type output parser.
254
- Generates embeddings for image or text input.
255
- """
256
-
257
- @wraps(func)
258
- def parse_predictions(self, input_data: Dict[str, np.ndarray], *args, **kwargs):
259
- """
260
- Format predictions and return clarifai compatible output.
261
- """
262
- out_embeddings = []
263
- model_input_data = []
264
- for group in zip_longest(*input_data.values()):
265
- _input_data = dict(zip(input_data, group))
266
- for k, v in _input_data.items():
267
- # decode np.object to string
268
- if isinstance(v, np.ndarray) and v.dtype == np.object_:
269
- _input_data.update({k: v[0].decode()})
270
- model_input_data.append(_input_data)
271
-
272
- preds = func(self, model_input_data, *args, **kwargs)
273
- for pred in preds:
274
- out_embeddings.append(pred.embedding_vector)
275
-
276
- out_embed_tensor = pb_utils.Tensor("embeddings", np.asarray(out_embeddings, dtype=np.float32))
277
- inference_response = pb_utils.InferenceResponse(output_tensors=[out_embed_tensor])
278
-
279
- return inference_response
280
-
281
- return parse_predictions
@@ -1,14 +0,0 @@
1
- # Copyright 2023 Clarifai, Inc.
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- from .build import RepositoryBuilder # noqa
14
- from .static_files.base_test import BaseTest # noqa
@@ -1,198 +0,0 @@
1
- # Copyright 2023 Clarifai, Inc.
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- """
14
- Triton python backend inference model controller.
15
- """
16
-
17
- import inspect
18
- import os
19
- import shutil
20
- import zipfile
21
- from dataclasses import asdict
22
- from pathlib import Path
23
- from typing import Iterable, Literal, Union
24
-
25
- import yaml
26
- from tqdm import tqdm
27
-
28
- from ..constants import BUILT_MODEL_EXT
29
- from ..model_config import MODEL_TYPES, ModelConfigClass, base, get_model_config, load_user_config
30
- from ..model_config.base import * # noqa
31
- from ..model_config.config import parse_config
32
- from ..model_config.triton.serializer import Serializer
33
-
34
-
35
- def __parse_type_to_class():
36
- _t = {}
37
- _classes = inspect.getmembers(base, inspect.isclass)
38
- for cls_name, cls_obj in _classes:
39
- if cls_obj.__base__ is base._BaseClarifaiModel:
40
- _t.update({cls_obj._config.clarifai_model.type: cls_name})
41
- return _t
42
-
43
-
44
- _TYPE_TO_CLASS = __parse_type_to_class()
45
-
46
-
47
- def _get_static_file_path(relative_path: str):
48
- curr_dir = os.path.dirname(__file__)
49
- return os.path.join(curr_dir, "static_files", relative_path)
50
-
51
-
52
- def _read_static_file(relative_path: str):
53
- path = _get_static_file_path(relative_path)
54
- with open(path, "r") as f:
55
- return f.read()
56
-
57
-
58
- def copy_folder(src_folder, dest_folder, exclude_items=None):
59
-
60
- if exclude_items is None:
61
- exclude_items = set()
62
-
63
- # Ensure the destination folder exists
64
- if not os.path.exists(dest_folder):
65
- os.makedirs(dest_folder)
66
-
67
- loader = tqdm(os.listdir(src_folder))
68
- if exclude_items:
69
- print(f"NOTE: skipping {exclude_items}")
70
-
71
- for item in loader:
72
- loader.set_description(f"copying {item}...")
73
- src_item = os.path.join(src_folder, item)
74
- dest_item = os.path.join(dest_folder, item)
75
-
76
- # Skip items in the exclude list
77
- if item in exclude_items or item.endswith(BUILT_MODEL_EXT):
78
- continue
79
-
80
- # Copy files directly
81
- if os.path.isfile(src_item):
82
- shutil.copy2(src_item, dest_item)
83
-
84
- # Copy directories using copytree
85
- elif os.path.isdir(src_item):
86
- shutil.copytree(src_item, dest_item, symlinks=False, ignore=None, dirs_exist_ok=True)
87
-
88
-
89
- def zip_dir(input: Union[Path, str], zip_filename: Union[Path, str]):
90
- """
91
- Zip folder without compressing
92
- """
93
- # Convert to Path object
94
- dir = Path(input)
95
-
96
- with zipfile.ZipFile(zip_filename, "w", zipfile.ZIP_STORED) as zip_file:
97
- for entry in dir.rglob("*"):
98
- zip_file.write(entry, entry.relative_to(dir))
99
-
100
-
101
- class RepositoryBuilder:
102
-
103
- @staticmethod
104
- def init_repository(model_type: str, working_dir: str, backend=Literal['triton'], **kwargs):
105
- assert model_type in MODEL_TYPES
106
- model_type = model_type
107
- default_model_type_config: ModelConfigClass = get_model_config(model_type)
108
-
109
- os.makedirs(working_dir, exist_ok=True)
110
-
111
- def __write_to(filename, data):
112
- with open(os.path.join(working_dir, filename), "w") as f:
113
- f.write(data)
114
-
115
- # create inference.py
116
- _filename = "inference.py"
117
- inference_py = _read_static_file(_filename)
118
- inference_py = inference_py.replace("InferenceModel()",
119
- f"InferenceModel({_TYPE_TO_CLASS[model_type]})")
120
- inference_py = inference_py.replace("predict_docstring",
121
- eval(_TYPE_TO_CLASS[model_type]).predict.__doc__)
122
- # create config
123
- config = asdict(default_model_type_config)
124
- if backend == "triton":
125
- max_batch_size = kwargs.get("max_batch_size", None)
126
- image_shape = kwargs.get("image_shape", None)
127
- if max_batch_size:
128
- config['serving_backend']['triton']['max_batch_size'] = max_batch_size
129
- if image_shape:
130
- config['serving_backend']['triton']['image_shape'] = image_shape
131
- config = parse_config(config).dump_to_user_config()
132
- config_data = yaml.dump(config)
133
- sample_yaml = _read_static_file("sample_clarifai_config.yaml")
134
- config_data = sample_yaml + "\n\n" + config_data
135
- __write_to("clarifai_config.yaml", config_data)
136
- #
137
- # create inference.py after checking all configs
138
- __write_to(_filename, inference_py)
139
- # create test.py
140
- __write_to("test.py", _read_static_file("test.py"))
141
- # create requirements.txt
142
- __write_to("requirements.txt", _read_static_file("_requirements.txt"))
143
-
144
- @staticmethod
145
- def build(working_dir: str, output_dir: str = None, name: str = None, backend=Literal['triton']):
146
- if not output_dir:
147
- output_dir = working_dir
148
- else:
149
- os.makedirs(output_dir, exist_ok=True)
150
-
151
- temp_folder = os.path.join(working_dir, ".cache")
152
- os.makedirs(temp_folder, exist_ok=True)
153
-
154
- user_config_file = os.path.join(working_dir, "clarifai_config.yaml")
155
- assert os.path.exists(
156
- user_config_file
157
- ), f"FileNotFound: please make sure `clarifai_config.yaml` exists in {working_dir}"
158
- user_config = load_user_config(user_config_file)
159
-
160
- if backend == "triton":
161
- triton_1_ver = os.path.join(temp_folder, "1")
162
- os.makedirs(triton_1_ver, exist_ok=True)
163
- # check if labels exists
164
- for output_config in user_config.serving_backend.triton.output:
165
- if output_config.label_filename:
166
- user_labels = user_config.clarifai_model.labels
167
- assert user_labels, f"Model type `{user_config.clarifai_model.type}` requires labels, "\
168
- f"but can not found value of `clarifai_model.labels` in {user_config_file}. Please update this attribute to build the model"
169
- with open(os.path.join(temp_folder, "labels.txt"), "w") as f:
170
- if not isinstance(user_labels, Iterable):
171
- user_labels = [user_labels]
172
- f.write("\n".join([str(lb) for lb in user_labels]) + "\n")
173
-
174
- # copy model.py
175
- shutil.copy(_get_static_file_path("triton/model.py"), triton_1_ver)
176
- # copy requirements.txt
177
- shutil.copy(os.path.join(working_dir, "requirements.txt"), temp_folder)
178
- # copy all other files
179
- copy_folder(
180
- working_dir, triton_1_ver, exclude_items=["requirements.txt", ".cache", "__pycache__"])
181
- # generate config.pbtxt
182
- _config_pbtxt_serializer = Serializer(user_config.serving_backend.triton)
183
- _config_pbtxt_serializer.to_file(temp_folder)
184
-
185
- else:
186
- raise ValueError(f"backend must be ['triton'], got {backend}")
187
-
188
- clarifai_model_name = name or user_config.clarifai_model.clarifai_model_id or "model"
189
- clarifai_model_name += BUILT_MODEL_EXT
190
- clarifai_model_name = os.path.join(output_dir, clarifai_model_name)
191
-
192
- print(
193
- "Model building in progress; the duration may vary depending on the size of checkpoints/assets..."
194
- )
195
- zip_dir(temp_folder, clarifai_model_name)
196
- print(f"Finished. Your model is located at {clarifai_model_name}")
197
-
198
- return clarifai_model_name
@@ -1,2 +0,0 @@
1
- clarifai>9.10.4
2
- tritonclient[all]