clarifai 11.6.4__py3-none-any.whl → 11.6.4rc1__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.
- clarifai/__init__.py +1 -1
- clarifai/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/__pycache__/errors.cpython-311.pyc +0 -0
- clarifai/__pycache__/errors.cpython-39.pyc +0 -0
- clarifai/__pycache__/versions.cpython-311.pyc +0 -0
- clarifai/__pycache__/versions.cpython-39.pyc +0 -0
- clarifai/cli/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/cli/__pycache__/base.cpython-39.pyc +0 -0
- clarifai/cli/__pycache__/compute_cluster.cpython-39.pyc +0 -0
- clarifai/cli/__pycache__/deployment.cpython-39.pyc +0 -0
- clarifai/cli/__pycache__/model.cpython-39.pyc +0 -0
- clarifai/cli/__pycache__/nodepool.cpython-39.pyc +0 -0
- clarifai/cli/base.py +11 -27
- clarifai/cli/model.py +171 -41
- clarifai/cli/model_templates.py +243 -0
- clarifai/cli/pipeline_step_templates.py +64 -0
- clarifai/client/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/app.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/app.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/base.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/base.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/compute_cluster.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/dataset.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/dataset.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/deployment.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/deployment.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/input.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/input.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/lister.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/lister.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/model.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/model.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/model_client.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/model_client.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/module.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/nodepool.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/runner.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/search.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/user.cpython-311.pyc +0 -0
- clarifai/client/__pycache__/workflow.cpython-311.pyc +0 -0
- clarifai/client/auth/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/client/auth/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/helper.cpython-311.pyc +0 -0
- clarifai/client/auth/__pycache__/helper.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/register.cpython-311.pyc +0 -0
- clarifai/client/auth/__pycache__/register.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/stub.cpython-311.pyc +0 -0
- clarifai/client/auth/__pycache__/stub.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/base.cpython-311.pyc +0 -0
- clarifai/constants/__pycache__/base.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/dataset.cpython-311.pyc +0 -0
- clarifai/constants/__pycache__/dataset.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/input.cpython-311.pyc +0 -0
- clarifai/constants/__pycache__/input.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/model.cpython-311.pyc +0 -0
- clarifai/constants/__pycache__/model.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/search.cpython-311.pyc +0 -0
- clarifai/constants/__pycache__/workflow.cpython-311.pyc +0 -0
- clarifai/datasets/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/datasets/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/datasets/export/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/datasets/export/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/datasets/export/__pycache__/inputs_annotations.cpython-311.pyc +0 -0
- clarifai/datasets/export/__pycache__/inputs_annotations.cpython-39.pyc +0 -0
- clarifai/datasets/upload/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/datasets/upload/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/datasets/upload/__pycache__/base.cpython-311.pyc +0 -0
- clarifai/datasets/upload/__pycache__/base.cpython-39.pyc +0 -0
- clarifai/datasets/upload/__pycache__/features.cpython-311.pyc +0 -0
- clarifai/datasets/upload/__pycache__/features.cpython-39.pyc +0 -0
- clarifai/datasets/upload/__pycache__/image.cpython-311.pyc +0 -0
- clarifai/datasets/upload/__pycache__/image.cpython-39.pyc +0 -0
- clarifai/datasets/upload/__pycache__/multimodal.cpython-311.pyc +0 -0
- clarifai/datasets/upload/__pycache__/multimodal.cpython-39.pyc +0 -0
- clarifai/datasets/upload/__pycache__/text.cpython-311.pyc +0 -0
- clarifai/datasets/upload/__pycache__/text.cpython-39.pyc +0 -0
- clarifai/datasets/upload/__pycache__/utils.cpython-311.pyc +0 -0
- clarifai/datasets/upload/__pycache__/utils.cpython-39.pyc +0 -0
- clarifai/models/model_serving/README.md +158 -0
- clarifai/models/model_serving/__init__.py +14 -0
- clarifai/models/model_serving/cli/__init__.py +12 -0
- clarifai/models/model_serving/cli/_utils.py +53 -0
- clarifai/models/model_serving/cli/base.py +14 -0
- clarifai/models/model_serving/cli/build.py +79 -0
- clarifai/models/model_serving/cli/clarifai_clis.py +33 -0
- clarifai/models/model_serving/cli/create.py +171 -0
- clarifai/models/model_serving/cli/example_cli.py +34 -0
- clarifai/models/model_serving/cli/login.py +26 -0
- clarifai/models/model_serving/cli/upload.py +179 -0
- clarifai/models/model_serving/constants.py +21 -0
- clarifai/models/model_serving/docs/cli.md +161 -0
- clarifai/models/model_serving/docs/concepts.md +229 -0
- clarifai/models/model_serving/docs/dependencies.md +11 -0
- clarifai/models/model_serving/docs/inference_parameters.md +139 -0
- clarifai/models/model_serving/docs/model_types.md +19 -0
- clarifai/models/model_serving/model_config/__init__.py +16 -0
- clarifai/models/model_serving/model_config/base.py +369 -0
- clarifai/models/model_serving/model_config/config.py +312 -0
- clarifai/models/model_serving/model_config/inference_parameter.py +129 -0
- clarifai/models/model_serving/model_config/model_types_config/multimodal-embedder.yaml +25 -0
- clarifai/models/model_serving/model_config/model_types_config/text-classifier.yaml +19 -0
- clarifai/models/model_serving/model_config/model_types_config/text-embedder.yaml +20 -0
- clarifai/models/model_serving/model_config/model_types_config/text-to-image.yaml +19 -0
- clarifai/models/model_serving/model_config/model_types_config/text-to-text.yaml +19 -0
- clarifai/models/model_serving/model_config/model_types_config/visual-classifier.yaml +22 -0
- clarifai/models/model_serving/model_config/model_types_config/visual-detector.yaml +32 -0
- clarifai/models/model_serving/model_config/model_types_config/visual-embedder.yaml +19 -0
- clarifai/models/model_serving/model_config/model_types_config/visual-segmenter.yaml +19 -0
- clarifai/models/model_serving/model_config/output.py +133 -0
- clarifai/models/model_serving/model_config/triton/__init__.py +14 -0
- clarifai/models/model_serving/model_config/triton/serializer.py +136 -0
- clarifai/models/model_serving/model_config/triton/triton_config.py +182 -0
- clarifai/models/model_serving/model_config/triton/wrappers.py +281 -0
- clarifai/models/model_serving/repo_build/__init__.py +14 -0
- clarifai/models/model_serving/repo_build/build.py +198 -0
- clarifai/models/model_serving/repo_build/static_files/_requirements.txt +2 -0
- clarifai/models/model_serving/repo_build/static_files/base_test.py +169 -0
- clarifai/models/model_serving/repo_build/static_files/inference.py +26 -0
- clarifai/models/model_serving/repo_build/static_files/sample_clarifai_config.yaml +25 -0
- clarifai/models/model_serving/repo_build/static_files/test.py +40 -0
- clarifai/models/model_serving/repo_build/static_files/triton/model.py +75 -0
- clarifai/models/model_serving/utils.py +23 -0
- clarifai/runners/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/runners/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/runners/models/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/runners/models/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/runners/models/__pycache__/mcp_class.cpython-311.pyc +0 -0
- clarifai/runners/models/__pycache__/model_builder.cpython-311.pyc +0 -0
- clarifai/runners/models/__pycache__/model_builder.cpython-39.pyc +0 -0
- clarifai/runners/models/__pycache__/model_class.cpython-311.pyc +0 -0
- clarifai/runners/models/__pycache__/model_runner.cpython-311.pyc +0 -0
- clarifai/runners/models/__pycache__/openai_class.cpython-311.pyc +0 -0
- clarifai/runners/models/base_typed_model.py +238 -0
- clarifai/runners/models/model_upload.py +607 -0
- clarifai/runners/utils/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/runners/utils/__pycache__/code_script.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/code_script.cpython-39.pyc +0 -0
- clarifai/runners/utils/__pycache__/const.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/data_utils.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/data_utils.cpython-39.pyc +0 -0
- clarifai/runners/utils/__pycache__/loader.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/method_signatures.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/model_utils.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/openai_convertor.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/serializers.cpython-311.pyc +0 -0
- clarifai/runners/utils/__pycache__/url_fetcher.cpython-311.pyc +0 -0
- clarifai/runners/utils/data_handler.py +231 -0
- clarifai/runners/utils/data_types/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/runners/utils/data_types/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/runners/utils/data_types/__pycache__/data_types.cpython-311.pyc +0 -0
- clarifai/runners/utils/data_types/__pycache__/data_types.cpython-39.pyc +0 -0
- clarifai/runners/utils/data_types.py +471 -0
- clarifai/runners/utils/temp.py +59 -0
- clarifai/schema/__pycache__/search.cpython-311.pyc +0 -0
- clarifai/urls/__pycache__/helper.cpython-311.pyc +0 -0
- clarifai/urls/__pycache__/helper.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/utils/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/cli.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/config.cpython-311.pyc +0 -0
- clarifai/utils/__pycache__/config.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/constants.cpython-311.pyc +0 -0
- clarifai/utils/__pycache__/constants.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/logging.cpython-311.pyc +0 -0
- clarifai/utils/__pycache__/logging.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/misc.cpython-311.pyc +0 -0
- clarifai/utils/__pycache__/misc.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/model_train.cpython-311.pyc +0 -0
- clarifai/utils/__pycache__/protobuf.cpython-311.pyc +0 -0
- clarifai/utils/__pycache__/protobuf.cpython-39.pyc +0 -0
- clarifai/utils/cli.py +14 -15
- clarifai/utils/constants.py +2 -0
- clarifai/utils/misc.py +381 -1
- clarifai/workflows/__pycache__/__init__.cpython-311.pyc +0 -0
- clarifai/workflows/__pycache__/export.cpython-311.pyc +0 -0
- clarifai/workflows/__pycache__/utils.cpython-311.pyc +0 -0
- clarifai/workflows/__pycache__/validate.cpython-311.pyc +0 -0
- {clarifai-11.6.4.dist-info → clarifai-11.6.4rc1.dist-info}/METADATA +1 -1
- clarifai-11.6.4rc1.dist-info/RECORD +301 -0
- {clarifai-11.6.4.dist-info → clarifai-11.6.4rc1.dist-info}/WHEEL +1 -1
- clarifai-11.6.4.dist-info/RECORD +0 -127
- {clarifai-11.6.4.dist-info → clarifai-11.6.4rc1.dist-info}/entry_points.txt +0 -0
- {clarifai-11.6.4.dist-info → clarifai-11.6.4rc1.dist-info}/licenses/LICENSE +0 -0
- {clarifai-11.6.4.dist-info → clarifai-11.6.4rc1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,231 @@
|
|
1
|
+
from typing import Dict, List, Tuple, Union
|
2
|
+
|
3
|
+
import numpy as np
|
4
|
+
from clarifai_grpc.grpc.api import resources_pb2
|
5
|
+
from clarifai_grpc.grpc.api.status import status_code_pb2, status_pb2
|
6
|
+
from PIL import Image
|
7
|
+
|
8
|
+
from clarifai.client.auth.helper import ClarifaiAuthHelper
|
9
|
+
|
10
|
+
from .data_utils import bytes_to_image, image_to_bytes
|
11
|
+
|
12
|
+
|
13
|
+
class BaseDataHandler:
|
14
|
+
|
15
|
+
def __init__(self,
|
16
|
+
proto: Union[resources_pb2.Input, resources_pb2.Output],
|
17
|
+
auth: ClarifaiAuthHelper = None):
|
18
|
+
self._proto = proto
|
19
|
+
self._auth = auth
|
20
|
+
|
21
|
+
#
|
22
|
+
def to_python(self):
|
23
|
+
return dict(text=self.text, image=self.image, audio=self.audio)
|
24
|
+
|
25
|
+
# ---------------- Start get/setters ---------------- #
|
26
|
+
# Proto
|
27
|
+
@property
|
28
|
+
def proto(self):
|
29
|
+
return self._proto
|
30
|
+
|
31
|
+
# Status
|
32
|
+
@property
|
33
|
+
def status(self) -> status_pb2.Status:
|
34
|
+
return self._proto.status
|
35
|
+
|
36
|
+
def set_status(self, code: str, description: str = ""):
|
37
|
+
self._proto.status.code = code
|
38
|
+
self._proto.status.description = description
|
39
|
+
|
40
|
+
# Text
|
41
|
+
@property
|
42
|
+
def text(self) -> Union[None, str]:
|
43
|
+
data = self._proto.data.text
|
44
|
+
text = None
|
45
|
+
if data.ByteSize():
|
46
|
+
if data.raw:
|
47
|
+
text = data.raw
|
48
|
+
else:
|
49
|
+
raise NotImplementedError
|
50
|
+
return text
|
51
|
+
|
52
|
+
def set_text(self, text: str):
|
53
|
+
self._proto.data.text.raw = text
|
54
|
+
|
55
|
+
# Image
|
56
|
+
@property
|
57
|
+
def image(self, format: str = "np") -> Union[None, Image.Image, np.ndarray]:
|
58
|
+
data = self._proto.data.image
|
59
|
+
image = None
|
60
|
+
if data.ByteSize():
|
61
|
+
data: resources_pb2.Image = data
|
62
|
+
if data.base64:
|
63
|
+
image = data.base64
|
64
|
+
elif data.url:
|
65
|
+
raise NotImplementedError
|
66
|
+
image = bytes_to_image(image)
|
67
|
+
image = image if not format == "np" else np.asarray(image).astype("uint8")
|
68
|
+
return image
|
69
|
+
|
70
|
+
def set_image(self, image: Union[Image.Image, np.ndarray]):
|
71
|
+
if isinstance(image, np.ndarray):
|
72
|
+
image = Image.fromarray(image)
|
73
|
+
self._proto.data.image.base64 = image_to_bytes(image)
|
74
|
+
|
75
|
+
# Audio
|
76
|
+
@property
|
77
|
+
def audio(self) -> bytes:
|
78
|
+
data = self._proto.data.audio
|
79
|
+
audio = None
|
80
|
+
if data.ByteSize():
|
81
|
+
if data.base64:
|
82
|
+
audio = data.base64
|
83
|
+
return audio
|
84
|
+
|
85
|
+
def set_audio(self, audio: bytes):
|
86
|
+
self._proto.data.audio.base64 = audio
|
87
|
+
|
88
|
+
# Bboxes
|
89
|
+
@property
|
90
|
+
def bboxes(self, real_coord: bool = False, image_width: int = None,
|
91
|
+
image_height: int = None) -> Tuple[List, List, List]:
|
92
|
+
if real_coord:
|
93
|
+
assert (image_height or image_width
|
94
|
+
), "image_height and image_width are required when when return real coordinates"
|
95
|
+
xyxy = []
|
96
|
+
scores = []
|
97
|
+
concepts = []
|
98
|
+
for _, each in enumerate(self._proto.data.regions):
|
99
|
+
box = each.region_info
|
100
|
+
score = each.value
|
101
|
+
concept = each.data.concepts[0].id
|
102
|
+
x1 = box.left_col
|
103
|
+
y1 = box.top_row
|
104
|
+
x2 = box.right_col
|
105
|
+
y2 = box.bottom_row
|
106
|
+
if real_coord:
|
107
|
+
x1 = x1 * image_width
|
108
|
+
y1 = y1 * image_height
|
109
|
+
x2 = x2 * image_width
|
110
|
+
y2 = y2 * image_height
|
111
|
+
xyxy.append([x1, y1, x2, y2])
|
112
|
+
scores.append(score)
|
113
|
+
concepts.append(concept)
|
114
|
+
|
115
|
+
return xyxy, scores, concepts
|
116
|
+
|
117
|
+
def set_bboxes(self,
|
118
|
+
boxes: list,
|
119
|
+
scores: list,
|
120
|
+
concepts: list,
|
121
|
+
real_coord: bool = False,
|
122
|
+
image_width: int = None,
|
123
|
+
image_height: int = None):
|
124
|
+
if real_coord:
|
125
|
+
assert (image_height and
|
126
|
+
image_width), "image_height and image_width are required when `real_coord` is set"
|
127
|
+
bboxes = [[x[1] / image_height, x[0] / image_width, x[3] / image_height, x[2] / image_width]
|
128
|
+
for x in boxes] # normalize the bboxes to [0,1] and [y1 x1 y2 x2]
|
129
|
+
bboxes = np.clip(bboxes, 0, 1.0)
|
130
|
+
|
131
|
+
regions = []
|
132
|
+
for ith, bbox in enumerate(bboxes):
|
133
|
+
score = scores[ith]
|
134
|
+
concept = concepts[ith]
|
135
|
+
if any([each > 1.0 for each in bbox]):
|
136
|
+
assert ValueError(
|
137
|
+
"Box coordinates is not normalized between [0, 1]. Please set format_box to True and provide image_height and image_width to normalize"
|
138
|
+
)
|
139
|
+
region = resources_pb2.RegionInfo(bounding_box=resources_pb2.BoundingBox(
|
140
|
+
top_row=bbox[0], # y_min
|
141
|
+
left_col=bbox[1], # x_min
|
142
|
+
bottom_row=bbox[2], # y_max
|
143
|
+
right_col=bbox[3], # x_max
|
144
|
+
))
|
145
|
+
data = resources_pb2.Data(concepts=resources_pb2.Concept(id=concept, value=score))
|
146
|
+
regions.append(resources_pb2.Region(region_info=region, data=data))
|
147
|
+
|
148
|
+
self._proto.data.regions = regions
|
149
|
+
|
150
|
+
# Concepts
|
151
|
+
@property
|
152
|
+
def concepts(self) -> Dict[str, float]:
|
153
|
+
con_scores = {}
|
154
|
+
for each in self.proto.data.concepts:
|
155
|
+
con_scores.update({each.id: each.value})
|
156
|
+
return con_scores
|
157
|
+
|
158
|
+
def set_concepts(self, concept_score_pairs: Dict[str, float]):
|
159
|
+
concepts = []
|
160
|
+
for concept, score in concept_score_pairs.items():
|
161
|
+
con_score = resources_pb2.Concept(id=concept, name=concept, value=score)
|
162
|
+
concepts.append(con_score)
|
163
|
+
if concepts:
|
164
|
+
self._proto.data.ClearField("concepts")
|
165
|
+
for each in concepts:
|
166
|
+
self._proto.data.concepts.append(each)
|
167
|
+
|
168
|
+
# Embeddings
|
169
|
+
@property
|
170
|
+
def embeddings(self) -> List[List[float]]:
|
171
|
+
return [each.vector for each in self.proto.data.embeddings]
|
172
|
+
|
173
|
+
def set_embeddings(self, list_vectors: List[List[float]]):
|
174
|
+
if list_vectors[0]:
|
175
|
+
self._proto.data.ClearField("embeddings")
|
176
|
+
for vec in list_vectors:
|
177
|
+
self._proto.data.embeddings.append(
|
178
|
+
resources_pb2.Embedding(vector=vec, num_dimensions=len(vec)))
|
179
|
+
|
180
|
+
# ---------------- End get/setters ---------------- #
|
181
|
+
|
182
|
+
# Constructors
|
183
|
+
@classmethod
|
184
|
+
def from_proto(cls, proto):
|
185
|
+
clss = cls(proto=proto)
|
186
|
+
return clss
|
187
|
+
|
188
|
+
@classmethod
|
189
|
+
def from_data(
|
190
|
+
cls,
|
191
|
+
status_code: int = status_code_pb2.SUCCESS,
|
192
|
+
status_description: str = "",
|
193
|
+
text: str = None,
|
194
|
+
image: Union[Image.Image, np.ndarray] = None,
|
195
|
+
audio: bytes = None,
|
196
|
+
boxes: dict = None,
|
197
|
+
concepts: Dict[str, float] = {},
|
198
|
+
embeddings: List[List[float]] = [],
|
199
|
+
) -> 'OutputDataHandler':
|
200
|
+
clss = cls(proto=resources_pb2.Output())
|
201
|
+
if isinstance(image, Image.Image) or isinstance(image, np.ndarray):
|
202
|
+
clss.set_image(image)
|
203
|
+
if text:
|
204
|
+
clss.set_text(text)
|
205
|
+
if audio:
|
206
|
+
clss.set_audio(audio)
|
207
|
+
if boxes:
|
208
|
+
clss.set_bboxes(**boxes)
|
209
|
+
if concepts:
|
210
|
+
clss.set_concepts(concepts)
|
211
|
+
if embeddings:
|
212
|
+
clss.set_embeddings(embeddings)
|
213
|
+
|
214
|
+
clss.set_status(code=status_code, description=status_description)
|
215
|
+
return clss
|
216
|
+
|
217
|
+
|
218
|
+
class InputDataHandler(BaseDataHandler):
|
219
|
+
|
220
|
+
def __init__(self,
|
221
|
+
proto: resources_pb2.Input = resources_pb2.Input(),
|
222
|
+
auth: ClarifaiAuthHelper = None):
|
223
|
+
super().__init__(proto=proto, auth=auth)
|
224
|
+
|
225
|
+
|
226
|
+
class OutputDataHandler(BaseDataHandler):
|
227
|
+
|
228
|
+
def __init__(self,
|
229
|
+
proto: resources_pb2.Output = resources_pb2.Output(),
|
230
|
+
auth: ClarifaiAuthHelper = None):
|
231
|
+
super().__init__(proto=proto, auth=auth)
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
@@ -0,0 +1,471 @@
|
|
1
|
+
import io
|
2
|
+
import json
|
3
|
+
from typing import Iterable, List, get_args, get_origin
|
4
|
+
|
5
|
+
import numpy as np
|
6
|
+
from clarifai_grpc.grpc.api.resources_pb2 import Audio as AudioProto
|
7
|
+
from clarifai_grpc.grpc.api.resources_pb2 import Concept as ConceptProto
|
8
|
+
from clarifai_grpc.grpc.api.resources_pb2 import Frame as FrameProto
|
9
|
+
from clarifai_grpc.grpc.api.resources_pb2 import Image as ImageProto
|
10
|
+
from clarifai_grpc.grpc.api.resources_pb2 import Region as RegionProto
|
11
|
+
from clarifai_grpc.grpc.api.resources_pb2 import Text as TextProto
|
12
|
+
from clarifai_grpc.grpc.api.resources_pb2 import Video as VideoProto
|
13
|
+
from PIL import Image as PILImage
|
14
|
+
|
15
|
+
|
16
|
+
class MessageData:
|
17
|
+
def to_proto(self):
|
18
|
+
raise NotImplementedError
|
19
|
+
|
20
|
+
@classmethod
|
21
|
+
def from_proto(cls, proto):
|
22
|
+
raise NotImplementedError
|
23
|
+
|
24
|
+
@classmethod
|
25
|
+
def from_value(cls, value):
|
26
|
+
if isinstance(value, cls):
|
27
|
+
return value
|
28
|
+
return cls(value)
|
29
|
+
|
30
|
+
def cast(self, python_type):
|
31
|
+
if python_type is self.__class__:
|
32
|
+
return self
|
33
|
+
raise TypeError(f'Incompatible type for {self.__class__.__name__}: {python_type}')
|
34
|
+
|
35
|
+
|
36
|
+
class NamedFieldsMeta(type):
|
37
|
+
"""Metaclass to create NamedFields subclasses with __annotations__ when fields are specified."""
|
38
|
+
|
39
|
+
def __call__(cls, *args, **kwargs):
|
40
|
+
# Check if keyword arguments are types (used in type annotations)
|
41
|
+
if kwargs and all(isinstance(v, type) for v in kwargs.values()):
|
42
|
+
# Dynamically create a subclass with __annotations__
|
43
|
+
name = f"NamedFields({', '.join(f'{k}:{v.__name__}' for k, v in kwargs.items())})"
|
44
|
+
return type(name, (cls,), {'__annotations__': kwargs})
|
45
|
+
else:
|
46
|
+
# Create a normal instance for runtime data
|
47
|
+
return super().__call__(*args, **kwargs)
|
48
|
+
|
49
|
+
|
50
|
+
class NamedFields(metaclass=NamedFieldsMeta):
|
51
|
+
"""A class that can be used to store named fields with values."""
|
52
|
+
|
53
|
+
def __init__(self, **kwargs):
|
54
|
+
for key, value in kwargs.items():
|
55
|
+
setattr(self, key, value)
|
56
|
+
|
57
|
+
def items(self):
|
58
|
+
return self.__dict__.items()
|
59
|
+
|
60
|
+
def keys(self):
|
61
|
+
return self.__dict__.keys()
|
62
|
+
|
63
|
+
def values(self):
|
64
|
+
return self.__dict__.values()
|
65
|
+
|
66
|
+
def __contains__(self, key):
|
67
|
+
return key in self.__dict__
|
68
|
+
|
69
|
+
def __getitem__(self, key):
|
70
|
+
return getattr(self, key)
|
71
|
+
|
72
|
+
def __setitem__(self, key, value):
|
73
|
+
setattr(self, key, value)
|
74
|
+
|
75
|
+
def __repr__(self):
|
76
|
+
return f"{self.__class__.__name__}({', '.join(f'{key}={value!r}' for key, value in self.__dict__.items())})"
|
77
|
+
|
78
|
+
def __origin__(self):
|
79
|
+
return self
|
80
|
+
|
81
|
+
def __args__(self):
|
82
|
+
return list(self.keys())
|
83
|
+
|
84
|
+
|
85
|
+
class JSON:
|
86
|
+
def __init__(self, value):
|
87
|
+
self.value = value
|
88
|
+
|
89
|
+
def __eq__(self, other):
|
90
|
+
return self.value == other
|
91
|
+
|
92
|
+
def __bool__(self):
|
93
|
+
return bool(self.value)
|
94
|
+
|
95
|
+
def __repr__(self):
|
96
|
+
return f"JSON({self.value})"
|
97
|
+
|
98
|
+
def to_json(self):
|
99
|
+
return json.dumps(self.value)
|
100
|
+
|
101
|
+
@classmethod
|
102
|
+
def from_json(cls, json_str):
|
103
|
+
return cls(json.loads(json_str))
|
104
|
+
|
105
|
+
@classmethod
|
106
|
+
def from_value(cls, value):
|
107
|
+
return cls(value)
|
108
|
+
|
109
|
+
def cast(self, python_type):
|
110
|
+
if not isinstance(self.value, python_type):
|
111
|
+
raise TypeError(f'Incompatible type {type(self.value)} for {python_type}')
|
112
|
+
return self.value
|
113
|
+
|
114
|
+
|
115
|
+
class Text(MessageData):
|
116
|
+
def __init__(self, text: str, url: str = None):
|
117
|
+
self.text = text
|
118
|
+
self.url = url
|
119
|
+
|
120
|
+
def __eq__(self, other):
|
121
|
+
if isinstance(other, Text):
|
122
|
+
return self.text == other.text and self.url == other.url
|
123
|
+
if isinstance(other, str):
|
124
|
+
return self.text == other
|
125
|
+
return False
|
126
|
+
|
127
|
+
def __bool__(self):
|
128
|
+
return bool(self.text) or bool(self.url)
|
129
|
+
|
130
|
+
def __repr__(self) -> str:
|
131
|
+
return f"Text(text={self.text!r}, url={self.url!r})"
|
132
|
+
|
133
|
+
def to_proto(self) -> TextProto:
|
134
|
+
return TextProto(raw=self.text or '', url=self.url or '')
|
135
|
+
|
136
|
+
@classmethod
|
137
|
+
def from_proto(cls, proto: TextProto) -> "Text":
|
138
|
+
return cls(proto.raw, proto.url or None)
|
139
|
+
|
140
|
+
@classmethod
|
141
|
+
def from_value(cls, value):
|
142
|
+
if isinstance(value, str):
|
143
|
+
return cls(value)
|
144
|
+
if isinstance(value, Text):
|
145
|
+
return value
|
146
|
+
if isinstance(value, dict):
|
147
|
+
return cls(value.get('text'), value.get('url'))
|
148
|
+
raise TypeError(f'Incompatible type for Text: {type(value)}')
|
149
|
+
|
150
|
+
def cast(self, python_type):
|
151
|
+
if python_type is str:
|
152
|
+
return self.text
|
153
|
+
if python_type is Text:
|
154
|
+
return self
|
155
|
+
raise TypeError(f'Incompatible type for Text: {python_type}')
|
156
|
+
|
157
|
+
|
158
|
+
class Concept(MessageData):
|
159
|
+
def __init__(self, name: str, value: float = 1):
|
160
|
+
self.id = name
|
161
|
+
self.name = name
|
162
|
+
self.value = value
|
163
|
+
|
164
|
+
def __repr__(self) -> str:
|
165
|
+
return f"Concept(id={self.id!r}, name={self.name!r}, value={self.value})"
|
166
|
+
|
167
|
+
def to_proto(self):
|
168
|
+
return ConceptProto(id=self.id, name=self.name, value=self.value)
|
169
|
+
|
170
|
+
@classmethod
|
171
|
+
def from_proto(cls, proto: ConceptProto) -> "Concept":
|
172
|
+
return cls(proto.name, proto.value)
|
173
|
+
|
174
|
+
|
175
|
+
class Region(MessageData):
|
176
|
+
def __init__(
|
177
|
+
self,
|
178
|
+
proto_region: RegionProto = None,
|
179
|
+
box: List[float] = None,
|
180
|
+
concepts: List[Concept] = None,
|
181
|
+
):
|
182
|
+
if proto_region is None:
|
183
|
+
proto_region = RegionProto()
|
184
|
+
self.proto = proto_region
|
185
|
+
# use setters for init vals
|
186
|
+
if (
|
187
|
+
box
|
188
|
+
and isinstance(box, list)
|
189
|
+
and len(box) == 4
|
190
|
+
and all(isinstance(val, (int, float)) for val in box)
|
191
|
+
):
|
192
|
+
self.box = box
|
193
|
+
if (
|
194
|
+
concepts
|
195
|
+
and isinstance(concepts, list)
|
196
|
+
and all(isinstance(concept, Concept) for concept in concepts)
|
197
|
+
):
|
198
|
+
self.concepts = concepts
|
199
|
+
|
200
|
+
@property
|
201
|
+
def box(self) -> List[float]:
|
202
|
+
bbox = self.proto.region_info.bounding_box
|
203
|
+
return [bbox.left_col, bbox.top_row, bbox.right_col, bbox.bottom_row] # x1, y1, x2, y2
|
204
|
+
|
205
|
+
@box.setter
|
206
|
+
def box(self, value: List[float]):
|
207
|
+
bbox = self.proto.region_info.bounding_box
|
208
|
+
bbox.left_col, bbox.top_row, bbox.right_col, bbox.bottom_row = value
|
209
|
+
|
210
|
+
@property
|
211
|
+
def concepts(self) -> List[Concept]:
|
212
|
+
return [Concept.from_proto(proto) for proto in self.proto.data.concepts]
|
213
|
+
|
214
|
+
@concepts.setter
|
215
|
+
def concepts(self, value: List[Concept]):
|
216
|
+
self.proto.data.concepts.extend([concept.to_proto() for concept in value])
|
217
|
+
|
218
|
+
def __repr__(self) -> str:
|
219
|
+
return f"Region(box={self.box}, concepts={self.concepts})"
|
220
|
+
|
221
|
+
def to_proto(self) -> RegionProto:
|
222
|
+
return self.proto
|
223
|
+
|
224
|
+
@classmethod
|
225
|
+
def from_proto(cls, proto: RegionProto) -> "Region":
|
226
|
+
return cls(proto)
|
227
|
+
|
228
|
+
|
229
|
+
class Image(MessageData):
|
230
|
+
def __init__(self, proto_image: ImageProto = None, url: str = None, bytes: bytes = None):
|
231
|
+
if proto_image is None:
|
232
|
+
proto_image = ImageProto()
|
233
|
+
self.proto = proto_image
|
234
|
+
# use setters for init vals
|
235
|
+
if url:
|
236
|
+
self.url = url
|
237
|
+
if bytes:
|
238
|
+
self.bytes = bytes
|
239
|
+
|
240
|
+
@property
|
241
|
+
def url(self) -> str:
|
242
|
+
return self.proto.url
|
243
|
+
|
244
|
+
@url.setter
|
245
|
+
def url(self, value: str):
|
246
|
+
self.proto.url = value
|
247
|
+
|
248
|
+
@property
|
249
|
+
def bytes(self) -> bytes:
|
250
|
+
return self.proto.base64
|
251
|
+
|
252
|
+
@bytes.setter
|
253
|
+
def bytes(self, value: bytes):
|
254
|
+
self.proto.base64 = value
|
255
|
+
|
256
|
+
def __repr__(self) -> str:
|
257
|
+
attrs = []
|
258
|
+
if self.url:
|
259
|
+
attrs.append(f"url={self.url!r}")
|
260
|
+
if self.bytes:
|
261
|
+
attrs.append(f"bytes=<{len(self.bytes)} bytes>")
|
262
|
+
return f"Image({', '.join(attrs)})"
|
263
|
+
|
264
|
+
@classmethod
|
265
|
+
def from_url(cls, url: str) -> "Image":
|
266
|
+
proto_image = ImageProto(url=url)
|
267
|
+
return cls(proto_image)
|
268
|
+
|
269
|
+
@classmethod
|
270
|
+
def from_pil(cls, pil_image: PILImage.Image) -> "Image":
|
271
|
+
with io.BytesIO() as output:
|
272
|
+
pil_image.save(output, format="PNG")
|
273
|
+
image_bytes = output.getvalue()
|
274
|
+
proto_image = ImageProto(base64=image_bytes)
|
275
|
+
return cls(proto_image)
|
276
|
+
|
277
|
+
def to_pil(self) -> PILImage.Image:
|
278
|
+
if not self.proto.base64:
|
279
|
+
raise ValueError("Image has no bytes")
|
280
|
+
return PILImage.open(io.BytesIO(self.proto.base64))
|
281
|
+
|
282
|
+
def to_numpy(self) -> np.ndarray:
|
283
|
+
return np.asarray(self.to_pil())
|
284
|
+
|
285
|
+
def to_proto(self) -> ImageProto:
|
286
|
+
return self.proto
|
287
|
+
|
288
|
+
@classmethod
|
289
|
+
def from_proto(cls, proto: ImageProto) -> "Image":
|
290
|
+
return cls(proto)
|
291
|
+
|
292
|
+
@classmethod
|
293
|
+
def from_value(cls, value):
|
294
|
+
if isinstance(value, PILImage.Image):
|
295
|
+
return cls.from_pil(value)
|
296
|
+
if isinstance(value, Image):
|
297
|
+
return value
|
298
|
+
raise TypeError(f'Incompatible type for Image: {type(value)}')
|
299
|
+
|
300
|
+
def cast(self, python_type):
|
301
|
+
if python_type is Image:
|
302
|
+
return self
|
303
|
+
if python_type is PILImage.Image or python_type is PILImage:
|
304
|
+
return self.to_pil()
|
305
|
+
if python_type is np.ndarray or get_origin(python_type) is np.ndarray:
|
306
|
+
return self.to_numpy()
|
307
|
+
raise TypeError(f'Incompatible type for Image: {python_type}')
|
308
|
+
|
309
|
+
|
310
|
+
class Audio(MessageData):
|
311
|
+
def __init__(self, proto_audio: AudioProto = None, url: str = None, bytes: bytes = None):
|
312
|
+
if proto_audio is None:
|
313
|
+
proto_audio = AudioProto()
|
314
|
+
self.proto = proto_audio
|
315
|
+
|
316
|
+
if url:
|
317
|
+
self.url = url
|
318
|
+
if bytes:
|
319
|
+
self.bytes = bytes
|
320
|
+
|
321
|
+
@property
|
322
|
+
def url(self) -> str:
|
323
|
+
return self.proto.url
|
324
|
+
|
325
|
+
@url.setter
|
326
|
+
def url(self, value: str):
|
327
|
+
self.proto.url = value
|
328
|
+
|
329
|
+
@property
|
330
|
+
def bytes(self) -> bytes:
|
331
|
+
return self.proto.base64
|
332
|
+
|
333
|
+
@bytes.setter
|
334
|
+
def bytes(self, value: bytes):
|
335
|
+
self.proto.base64 = value
|
336
|
+
|
337
|
+
@classmethod
|
338
|
+
def from_url(cls, url: str) -> "Audio":
|
339
|
+
proto_audio = AudioProto(url=url)
|
340
|
+
return cls(proto_audio)
|
341
|
+
|
342
|
+
def __repr__(self) -> str:
|
343
|
+
attrs = []
|
344
|
+
if self.url:
|
345
|
+
attrs.append(f"url={self.url!r}")
|
346
|
+
if self.bytes:
|
347
|
+
attrs.append(f"bytes=<{len(self.bytes)} bytes>")
|
348
|
+
return f"Audio({', '.join(attrs)})"
|
349
|
+
|
350
|
+
def to_proto(self) -> AudioProto:
|
351
|
+
return self.proto
|
352
|
+
|
353
|
+
@classmethod
|
354
|
+
def from_proto(cls, proto: AudioProto) -> "Audio":
|
355
|
+
return cls(proto)
|
356
|
+
|
357
|
+
|
358
|
+
class Frame(MessageData):
|
359
|
+
def __init__(
|
360
|
+
self,
|
361
|
+
proto_frame: FrameProto = None,
|
362
|
+
image: Image = None,
|
363
|
+
regions: List[Region] = None,
|
364
|
+
time: float = None,
|
365
|
+
):
|
366
|
+
if proto_frame is None:
|
367
|
+
proto_frame = FrameProto()
|
368
|
+
self.proto = proto_frame
|
369
|
+
# use setters for init vals
|
370
|
+
if image:
|
371
|
+
self.image = image
|
372
|
+
if regions:
|
373
|
+
self.regions = regions
|
374
|
+
if time:
|
375
|
+
self.time = time
|
376
|
+
|
377
|
+
@property
|
378
|
+
def time(self) -> float:
|
379
|
+
# TODO: time is a uint32, so this will overflow at 49.7 days
|
380
|
+
# we should be using double or uint64 in the proto instead
|
381
|
+
return self.proto.frame_info.time / 1000.0
|
382
|
+
|
383
|
+
@time.setter
|
384
|
+
def time(self, value: float):
|
385
|
+
self.proto.frame_info.time = int(value * 1000)
|
386
|
+
|
387
|
+
@property
|
388
|
+
def image(self) -> Image:
|
389
|
+
return Image.from_proto(self.proto.data.image)
|
390
|
+
|
391
|
+
@image.setter
|
392
|
+
def image(self, value: Image):
|
393
|
+
self.proto.data.image.CopyFrom(value.to_proto())
|
394
|
+
|
395
|
+
@property
|
396
|
+
def regions(self) -> List[Region]:
|
397
|
+
return [Region(region) for region in self.proto.data.regions]
|
398
|
+
|
399
|
+
@regions.setter
|
400
|
+
def regions(self, value: List[Region]):
|
401
|
+
self.proto.data.regions.extend([region.proto for region in value])
|
402
|
+
|
403
|
+
def to_proto(self) -> FrameProto:
|
404
|
+
return self.proto
|
405
|
+
|
406
|
+
@classmethod
|
407
|
+
def from_proto(cls, proto: FrameProto) -> "Frame":
|
408
|
+
return cls(proto)
|
409
|
+
|
410
|
+
|
411
|
+
class Video(MessageData):
|
412
|
+
def __init__(self, proto_video: VideoProto = None, url: str = None, bytes: bytes = None):
|
413
|
+
if proto_video is None:
|
414
|
+
proto_video = VideoProto()
|
415
|
+
self.proto = proto_video
|
416
|
+
|
417
|
+
if url:
|
418
|
+
self.url = url
|
419
|
+
if bytes:
|
420
|
+
self.bytes = bytes
|
421
|
+
|
422
|
+
@property
|
423
|
+
def url(self) -> str:
|
424
|
+
return self.proto.url
|
425
|
+
|
426
|
+
@url.setter
|
427
|
+
def url(self, value: str):
|
428
|
+
self.proto.url = value
|
429
|
+
|
430
|
+
@property
|
431
|
+
def bytes(self) -> bytes:
|
432
|
+
return self.proto.base64
|
433
|
+
|
434
|
+
@bytes.setter
|
435
|
+
def bytes(self, value: bytes):
|
436
|
+
self.proto.base64 = value
|
437
|
+
|
438
|
+
@classmethod
|
439
|
+
def from_url(cls, url: str) -> "Video":
|
440
|
+
proto_video = VideoProto(url=url)
|
441
|
+
return cls(proto_video)
|
442
|
+
|
443
|
+
def __repr__(self) -> str:
|
444
|
+
attrs = []
|
445
|
+
if self.url:
|
446
|
+
attrs.append(f"url={self.url!r}")
|
447
|
+
if self.bytes:
|
448
|
+
attrs.append(f"bytes=<{len(self.bytes)} bytes>")
|
449
|
+
return f"Video({', '.join(attrs)})"
|
450
|
+
|
451
|
+
def to_proto(self) -> VideoProto:
|
452
|
+
return self.proto
|
453
|
+
|
454
|
+
@classmethod
|
455
|
+
def from_proto(cls, proto: VideoProto) -> "Video":
|
456
|
+
return cls(proto)
|
457
|
+
|
458
|
+
|
459
|
+
def cast(value, python_type):
|
460
|
+
list_type = get_origin(python_type) is list
|
461
|
+
if isinstance(value, MessageData):
|
462
|
+
return value.cast(python_type)
|
463
|
+
if list_type and isinstance(value, np.ndarray):
|
464
|
+
return value.tolist()
|
465
|
+
if list_type and isinstance(value, list):
|
466
|
+
if get_args(python_type):
|
467
|
+
inner_type = get_args(python_type)[0]
|
468
|
+
return [cast(item, inner_type) for item in value]
|
469
|
+
if not isinstance(value, Iterable):
|
470
|
+
raise TypeError(f'Expected list, got {type(value)}')
|
471
|
+
return value
|