clarifai 11.1.7rc3__py3-none-any.whl → 11.2.0__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 (154) hide show
  1. clarifai/__init__.py +1 -1
  2. clarifai/cli/base.py +16 -3
  3. clarifai/cli/model.py +0 -25
  4. clarifai/client/model.py +393 -157
  5. clarifai/runners/__init__.py +7 -2
  6. clarifai/runners/models/model_builder.py +12 -80
  7. clarifai/runners/models/model_class.py +28 -279
  8. clarifai/runners/models/model_run_locally.py +80 -15
  9. clarifai/runners/models/model_runner.py +0 -2
  10. clarifai/runners/models/model_servicer.py +2 -11
  11. clarifai/runners/utils/data_handler.py +210 -271
  12. {clarifai-11.1.7rc3.dist-info → clarifai-11.2.0.dist-info}/METADATA +16 -4
  13. clarifai-11.2.0.dist-info/RECORD +101 -0
  14. {clarifai-11.1.7rc3.dist-info → clarifai-11.2.0.dist-info}/WHEEL +1 -1
  15. clarifai/__pycache__/__init__.cpython-310.pyc +0 -0
  16. clarifai/__pycache__/__init__.cpython-39.pyc +0 -0
  17. clarifai/__pycache__/errors.cpython-310.pyc +0 -0
  18. clarifai/__pycache__/versions.cpython-310.pyc +0 -0
  19. clarifai/cli/__pycache__/__init__.cpython-310.pyc +0 -0
  20. clarifai/cli/__pycache__/base.cpython-310.pyc +0 -0
  21. clarifai/cli/__pycache__/base_cli.cpython-310.pyc +0 -0
  22. clarifai/cli/__pycache__/compute_cluster.cpython-310.pyc +0 -0
  23. clarifai/cli/__pycache__/deployment.cpython-310.pyc +0 -0
  24. clarifai/cli/__pycache__/model.cpython-310.pyc +0 -0
  25. clarifai/cli/__pycache__/model_cli.cpython-310.pyc +0 -0
  26. clarifai/cli/__pycache__/nodepool.cpython-310.pyc +0 -0
  27. clarifai/client/__pycache__/__init__.cpython-310.pyc +0 -0
  28. clarifai/client/__pycache__/__init__.cpython-39.pyc +0 -0
  29. clarifai/client/__pycache__/app.cpython-310.pyc +0 -0
  30. clarifai/client/__pycache__/app.cpython-39.pyc +0 -0
  31. clarifai/client/__pycache__/base.cpython-310.pyc +0 -0
  32. clarifai/client/__pycache__/compute_cluster.cpython-310.pyc +0 -0
  33. clarifai/client/__pycache__/dataset.cpython-310.pyc +0 -0
  34. clarifai/client/__pycache__/deployment.cpython-310.pyc +0 -0
  35. clarifai/client/__pycache__/input.cpython-310.pyc +0 -0
  36. clarifai/client/__pycache__/lister.cpython-310.pyc +0 -0
  37. clarifai/client/__pycache__/model.cpython-310.pyc +0 -0
  38. clarifai/client/__pycache__/module.cpython-310.pyc +0 -0
  39. clarifai/client/__pycache__/nodepool.cpython-310.pyc +0 -0
  40. clarifai/client/__pycache__/search.cpython-310.pyc +0 -0
  41. clarifai/client/__pycache__/user.cpython-310.pyc +0 -0
  42. clarifai/client/__pycache__/workflow.cpython-310.pyc +0 -0
  43. clarifai/client/auth/__pycache__/__init__.cpython-310.pyc +0 -0
  44. clarifai/client/auth/__pycache__/helper.cpython-310.pyc +0 -0
  45. clarifai/client/auth/__pycache__/register.cpython-310.pyc +0 -0
  46. clarifai/client/auth/__pycache__/stub.cpython-310.pyc +0 -0
  47. clarifai/client/cli/__init__.py +0 -0
  48. clarifai/client/cli/__pycache__/__init__.cpython-310.pyc +0 -0
  49. clarifai/client/cli/__pycache__/base_cli.cpython-310.pyc +0 -0
  50. clarifai/client/cli/__pycache__/model_cli.cpython-310.pyc +0 -0
  51. clarifai/client/cli/base_cli.py +0 -88
  52. clarifai/client/cli/model_cli.py +0 -29
  53. clarifai/client/model_client.py +0 -448
  54. clarifai/constants/__pycache__/base.cpython-310.pyc +0 -0
  55. clarifai/constants/__pycache__/dataset.cpython-310.pyc +0 -0
  56. clarifai/constants/__pycache__/input.cpython-310.pyc +0 -0
  57. clarifai/constants/__pycache__/model.cpython-310.pyc +0 -0
  58. clarifai/constants/__pycache__/rag.cpython-310.pyc +0 -0
  59. clarifai/constants/__pycache__/search.cpython-310.pyc +0 -0
  60. clarifai/constants/__pycache__/workflow.cpython-310.pyc +0 -0
  61. clarifai/datasets/__pycache__/__init__.cpython-310.pyc +0 -0
  62. clarifai/datasets/__pycache__/__init__.cpython-39.pyc +0 -0
  63. clarifai/datasets/export/__pycache__/__init__.cpython-310.pyc +0 -0
  64. clarifai/datasets/export/__pycache__/__init__.cpython-39.pyc +0 -0
  65. clarifai/datasets/export/__pycache__/inputs_annotations.cpython-310.pyc +0 -0
  66. clarifai/datasets/upload/__pycache__/__init__.cpython-310.pyc +0 -0
  67. clarifai/datasets/upload/__pycache__/__init__.cpython-39.pyc +0 -0
  68. clarifai/datasets/upload/__pycache__/base.cpython-310.pyc +0 -0
  69. clarifai/datasets/upload/__pycache__/features.cpython-310.pyc +0 -0
  70. clarifai/datasets/upload/__pycache__/image.cpython-310.pyc +0 -0
  71. clarifai/datasets/upload/__pycache__/multimodal.cpython-310.pyc +0 -0
  72. clarifai/datasets/upload/__pycache__/text.cpython-310.pyc +0 -0
  73. clarifai/datasets/upload/__pycache__/utils.cpython-310.pyc +0 -0
  74. clarifai/datasets/upload/loaders/__pycache__/__init__.cpython-39.pyc +0 -0
  75. clarifai/models/__pycache__/__init__.cpython-39.pyc +0 -0
  76. clarifai/modules/__pycache__/__init__.cpython-39.pyc +0 -0
  77. clarifai/rag/__pycache__/__init__.cpython-310.pyc +0 -0
  78. clarifai/rag/__pycache__/__init__.cpython-39.pyc +0 -0
  79. clarifai/rag/__pycache__/rag.cpython-310.pyc +0 -0
  80. clarifai/rag/__pycache__/rag.cpython-39.pyc +0 -0
  81. clarifai/rag/__pycache__/utils.cpython-310.pyc +0 -0
  82. clarifai/runners/__pycache__/__init__.cpython-310.pyc +0 -0
  83. clarifai/runners/__pycache__/__init__.cpython-39.pyc +0 -0
  84. clarifai/runners/dockerfile_template/Dockerfile.cpu.template +0 -31
  85. clarifai/runners/dockerfile_template/Dockerfile.cuda.template +0 -42
  86. clarifai/runners/dockerfile_template/Dockerfile.nim +0 -71
  87. clarifai/runners/models/__pycache__/__init__.cpython-310.pyc +0 -0
  88. clarifai/runners/models/__pycache__/__init__.cpython-39.pyc +0 -0
  89. clarifai/runners/models/__pycache__/base_typed_model.cpython-310.pyc +0 -0
  90. clarifai/runners/models/__pycache__/base_typed_model.cpython-39.pyc +0 -0
  91. clarifai/runners/models/__pycache__/model_class.cpython-310.pyc +0 -0
  92. clarifai/runners/models/__pycache__/model_run_locally.cpython-310-pytest-7.1.2.pyc +0 -0
  93. clarifai/runners/models/__pycache__/model_run_locally.cpython-310.pyc +0 -0
  94. clarifai/runners/models/__pycache__/model_runner.cpython-310.pyc +0 -0
  95. clarifai/runners/models/__pycache__/model_upload.cpython-310.pyc +0 -0
  96. clarifai/runners/models/model_class_refract.py +0 -80
  97. clarifai/runners/models/model_upload.py +0 -607
  98. clarifai/runners/models/temp.py +0 -25
  99. clarifai/runners/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  100. clarifai/runners/utils/__pycache__/__init__.cpython-38.pyc +0 -0
  101. clarifai/runners/utils/__pycache__/__init__.cpython-39.pyc +0 -0
  102. clarifai/runners/utils/__pycache__/buffered_stream.cpython-310.pyc +0 -0
  103. clarifai/runners/utils/__pycache__/buffered_stream.cpython-38.pyc +0 -0
  104. clarifai/runners/utils/__pycache__/buffered_stream.cpython-39.pyc +0 -0
  105. clarifai/runners/utils/__pycache__/const.cpython-310.pyc +0 -0
  106. clarifai/runners/utils/__pycache__/constants.cpython-310.pyc +0 -0
  107. clarifai/runners/utils/__pycache__/constants.cpython-38.pyc +0 -0
  108. clarifai/runners/utils/__pycache__/constants.cpython-39.pyc +0 -0
  109. clarifai/runners/utils/__pycache__/data_handler.cpython-310.pyc +0 -0
  110. clarifai/runners/utils/__pycache__/data_handler.cpython-38.pyc +0 -0
  111. clarifai/runners/utils/__pycache__/data_handler.cpython-39.pyc +0 -0
  112. clarifai/runners/utils/__pycache__/data_utils.cpython-310.pyc +0 -0
  113. clarifai/runners/utils/__pycache__/data_utils.cpython-38.pyc +0 -0
  114. clarifai/runners/utils/__pycache__/data_utils.cpython-39.pyc +0 -0
  115. clarifai/runners/utils/__pycache__/grpc_server.cpython-310.pyc +0 -0
  116. clarifai/runners/utils/__pycache__/grpc_server.cpython-38.pyc +0 -0
  117. clarifai/runners/utils/__pycache__/grpc_server.cpython-39.pyc +0 -0
  118. clarifai/runners/utils/__pycache__/health.cpython-310.pyc +0 -0
  119. clarifai/runners/utils/__pycache__/health.cpython-38.pyc +0 -0
  120. clarifai/runners/utils/__pycache__/health.cpython-39.pyc +0 -0
  121. clarifai/runners/utils/__pycache__/loader.cpython-310.pyc +0 -0
  122. clarifai/runners/utils/__pycache__/logging.cpython-310.pyc +0 -0
  123. clarifai/runners/utils/__pycache__/logging.cpython-38.pyc +0 -0
  124. clarifai/runners/utils/__pycache__/logging.cpython-39.pyc +0 -0
  125. clarifai/runners/utils/__pycache__/stream_source.cpython-310.pyc +0 -0
  126. clarifai/runners/utils/__pycache__/stream_source.cpython-39.pyc +0 -0
  127. clarifai/runners/utils/__pycache__/url_fetcher.cpython-310.pyc +0 -0
  128. clarifai/runners/utils/__pycache__/url_fetcher.cpython-38.pyc +0 -0
  129. clarifai/runners/utils/__pycache__/url_fetcher.cpython-39.pyc +0 -0
  130. clarifai/runners/utils/data_handler_refract.py +0 -213
  131. clarifai/runners/utils/data_types.py +0 -427
  132. clarifai/runners/utils/logger.py +0 -0
  133. clarifai/runners/utils/method_signatures.py +0 -477
  134. clarifai/runners/utils/serializers.py +0 -222
  135. clarifai/schema/__pycache__/search.cpython-310.pyc +0 -0
  136. clarifai/urls/__pycache__/helper.cpython-310.pyc +0 -0
  137. clarifai/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  138. clarifai/utils/__pycache__/__init__.cpython-39.pyc +0 -0
  139. clarifai/utils/__pycache__/cli.cpython-310.pyc +0 -0
  140. clarifai/utils/__pycache__/constants.cpython-310.pyc +0 -0
  141. clarifai/utils/__pycache__/logging.cpython-310.pyc +0 -0
  142. clarifai/utils/__pycache__/misc.cpython-310.pyc +0 -0
  143. clarifai/utils/__pycache__/model_train.cpython-310.pyc +0 -0
  144. clarifai/utils/evaluation/__pycache__/__init__.cpython-39.pyc +0 -0
  145. clarifai/utils/evaluation/__pycache__/main.cpython-39.pyc +0 -0
  146. clarifai/workflows/__pycache__/__init__.cpython-310.pyc +0 -0
  147. clarifai/workflows/__pycache__/__init__.cpython-39.pyc +0 -0
  148. clarifai/workflows/__pycache__/export.cpython-310.pyc +0 -0
  149. clarifai/workflows/__pycache__/utils.cpython-310.pyc +0 -0
  150. clarifai/workflows/__pycache__/validate.cpython-310.pyc +0 -0
  151. clarifai-11.1.7rc3.dist-info/RECORD +0 -237
  152. {clarifai-11.1.7rc3.dist-info → clarifai-11.2.0.dist-info}/entry_points.txt +0 -0
  153. {clarifai-11.1.7rc3.dist-info → clarifai-11.2.0.dist-info/licenses}/LICENSE +0 -0
  154. {clarifai-11.1.7rc3.dist-info → clarifai-11.2.0.dist-info}/top_level.txt +0 -0
@@ -1,213 +0,0 @@
1
- import io
2
- from typing import Any, Callable, Dict, Type
3
-
4
- import numpy as np
5
- from clarifai_grpc.grpc.api import resources_pb2
6
- from clarifai_grpc.grpc.api.resources_pb2 import Audio as AudioProto
7
- from clarifai_grpc.grpc.api.resources_pb2 import Image as ImageProto
8
- from clarifai_grpc.grpc.api.resources_pb2 import NDArray
9
- from clarifai_grpc.grpc.api.resources_pb2 import Text as TextProto
10
- from clarifai_grpc.grpc.api.resources_pb2 import Video as VideoProto
11
- from google.protobuf.json_format import MessageToDict, ParseDict
12
- from google.protobuf.struct_pb2 import Struct
13
- from PIL import Image as PILImage
14
-
15
- # Type registry for conversion between Python types and protobuf
16
- _TYPE_HANDLERS: Dict[Type, Callable] = {
17
- # Python type: (to_proto, from_proto)
18
- TextProto: (
19
- lambda value: value.to_proto(),
20
- lambda proto: Text.from_proto(proto)
21
- ),
22
- ImageProto: (
23
- lambda value: value.to_proto(),
24
- lambda proto: Image(proto)
25
- ),
26
- AudioProto: (
27
- lambda value: value.to_proto(),
28
- lambda proto: Audio(proto)
29
- ),
30
- VideoProto: (
31
- lambda value: value.to_proto(),
32
- lambda proto: Video(proto)
33
- ),
34
- str: (
35
- lambda value: TextProto(raw=value),
36
- lambda proto: proto.raw
37
- ),
38
- bytes: (
39
- lambda value: resources_pb2.Data(base64=value),
40
- lambda proto: proto.base64
41
- ),
42
- int: (
43
- lambda value: resources_pb2.Data(int_value=value),
44
- lambda proto: proto.int_value
45
- ),
46
- float: (
47
- lambda value: resources_pb2.Data(float_value=value),
48
- lambda proto: proto.float_value
49
- ),
50
- bool: (
51
- lambda value: resources_pb2.Data(boolean=value),
52
- lambda proto: proto.boolean
53
- ),
54
- np.ndarray: (
55
- lambda value: NDArray(buffer=value.tobytes(), shape=value.shape, dtype=str(value.dtype)),
56
- lambda proto: np.frombuffer(proto.buffer, dtype=np.dtype(proto.dtype)).reshape(proto.shape)
57
- ),
58
- PILImage.Image: (
59
- lambda value: Image.from_pil(value).to_proto(),
60
- lambda proto: Image(proto).to_pil()
61
- ),
62
- dict: (
63
- lambda value: _dict_to_metadata(value),
64
- lambda proto: MessageToDict(proto.metadata)
65
- )
66
- }
67
-
68
-
69
- def _dict_to_metadata(metadata: dict) -> Struct:
70
- struct = Struct()
71
- ParseDict(metadata, struct)
72
- return struct
73
-
74
-
75
- def _value_to_proto(value: Any) -> resources_pb2.Data:
76
- """Convert a Python value to a protobuf Data message."""
77
- data = resources_pb2.Data()
78
- for py_type, (to_proto, _) in _TYPE_HANDLERS.items():
79
- if isinstance(value, py_type):
80
- handler = to_proto
81
- break
82
- else:
83
- if isinstance(value, (Text, Image, Audio, Video)):
84
- data_part = getattr(data, type(value).__name__.lower())
85
- data_part.CopyFrom(value.to_proto())
86
- return data
87
- raise TypeError(f"Unsupported type: {type(value)}")
88
-
89
- result = handler(value)
90
- if isinstance(result, resources_pb2.Data):
91
- data.CopyFrom(result)
92
- else:
93
- field_name = type(result).DESCRIPTOR.name.lower()
94
- getattr(data, field_name).CopyFrom(result)
95
- return data
96
-
97
-
98
- def _proto_to_value(proto: resources_pb2.Data) -> Any:
99
- """Convert a protobuf Data message to a Python value."""
100
- for field in proto.DESCRIPTOR.fields:
101
- if proto.HasField(field.name):
102
- _, from_proto = _TYPE_HANDLERS.get(field.type, (None, None))
103
- if from_proto:
104
- return from_proto(getattr(proto, field.name))
105
- if proto.parts:
106
- return [_proto_to_value(part.data) for part in proto.parts]
107
- return None
108
-
109
-
110
- def kwargs_to_proto(**kwargs) -> resources_pb2.Data:
111
- """Convert keyword arguments to a Data proto."""
112
- data_proto = resources_pb2.Data()
113
- for part_name, part_value in kwargs.items():
114
- part = data_proto.parts.add()
115
- part.id = part_name
116
-
117
- if isinstance(part_value, list):
118
- for item in part_value:
119
- item_proto = _value_to_proto(item)
120
- part_part = part.data.parts.add()
121
- part_part.data.CopyFrom(item_proto)
122
- else:
123
- part_proto = _value_to_proto(part_value)
124
- part.data.CopyFrom(part_proto)
125
- return data_proto
126
-
127
-
128
- def proto_to_kwargs(data: resources_pb2.Data) -> dict:
129
- """Convert a Data proto to keyword arguments."""
130
- kwargs = {}
131
- for part in data.parts:
132
- part_name = part.id
133
- if part.data.parts:
134
- kwargs[part_name] = [_proto_to_value(part.data) for _ in part.data.parts]
135
- else:
136
- kwargs[part_name] = _proto_to_value(part.data)
137
- return kwargs
138
-
139
-
140
- class Output:
141
-
142
- def __init__(self, **kwargs: Any):
143
- if not kwargs:
144
- raise ValueError("Output must have at least one key-value pair")
145
- self.parts = kwargs
146
-
147
- def to_proto(self) -> resources_pb2.Output:
148
- data_proto = kwargs_to_proto(**self.parts)
149
- return resources_pb2.Output(data=data_proto)
150
-
151
-
152
- class Text:
153
-
154
- def __init__(self, text: str):
155
- self.text = text
156
-
157
- def to_proto(self) -> TextProto:
158
- return TextProto(raw=self.text)
159
-
160
- @classmethod
161
- def from_proto(cls, proto: TextProto) -> "Text":
162
- return cls(proto.raw)
163
-
164
-
165
- class Image:
166
-
167
- def __init__(self, proto_image: ImageProto):
168
- self.proto = proto_image
169
-
170
- @classmethod
171
- def from_url(cls, url: str) -> "Image":
172
- return cls(ImageProto(url=url))
173
-
174
- @classmethod
175
- def from_pil(cls, pil_image: PILImage.Image) -> "Image":
176
- with io.BytesIO() as output:
177
- pil_image.save(output, format="PNG")
178
- return cls(ImageProto(base64=output.getvalue()))
179
-
180
- def to_pil(self) -> PILImage.Image:
181
- return PILImage.open(io.BytesIO(self.proto.base64))
182
-
183
- def to_proto(self) -> ImageProto:
184
- return self.proto
185
-
186
-
187
- class Audio:
188
-
189
- def __init__(self, proto_audio: AudioProto):
190
- self.proto = proto_audio
191
-
192
- def to_proto(self) -> AudioProto:
193
- return self.proto
194
-
195
-
196
- class Video:
197
-
198
- def __init__(self, proto_video: VideoProto):
199
- self.proto = proto_video
200
-
201
- def to_proto(self) -> VideoProto:
202
- return self.proto
203
-
204
-
205
- '''
206
- Type Handling Registry: Centralized conversion logic reduces duplication and enhances extensibility.
207
- Simplified Conversion Functions: _value_to_proto and _proto_to_value handle all type conversions using the registry.
208
- Streamlined Wrapper Methods: Common processing logic extracted into _process_request, reducing code duplication.
209
- Improved Batch Processing: Uses ThreadPoolExecutor.map for cleaner batch prediction.
210
- Error Handling: Clearer error messages and validation of required parameters.
211
- Removed Redundant Checks: Simplified Output class initialization.
212
-
213
- '''
@@ -1,427 +0,0 @@
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
-
18
- def to_proto(self):
19
- raise NotImplementedError
20
-
21
- @classmethod
22
- def from_proto(cls, proto):
23
- raise NotImplementedError
24
-
25
- @classmethod
26
- def from_value(cls, value):
27
- if isinstance(value, cls):
28
- return value
29
- return cls(value)
30
-
31
- def cast(self, python_type):
32
- if python_type == self.__class__:
33
- return self
34
- raise TypeError(f'Incompatible type for {self.__class__.__name__}: {python_type}')
35
-
36
-
37
- class NamedFieldsMeta(type):
38
- """Metaclass to create NamedFields subclasses with __annotations__ when fields are specified."""
39
-
40
- def __call__(cls, *args, **kwargs):
41
- # Check if keyword arguments are types (used in type annotations)
42
- if kwargs and all(isinstance(v, type) for v in kwargs.values()):
43
- # Dynamically create a subclass with __annotations__
44
- name = f"NamedFields({', '.join(f'{k}:{v.__name__}' for k, v in kwargs.items())})"
45
- return type(name, (cls,), {'__annotations__': kwargs})
46
- else:
47
- # Create a normal instance for runtime data
48
- return super().__call__(*args, **kwargs)
49
-
50
-
51
- class NamedFields(metaclass=NamedFieldsMeta):
52
- """A class that can be used to store named fields with values."""
53
-
54
- def __init__(self, **kwargs):
55
- for key, value in kwargs.items():
56
- setattr(self, key, value)
57
-
58
- def items(self):
59
- return self.__dict__.items()
60
-
61
- def keys(self):
62
- return self.__dict__.keys()
63
-
64
- def values(self):
65
- return self.__dict__.values()
66
-
67
- def __contains__(self, key):
68
- return key in self.__dict__
69
-
70
- def __getitem__(self, key):
71
- return getattr(self, key)
72
-
73
- def __setitem__(self, key, value):
74
- setattr(self, key, value)
75
-
76
- def __repr__(self):
77
- return f"{self.__class__.__name__}({', '.join(f'{key}={value!r}' for key, value in self.__dict__.items())})"
78
-
79
- def __origin__(self):
80
- return self
81
-
82
- def __args__(self):
83
- return list(self.keys())
84
-
85
-
86
- class Stream(Iterable):
87
- pass
88
-
89
-
90
- class JSON:
91
-
92
- def __init__(self, value):
93
- self.value = value
94
-
95
- def __eq__(self, other):
96
- return self.value == other
97
-
98
- def __bool__(self):
99
- return bool(self.value)
100
-
101
- def to_json(self):
102
- return json.dumps(self.value)
103
-
104
- @classmethod
105
- def from_json(cls, json_str):
106
- return cls(json.loads(json_str))
107
-
108
- @classmethod
109
- def from_value(cls, value):
110
- return cls(value)
111
-
112
- def cast(self, python_type):
113
- if not isinstance(self.value, python_type):
114
- raise TypeError(f'Incompatible type {type(self.value)} for {python_type}')
115
- return self.value
116
-
117
-
118
- class Text(MessageData):
119
-
120
- def __init__(self, text: str, url: str = None):
121
- self.text = text
122
- self.url = url
123
-
124
- def __eq__(self, other):
125
- if isinstance(other, Text):
126
- return self.text == other.text and self.url == other.url
127
- if isinstance(other, str):
128
- return self.text == other
129
- return False
130
-
131
- def __bool__(self):
132
- return bool(self.text) or bool(self.url)
133
-
134
- def to_proto(self) -> TextProto:
135
- return TextProto(raw=self.text or '', url=self.url or '')
136
-
137
- @classmethod
138
- def from_proto(cls, proto: TextProto) -> "Text":
139
- return cls(proto.raw, proto.url or None)
140
-
141
- @classmethod
142
- def from_value(cls, value):
143
- if isinstance(value, str):
144
- return cls(value)
145
- if isinstance(value, Text):
146
- return value
147
- if isinstance(value, dict):
148
- return cls(value.get('text'), value.get('url'))
149
- raise TypeError(f'Incompatible type for Text: {type(value)}')
150
-
151
- def cast(self, python_type):
152
- if python_type == str:
153
- return self.text
154
- if python_type == Text:
155
- return self
156
- raise TypeError(f'Incompatible type for Text: {python_type}')
157
-
158
-
159
- class Concept(MessageData):
160
-
161
- def __init__(self, name: str, value: float = 0):
162
- self.name = name
163
- self.value = value
164
-
165
- def __repr__(self) -> str:
166
- return f"Concept(name={self.name!r}, value={self.value})"
167
-
168
- def to_proto(self):
169
- return ConceptProto(name=self.name, value=self.value)
170
-
171
- @classmethod
172
- def from_proto(cls, proto: ConceptProto) -> "Concept":
173
- return cls(proto.name, proto.value)
174
-
175
-
176
- class Region(MessageData):
177
-
178
- def __init__(self, proto_region: RegionProto):
179
- self.proto = proto_region
180
-
181
- @property
182
- def box(self) -> List[float]:
183
- bbox = self.proto.region_info.bounding_box
184
- return [bbox.left_col, bbox.top_row, bbox.right_col, bbox.bottom_row] # x1, y1, x2, y2
185
-
186
- @box.setter
187
- def box(self, value: List[float]):
188
- bbox = self.proto.region_info.bounding_box
189
- bbox.left_col, bbox.top_row, bbox.right_col, bbox.bottom_row = value
190
-
191
- @property
192
- def concepts(self) -> List[Concept]:
193
- return [Concept.from_proto(proto) for proto in self.proto.data.concepts]
194
-
195
- @concepts.setter
196
- def concepts(self, value: List[Concept]):
197
- self.proto.data.concepts.extend([concept.to_proto() for concept in value])
198
-
199
- def __repr__(self) -> str:
200
- return f"Region(box={self.box}, concepts={self.concepts})"
201
-
202
- def to_proto(self) -> RegionProto:
203
- return self.proto
204
-
205
- @classmethod
206
- def from_proto(cls, proto: RegionProto) -> "Region":
207
- return cls(proto)
208
-
209
-
210
- class Image(MessageData):
211
-
212
- def __init__(self, proto_image: ImageProto = None, url: str = None, bytes: bytes = None):
213
- if proto_image is None:
214
- proto_image = ImageProto()
215
- self.proto = proto_image
216
- # use setters for init vals
217
- if url:
218
- self.url = url
219
- if bytes:
220
- self.bytes = bytes
221
-
222
- @property
223
- def url(self) -> str:
224
- return self.proto.url
225
-
226
- @url.setter
227
- def url(self, value: str):
228
- self.proto.url = value
229
-
230
- @property
231
- def bytes(self) -> bytes:
232
- return self.proto.base64
233
-
234
- @bytes.setter
235
- def bytes(self, value: bytes):
236
- self.proto.base64 = value
237
-
238
- def __repr__(self) -> str:
239
- attrs = []
240
- if self.url:
241
- attrs.append(f"url={self.url!r}")
242
- if self.bytes:
243
- attrs.append(f"bytes=<{len(self.bytes)} bytes>")
244
- return f"Image({', '.join(attrs)})"
245
-
246
- @classmethod
247
- def from_url(cls, url: str) -> "Image":
248
- proto_image = ImageProto(url=url)
249
- return cls(proto_image)
250
-
251
- @classmethod
252
- def from_pil(cls, pil_image: PILImage.Image) -> "Image":
253
- with io.BytesIO() as output:
254
- pil_image.save(output, format="PNG")
255
- image_bytes = output.getvalue()
256
- proto_image = ImageProto(base64=image_bytes)
257
- return cls(proto_image)
258
-
259
- def to_pil(self) -> PILImage.Image:
260
- if not self.proto.base64:
261
- raise ValueError("Image has no bytes")
262
- return PILImage.open(io.BytesIO(self.proto.base64))
263
-
264
- def to_numpy(self) -> np.ndarray:
265
- return np.asarray(self.to_pil())
266
-
267
- def to_proto(self) -> ImageProto:
268
- return self.proto
269
-
270
- @classmethod
271
- def from_proto(cls, proto: ImageProto) -> "Image":
272
- return cls(proto)
273
-
274
- @classmethod
275
- def from_value(cls, value):
276
- if isinstance(value, PILImage.Image):
277
- return cls.from_pil(value)
278
- if isinstance(value, Image):
279
- return value
280
- raise TypeError(f'Incompatible type for Image: {type(value)}')
281
-
282
- def cast(self, python_type):
283
- if python_type == Image:
284
- return self
285
- if python_type in (PILImage.Image, PILImage):
286
- return self.to_pil()
287
- if python_type == np.ndarray or get_origin(python_type) == np.ndarray:
288
- return self.to_numpy()
289
- raise TypeError(f'Incompatible type for Image: {python_type}')
290
-
291
-
292
- class Audio(MessageData):
293
-
294
- def __init__(self, proto_audio: AudioProto):
295
- self.proto = proto_audio
296
-
297
- @property
298
- def url(self) -> str:
299
- return self.proto.url
300
-
301
- @url.setter
302
- def url(self, value: str):
303
- self.proto.url = value
304
-
305
- @property
306
- def bytes(self) -> bytes:
307
- return self.proto.base64
308
-
309
- @bytes.setter
310
- def bytes(self, value: bytes):
311
- self.proto.base64 = value
312
-
313
- @classmethod
314
- def from_url(cls, url: str) -> "Audio":
315
- proto_audio = AudioProto(url=url)
316
- return cls(proto_audio)
317
-
318
- def __repr__(self) -> str:
319
- attrs = []
320
- if self.url:
321
- attrs.append(f"url={self.url!r}")
322
- if self.bytes:
323
- attrs.append(f"bytes=<{len(self.bytes)} bytes>")
324
- return f"Audio({', '.join(attrs)})"
325
-
326
- def to_proto(self) -> AudioProto:
327
- return self.proto
328
-
329
- @classmethod
330
- def from_proto(cls, proto: AudioProto) -> "Audio":
331
- return cls(proto)
332
-
333
-
334
- class Frame(MessageData):
335
-
336
- def __init__(self, proto_frame: FrameProto):
337
- self.proto = proto_frame
338
-
339
- @property
340
- def time(self) -> float:
341
- # TODO: time is a uint32, so this will overflow at 49.7 days
342
- # we should be using double or uint64 in the proto instead
343
- return self.proto.frame_info.time / 1000.0
344
-
345
- @time.setter
346
- def time(self, value: float):
347
- self.proto.frame_info.time = int(value * 1000)
348
-
349
- @property
350
- def image(self) -> Image:
351
- return Image.from_proto(self.proto.data.image)
352
-
353
- @image.setter
354
- def image(self, value: Image):
355
- self.proto.data.image.CopyFrom(value.to_proto())
356
-
357
- @property
358
- def regions(self) -> List[Region]:
359
- return [Region(region) for region in self.proto.data.regions]
360
-
361
- @regions.setter
362
- def regions(self, value: List[Region]):
363
- self.proto.data.regions.extend([region.proto for region in value])
364
-
365
- def to_proto(self) -> FrameProto:
366
- return self.proto
367
-
368
- @classmethod
369
- def from_proto(cls, proto: FrameProto) -> "Frame":
370
- return cls(proto)
371
-
372
-
373
- class Video(MessageData):
374
-
375
- def __init__(self, proto_video: VideoProto):
376
- self.proto = proto_video
377
-
378
- @property
379
- def url(self) -> str:
380
- return self.proto.url
381
-
382
- @url.setter
383
- def url(self, value: str):
384
- self.proto.url = value
385
-
386
- @property
387
- def bytes(self) -> bytes:
388
- return self.proto.base64
389
-
390
- @bytes.setter
391
- def bytes(self, value: bytes):
392
- self.proto.base64 = value
393
-
394
- @classmethod
395
- def from_url(cls, url: str) -> "Video":
396
- proto_video = VideoProto(url=url)
397
- return cls(proto_video)
398
-
399
- def __repr__(self) -> str:
400
- attrs = []
401
- if self.url:
402
- attrs.append(f"url={self.url!r}")
403
- if self.bytes:
404
- attrs.append(f"bytes=<{len(self.bytes)} bytes>")
405
- return f"Video({', '.join(attrs)})"
406
-
407
- def to_proto(self) -> VideoProto:
408
- return self.proto
409
-
410
- @classmethod
411
- def from_proto(cls, proto: VideoProto) -> "Video":
412
- return cls(proto)
413
-
414
-
415
- def cast(value, python_type):
416
- list_type = (get_origin(python_type) == list)
417
- if isinstance(value, MessageData):
418
- return value.cast(python_type)
419
- if list_type and isinstance(value, np.ndarray):
420
- return value.tolist()
421
- if list_type and isinstance(value, list):
422
- if get_args(python_type):
423
- inner_type = get_args(python_type)[0]
424
- return [cast(item, inner_type) for item in value]
425
- if not isinstance(value, Iterable):
426
- raise TypeError(f'Expected list, got {type(value)}')
427
- return value
File without changes