clarifai 11.1.7__py3-none-any.whl → 11.1.7rc1__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 (121) hide show
  1. clarifai/__init__.py +1 -1
  2. clarifai/__pycache__/__init__.cpython-310.pyc +0 -0
  3. clarifai/__pycache__/errors.cpython-310.pyc +0 -0
  4. clarifai/__pycache__/versions.cpython-310.pyc +0 -0
  5. clarifai/cli/__main__.py~ +4 -0
  6. clarifai/cli/__pycache__/__init__.cpython-310.pyc +0 -0
  7. clarifai/cli/__pycache__/__main__.cpython-310.pyc +0 -0
  8. clarifai/cli/__pycache__/base.cpython-310.pyc +0 -0
  9. clarifai/cli/__pycache__/compute_cluster.cpython-310.pyc +0 -0
  10. clarifai/cli/__pycache__/deployment.cpython-310.pyc +0 -0
  11. clarifai/cli/__pycache__/model.cpython-310.pyc +0 -0
  12. clarifai/cli/__pycache__/nodepool.cpython-310.pyc +0 -0
  13. clarifai/cli/model.py +25 -0
  14. clarifai/client/#model_client.py# +430 -0
  15. clarifai/client/__pycache__/__init__.cpython-310.pyc +0 -0
  16. clarifai/client/__pycache__/app.cpython-310.pyc +0 -0
  17. clarifai/client/__pycache__/base.cpython-310.pyc +0 -0
  18. clarifai/client/__pycache__/dataset.cpython-310.pyc +0 -0
  19. clarifai/client/__pycache__/input.cpython-310.pyc +0 -0
  20. clarifai/client/__pycache__/lister.cpython-310.pyc +0 -0
  21. clarifai/client/__pycache__/model.cpython-310.pyc +0 -0
  22. clarifai/client/__pycache__/module.cpython-310.pyc +0 -0
  23. clarifai/client/__pycache__/runner.cpython-310.pyc +0 -0
  24. clarifai/client/__pycache__/search.cpython-310.pyc +0 -0
  25. clarifai/client/__pycache__/user.cpython-310.pyc +0 -0
  26. clarifai/client/__pycache__/workflow.cpython-310.pyc +0 -0
  27. clarifai/client/auth/__pycache__/__init__.cpython-310.pyc +0 -0
  28. clarifai/client/auth/__pycache__/helper.cpython-310.pyc +0 -0
  29. clarifai/client/auth/__pycache__/register.cpython-310.pyc +0 -0
  30. clarifai/client/auth/__pycache__/stub.cpython-310.pyc +0 -0
  31. clarifai/client/model.py +158 -393
  32. clarifai/client/model_client.py +449 -0
  33. clarifai/constants/__pycache__/dataset.cpython-310.pyc +0 -0
  34. clarifai/constants/__pycache__/model.cpython-310.pyc +0 -0
  35. clarifai/constants/__pycache__/search.cpython-310.pyc +0 -0
  36. clarifai/datasets/__pycache__/__init__.cpython-310.pyc +0 -0
  37. clarifai/datasets/export/__pycache__/__init__.cpython-310.pyc +0 -0
  38. clarifai/datasets/export/__pycache__/inputs_annotations.cpython-310.pyc +0 -0
  39. clarifai/datasets/upload/__pycache__/__init__.cpython-310.pyc +0 -0
  40. clarifai/datasets/upload/__pycache__/base.cpython-310.pyc +0 -0
  41. clarifai/datasets/upload/__pycache__/features.cpython-310.pyc +0 -0
  42. clarifai/datasets/upload/__pycache__/image.cpython-310.pyc +0 -0
  43. clarifai/datasets/upload/__pycache__/text.cpython-310.pyc +0 -0
  44. clarifai/datasets/upload/__pycache__/utils.cpython-310.pyc +0 -0
  45. clarifai/datasets/upload/loaders/__pycache__/__init__.cpython-310.pyc +0 -0
  46. clarifai/datasets/upload/loaders/__pycache__/coco_detection.cpython-310.pyc +0 -0
  47. clarifai/models/__pycache__/__init__.cpython-310.pyc +0 -0
  48. clarifai/models/model_serving/__pycache__/__init__.cpython-310.pyc +0 -0
  49. clarifai/models/model_serving/__pycache__/constants.cpython-310.pyc +0 -0
  50. clarifai/models/model_serving/cli/__pycache__/__init__.cpython-310.pyc +0 -0
  51. clarifai/models/model_serving/cli/__pycache__/_utils.cpython-310.pyc +0 -0
  52. clarifai/models/model_serving/cli/__pycache__/base.cpython-310.pyc +0 -0
  53. clarifai/models/model_serving/cli/__pycache__/build.cpython-310.pyc +0 -0
  54. clarifai/models/model_serving/cli/__pycache__/create.cpython-310.pyc +0 -0
  55. clarifai/models/model_serving/model_config/__pycache__/__init__.cpython-310.pyc +0 -0
  56. clarifai/models/model_serving/model_config/__pycache__/base.cpython-310.pyc +0 -0
  57. clarifai/models/model_serving/model_config/__pycache__/config.cpython-310.pyc +0 -0
  58. clarifai/models/model_serving/model_config/__pycache__/inference_parameter.cpython-310.pyc +0 -0
  59. clarifai/models/model_serving/model_config/__pycache__/output.cpython-310.pyc +0 -0
  60. clarifai/models/model_serving/model_config/triton/__pycache__/__init__.cpython-310.pyc +0 -0
  61. clarifai/models/model_serving/model_config/triton/__pycache__/serializer.cpython-310.pyc +0 -0
  62. clarifai/models/model_serving/model_config/triton/__pycache__/triton_config.cpython-310.pyc +0 -0
  63. clarifai/models/model_serving/model_config/triton/__pycache__/wrappers.cpython-310.pyc +0 -0
  64. clarifai/models/model_serving/repo_build/__pycache__/__init__.cpython-310.pyc +0 -0
  65. clarifai/models/model_serving/repo_build/__pycache__/build.cpython-310.pyc +0 -0
  66. clarifai/models/model_serving/repo_build/static_files/__pycache__/base_test.cpython-310-pytest-7.2.0.pyc +0 -0
  67. clarifai/rag/__pycache__/__init__.cpython-310.pyc +0 -0
  68. clarifai/rag/__pycache__/rag.cpython-310.pyc +0 -0
  69. clarifai/rag/__pycache__/utils.cpython-310.pyc +0 -0
  70. clarifai/runners/__init__.py +2 -7
  71. clarifai/runners/__pycache__/__init__.cpython-310.pyc +0 -0
  72. clarifai/runners/__pycache__/server.cpython-310.pyc +0 -0
  73. clarifai/runners/dockerfile_template/Dockerfile.debug +11 -0
  74. clarifai/runners/dockerfile_template/Dockerfile.debug~ +9 -0
  75. clarifai/runners/dockerfile_template/Dockerfile.template +3 -0
  76. clarifai/runners/models/__pycache__/__init__.cpython-310.pyc +0 -0
  77. clarifai/runners/models/__pycache__/base_typed_model.cpython-310.pyc +0 -0
  78. clarifai/runners/models/__pycache__/model_builder.cpython-310.pyc +0 -0
  79. clarifai/runners/models/__pycache__/model_class.cpython-310.pyc +0 -0
  80. clarifai/runners/models/__pycache__/model_run_locally.cpython-310.pyc +0 -0
  81. clarifai/runners/models/__pycache__/model_runner.cpython-310.pyc +0 -0
  82. clarifai/runners/models/__pycache__/model_servicer.cpython-310.pyc +0 -0
  83. clarifai/runners/models/__pycache__/model_upload.cpython-310.pyc +0 -0
  84. clarifai/runners/models/model_builder.py +24 -7
  85. clarifai/runners/models/model_class.py +256 -28
  86. clarifai/runners/models/model_run_locally.py +3 -78
  87. clarifai/runners/models/model_runner.py +2 -0
  88. clarifai/runners/models/model_servicer.py +11 -2
  89. clarifai/runners/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  90. clarifai/runners/utils/__pycache__/const.cpython-310.pyc +0 -0
  91. clarifai/runners/utils/__pycache__/data_handler.cpython-310.pyc +0 -0
  92. clarifai/runners/utils/__pycache__/data_types.cpython-310.pyc +0 -0
  93. clarifai/runners/utils/__pycache__/data_utils.cpython-310.pyc +0 -0
  94. clarifai/runners/utils/__pycache__/loader.cpython-310.pyc +0 -0
  95. clarifai/runners/utils/__pycache__/logging.cpython-310.pyc +0 -0
  96. clarifai/runners/utils/__pycache__/method_signatures.cpython-310.pyc +0 -0
  97. clarifai/runners/utils/__pycache__/serializers.cpython-310.pyc +0 -0
  98. clarifai/runners/utils/__pycache__/url_fetcher.cpython-310.pyc +0 -0
  99. clarifai/runners/utils/data_types.py +427 -0
  100. clarifai/runners/utils/method_signatures.py +500 -0
  101. clarifai/runners/utils/serializers.py +222 -0
  102. clarifai/schema/__pycache__/search.cpython-310.pyc +0 -0
  103. clarifai/urls/__pycache__/helper.cpython-310.pyc +0 -0
  104. clarifai/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  105. clarifai/utils/__pycache__/logging.cpython-310.pyc +0 -0
  106. clarifai/utils/__pycache__/misc.cpython-310.pyc +0 -0
  107. clarifai/utils/__pycache__/model_train.cpython-310.pyc +0 -0
  108. clarifai/utils/evaluation/__pycache__/__init__.cpython-310.pyc +0 -0
  109. clarifai/utils/evaluation/__pycache__/helpers.cpython-310.pyc +0 -0
  110. clarifai/utils/evaluation/__pycache__/main.cpython-310.pyc +0 -0
  111. clarifai/workflows/__pycache__/__init__.cpython-310.pyc +0 -0
  112. clarifai/workflows/__pycache__/export.cpython-310.pyc +0 -0
  113. clarifai/workflows/__pycache__/utils.cpython-310.pyc +0 -0
  114. clarifai/workflows/__pycache__/validate.cpython-310.pyc +0 -0
  115. {clarifai-11.1.7.dist-info → clarifai-11.1.7rc1.dist-info}/METADATA +16 -26
  116. clarifai-11.1.7rc1.dist-info/RECORD +205 -0
  117. {clarifai-11.1.7.dist-info → clarifai-11.1.7rc1.dist-info}/WHEEL +1 -1
  118. clarifai-11.1.7.dist-info/RECORD +0 -101
  119. {clarifai-11.1.7.dist-info → clarifai-11.1.7rc1.dist-info}/LICENSE +0 -0
  120. {clarifai-11.1.7.dist-info → clarifai-11.1.7rc1.dist-info}/entry_points.txt +0 -0
  121. {clarifai-11.1.7.dist-info → clarifai-11.1.7rc1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,449 @@
1
+ import inspect
2
+ import json
3
+ import time
4
+ from typing import Any, Dict, Iterator, List
5
+
6
+ from clarifai_grpc.grpc.api import resources_pb2, service_pb2
7
+ from clarifai_grpc.grpc.api.status import status_code_pb2
8
+
9
+ from clarifai.constants.model import MAX_MODEL_PREDICT_INPUTS
10
+ from clarifai.errors import UserError
11
+ from clarifai.runners.utils.method_signatures import (CompatibilitySerializer, deserialize,
12
+ get_stream_from_signature, serialize,
13
+ signatures_from_json)
14
+ from clarifai.utils.logging import logger
15
+ from clarifai.utils.misc import BackoffIterator, status_is_retryable
16
+
17
+
18
+ class ModelClient:
19
+ '''
20
+ Client for calling model predict, generate, and stream methods.
21
+ '''
22
+
23
+ def __init__(self, stub, request_template: service_pb2.PostModelOutputsRequest = None):
24
+ '''
25
+ Initialize the model client.
26
+
27
+ Args:
28
+ stub: The gRPC stub for the model.
29
+ request_template: The template for the request to send to the model, including
30
+ common fields like model_id, model_version, cluster, etc.
31
+ '''
32
+ self.STUB = stub
33
+ self.request_template = request_template or service_pb2.PostModelOutputsRequest()
34
+ self._method_signatures = None
35
+ self._defined = False
36
+
37
+ def fetch(self):
38
+ '''
39
+ Fetch function signature definitions from the model and define the functions in the client
40
+ '''
41
+ if self._defined:
42
+ return
43
+ try:
44
+ self._fetch_signatures()
45
+ self._define_functions()
46
+ finally:
47
+ self._defined = True
48
+
49
+ def __getattr__(self, name):
50
+ if not self._defined:
51
+ self.fetch()
52
+ return self.__getattribute__(name)
53
+
54
+ def _fetch_signatures(self):
55
+ '''
56
+ Fetch the method signatures from the model.
57
+
58
+ Returns:
59
+ Dict: The method signatures.
60
+ '''
61
+ #request = resources_pb2.GetModelSignaturesRequest()
62
+ #response = self.stub.GetModelSignatures(request)
63
+ #self._method_signatures = json.loads(response.signatures) # or define protos
64
+ # TODO this could use a new endpoint to get the signatures
65
+ # for local grpc models, we'll also have to add the endpoint to the model servicer
66
+ # for now we'll just use the predict endpoint with a special method name
67
+
68
+ request = service_pb2.PostModelOutputsRequest()
69
+ request.CopyFrom(self.request_template)
70
+ # request.model.model_version.output_info.params['_method_name'] = '_GET_SIGNATURES'
71
+ inp = request.inputs.add() # empty input for this method
72
+ inp.data.parts.add() # empty part for this input
73
+ inp.data.metadata['_method_name'] = '_GET_SIGNATURES'
74
+ start_time = time.time()
75
+ backoff_iterator = BackoffIterator(10)
76
+ while True:
77
+ response = self.STUB.PostModelOutputs(request)
78
+ if status_is_retryable(
79
+ response.status.code) and time.time() - start_time < 60 * 10: # 10 minutes
80
+ logger.info(f"Retrying model info fetch with response {response.status!r}")
81
+ time.sleep(next(backoff_iterator))
82
+ continue
83
+ break
84
+ if (response.status.code == status_code_pb2.INPUT_UNSUPPORTED_FORMAT or
85
+ (response.status.code == status_code_pb2.SUCCESS and
86
+ response.outputs[0].data.text.raw == '')):
87
+ # return codes/values from older models that don't support _GET_SIGNATURES
88
+ self._method_signatures = {}
89
+ self._define_compatability_functions()
90
+ return
91
+ if response.status.code != status_code_pb2.SUCCESS:
92
+ raise Exception(f"Model failed with response {response!r}")
93
+ self._method_signatures = signatures_from_json(response.outputs[0].data.text.raw)
94
+
95
+ def _define_functions(self):
96
+ '''
97
+ Define the functions based on the method signatures.
98
+ '''
99
+ for method_name, method_signature in self._method_signatures.items():
100
+ # define the function in this client instance
101
+ if method_signature.method_type == 'predict':
102
+ call_func = self._predict
103
+ elif method_signature.method_type == 'generate':
104
+ call_func = self._generate
105
+ elif method_signature.method_type == 'stream':
106
+ call_func = self._stream
107
+ else:
108
+ raise ValueError(f"Unknown method type {method_signature.method_type}")
109
+
110
+ # method argnames, in order, collapsing nested keys to corresponding user function args
111
+ method_argnames = []
112
+ for var in method_signature.inputs:
113
+ outer = var.name.split('.', 1)[0]
114
+ if outer in method_argnames:
115
+ continue
116
+ method_argnames.append(outer)
117
+
118
+ def bind_f(method_name, method_argnames, call_func):
119
+
120
+ def f(*args, **kwargs):
121
+ if len(args) > len(method_argnames):
122
+ raise TypeError(
123
+ f"{method_name}() takes {len(method_argnames)} positional arguments but {len(args)} were given"
124
+ )
125
+ for name, arg in zip(method_argnames, args): # handle positional with zip shortest
126
+ if name in kwargs:
127
+ raise TypeError(f"Multiple values for argument {name}")
128
+ kwargs[name] = arg
129
+ return call_func(kwargs, method_name)
130
+
131
+ return f
132
+
133
+ # need to bind method_name to the value, not the mutating loop variable
134
+ f = bind_f(method_name, method_argnames, call_func)
135
+
136
+ # set names, annotations and docstrings
137
+ f.__name__ = method_name
138
+ f.__qualname__ = f'{self.__class__.__name__}.{method_name}'
139
+ f.__doc__ = method_signature.docstring
140
+ input_annotations = json.loads(method_signature.annotations_json)
141
+ return_annotation = input_annotations.pop('return', None)
142
+ sig = inspect.signature(f).replace(
143
+ parameters=[
144
+ inspect.Parameter(k, inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=v)
145
+ for k, v in input_annotations.items()
146
+ ],
147
+ return_annotation=return_annotation,
148
+ )
149
+ f.__signature__ = sig
150
+ f.__doc__ = method_signature.docstring
151
+ setattr(self, method_name, f)
152
+
153
+ def _define_compatability_functions(self):
154
+
155
+ serializer = CompatibilitySerializer()
156
+
157
+ def predict(input: Any) -> Any:
158
+ proto = resources_pb2.Input()
159
+ serializer.serialize(proto.data, input)
160
+ # always use text.raw for compat
161
+ if proto.data.string_value:
162
+ proto.data.text.raw = proto.data.string_value
163
+ proto.data.string_value = ''
164
+ response = self._predict_by_proto([proto])
165
+ if response.status.code != status_code_pb2.SUCCESS:
166
+ raise Exception(f"Model predict failed with response {response!r}")
167
+ response_data = response.outputs[0].data
168
+ if response_data.text.raw:
169
+ response_data.string_value = response_data.text.raw
170
+ response_data.text.raw = ''
171
+ return serializer.deserialize(response_data)
172
+
173
+ self.predict = predict
174
+
175
+ def _predict(
176
+ self,
177
+ inputs, # TODO set up functions according to fetched signatures?
178
+ method_name: str = 'predict',
179
+ ) -> Any:
180
+ input_signature = self._method_signatures[method_name].inputs
181
+ output_signature = self._method_signatures[method_name].outputs
182
+
183
+ batch_input = True
184
+ if isinstance(inputs, dict):
185
+ inputs = [inputs]
186
+ batch_input = False
187
+
188
+ proto_inputs = []
189
+ for input in inputs:
190
+ proto = resources_pb2.Input()
191
+ serialize(input, input_signature, proto.data)
192
+ proto_inputs.append(proto)
193
+
194
+ response = self._predict_by_proto(proto_inputs, method_name)
195
+ #print(response)
196
+
197
+ outputs = []
198
+ for output in response.outputs:
199
+ outputs.append(deserialize(output.data, output_signature, is_output=True))
200
+ if batch_input:
201
+ return outputs
202
+ return outputs[0]
203
+
204
+ def _predict_by_proto(
205
+ self,
206
+ inputs: List[resources_pb2.Input],
207
+ method_name: str = None,
208
+ inference_params: Dict = None,
209
+ output_config: Dict = None,
210
+ ) -> service_pb2.MultiOutputResponse:
211
+ """Predicts the model based on the given inputs.
212
+
213
+ Args:
214
+ inputs (List[resources_pb2.Input]): The inputs to predict.
215
+ method_name (str): The remote method name to call.
216
+ inference_params (Dict): Inference parameters to override.
217
+ output_config (Dict): Output configuration to override.
218
+
219
+ Returns:
220
+ service_pb2.MultiOutputResponse: The prediction response(s).
221
+ """
222
+ if not isinstance(inputs, list):
223
+ raise UserError('Invalid inputs, inputs must be a list of Input objects.')
224
+ if len(inputs) > MAX_MODEL_PREDICT_INPUTS:
225
+ raise UserError(f"Too many inputs. Max is {MAX_MODEL_PREDICT_INPUTS}.")
226
+
227
+ request = service_pb2.PostModelOutputsRequest()
228
+ request.CopyFrom(self.request_template)
229
+
230
+ request.inputs.extend(inputs)
231
+
232
+ if method_name:
233
+ # TODO put in new proto field?
234
+ for inp in request.inputs:
235
+ inp.data.metadata['_method_name'] = method_name
236
+ if inference_params:
237
+ request.model.model_version.output_info.params.update(inference_params)
238
+ if output_config:
239
+ request.model.model_version.output_info.output_config.MergeFrom(
240
+ resources_pb2.OutputConfig(**output_config))
241
+
242
+ start_time = time.time()
243
+ backoff_iterator = BackoffIterator(10)
244
+ while True:
245
+ response = self.STUB.PostModelOutputs(request)
246
+ if status_is_retryable(
247
+ response.status.code) and time.time() - start_time < 60 * 10: # 10 minutes
248
+ logger.info(f"Model predict failed with response {response!r}")
249
+ time.sleep(next(backoff_iterator))
250
+ continue
251
+
252
+ if response.status.code != status_code_pb2.SUCCESS:
253
+ raise Exception(f"Model predict failed with response {response!r}")
254
+ break
255
+
256
+ return response
257
+
258
+ def _generate(
259
+ self,
260
+ inputs, # TODO set up functions according to fetched signatures?
261
+ method_name: str = 'generate',
262
+ ) -> Any:
263
+ input_signature = self._method_signatures[method_name].inputs
264
+ output_signature = self._method_signatures[method_name].outputs
265
+
266
+ batch_input = True
267
+ if isinstance(inputs, dict):
268
+ inputs = [inputs]
269
+ batch_input = False
270
+
271
+ proto_inputs = []
272
+ for input in inputs:
273
+ proto = resources_pb2.Input()
274
+ serialize(input, input_signature, proto.data)
275
+ proto_inputs.append(proto)
276
+
277
+ response_stream = self._generate_by_proto(proto_inputs, method_name)
278
+ #print(response)
279
+
280
+ for response in response_stream:
281
+ outputs = []
282
+ for output in response.outputs:
283
+ outputs.append(deserialize(output.data, output_signature, is_output=True))
284
+ if batch_input:
285
+ yield outputs
286
+ yield outputs[0]
287
+
288
+ def _generate_by_proto(
289
+ self,
290
+ inputs: List[resources_pb2.Input],
291
+ method_name: str = None,
292
+ inference_params: Dict = {},
293
+ output_config: Dict = {},
294
+ ):
295
+ """Generate the stream output on model based on the given inputs.
296
+
297
+ Args:
298
+ inputs (list[Input]): The inputs to generate, must be less than 128.
299
+ method_name (str): The remote method name to call.
300
+ inference_params (dict): The inference params to override.
301
+ output_config (dict): The output config to override.
302
+ """
303
+ if not isinstance(inputs, list):
304
+ raise UserError('Invalid inputs, inputs must be a list of Input objects.')
305
+ if len(inputs) > MAX_MODEL_PREDICT_INPUTS:
306
+ raise UserError(f"Too many inputs. Max is {MAX_MODEL_PREDICT_INPUTS}."
307
+ ) # TODO Use Chunker for inputs len > 128
308
+
309
+ request = service_pb2.PostModelOutputsRequest()
310
+ request.CopyFrom(self.request_template)
311
+
312
+ request.inputs.extend(inputs)
313
+
314
+ if method_name:
315
+ # TODO put in new proto field?
316
+ for inp in request.inputs:
317
+ inp.data.metadata['_method_name'] = method_name
318
+ if inference_params:
319
+ request.model.model_version.output_info.params.update(inference_params)
320
+ if output_config:
321
+ request.model.model_version.output_info.output_config.MergeFromDict(output_config)
322
+
323
+ start_time = time.time()
324
+ backoff_iterator = BackoffIterator(10)
325
+ started = False
326
+ while not started:
327
+ stream_response = self.STUB.GenerateModelOutputs(request)
328
+ try:
329
+ response = next(stream_response) # get the first response
330
+ except StopIteration:
331
+ raise Exception("Model Generate failed with no response")
332
+ if status_is_retryable(response.status.code) and \
333
+ time.time() - start_time < 60 * 10:
334
+ logger.info("Model is still deploying, please wait...")
335
+ time.sleep(next(backoff_iterator))
336
+ continue
337
+ if response.status.code != status_code_pb2.SUCCESS:
338
+ raise Exception(f"Model Generate failed with response {response.status!r}")
339
+ started = True
340
+
341
+ yield response # yield the first response
342
+
343
+ for response in stream_response:
344
+ if response.status.code != status_code_pb2.SUCCESS:
345
+ raise Exception(f"Model Generate failed with response {response.status!r}")
346
+ yield response
347
+
348
+ def _stream(
349
+ self,
350
+ inputs,
351
+ method_name: str = 'stream',
352
+ ) -> Any:
353
+ input_signature = self._method_signatures[method_name].inputs
354
+ output_signature = self._method_signatures[method_name].outputs
355
+
356
+ if isinstance(inputs, list):
357
+ assert len(inputs) == 1, 'streaming methods do not support batched calls'
358
+ inputs = inputs[0]
359
+ assert isinstance(inputs, dict)
360
+ kwargs = inputs
361
+
362
+ # find the streaming vars in the input signature, and the streaming input python param
363
+ stream_sig = get_stream_from_signature(input_signature)
364
+ if stream_sig is None:
365
+ raise ValueError("Streaming method must have a Stream input")
366
+ stream_argname = stream_sig.name
367
+
368
+ # get the streaming input generator from the user-provided function arg values
369
+ user_inputs_generator = kwargs.pop(stream_argname)
370
+
371
+ def _input_proto_stream():
372
+ # first item contains all the inputs and the first stream item
373
+ proto = resources_pb2.Input()
374
+ try:
375
+ item = next(user_inputs_generator)
376
+ except StopIteration:
377
+ return # no items to stream
378
+ kwargs[stream_argname] = item
379
+ serialize(kwargs, input_signature, proto.data)
380
+
381
+ yield proto
382
+
383
+ # subsequent items are just the stream items
384
+ for item in user_inputs_generator:
385
+ proto = resources_pb2.Input()
386
+ serialize({stream_argname: item}, [stream_sig], proto.data)
387
+ yield proto
388
+
389
+ response_stream = self._stream_by_proto(_input_proto_stream(), method_name)
390
+ #print(response)
391
+
392
+ for response in response_stream:
393
+ assert len(response.outputs) == 1, 'streaming methods must have exactly one output'
394
+ yield deserialize(response.outputs[0].data, output_signature, is_output=True)
395
+
396
+ def _req_iterator(self,
397
+ input_iterator: Iterator[List[resources_pb2.Input]],
398
+ method_name: str = None,
399
+ inference_params: Dict = {},
400
+ output_config: Dict = {}):
401
+ request = service_pb2.PostModelOutputsRequest()
402
+ request.CopyFrom(self.request_template)
403
+ if inference_params:
404
+ request.model.model_version.output_info.params.update(inference_params)
405
+ if output_config:
406
+ request.model.model_version.output_info.output_config.MergeFromDict(output_config)
407
+ for inputs in input_iterator:
408
+ req = service_pb2.PostModelOutputsRequest()
409
+ req.CopyFrom(request)
410
+ if isinstance(inputs, list):
411
+ req.inputs.extend(inputs)
412
+ else:
413
+ req.inputs.append(inputs)
414
+ # TODO: put into new proto field?
415
+ for inp in req.inputs:
416
+ inp.data.metadata['_method_name'] = method_name
417
+ yield req
418
+
419
+ def _stream_by_proto(self,
420
+ inputs: Iterator[List[resources_pb2.Input]],
421
+ method_name: str = None,
422
+ inference_params: Dict = {},
423
+ output_config: Dict = {}):
424
+ """Generate the stream output on model based on the given stream of inputs.
425
+ """
426
+ # if not isinstance(inputs, Iterator[List[Input]]):
427
+ # raise UserError('Invalid inputs, inputs must be a iterator of list of Input objects.')
428
+
429
+ request = self._req_iterator(inputs, method_name, inference_params, output_config)
430
+
431
+ start_time = time.time()
432
+ backoff_iterator = BackoffIterator(10)
433
+ generation_started = False
434
+ while True:
435
+ if generation_started:
436
+ break
437
+ stream_response = self.STUB.StreamModelOutputs(request)
438
+ for response in stream_response:
439
+ if status_is_retryable(response.status.code) and \
440
+ time.time() - start_time < 60 * 10:
441
+ logger.info("Model is still deploying, please wait...")
442
+ time.sleep(next(backoff_iterator))
443
+ break
444
+ if response.status.code != status_code_pb2.SUCCESS:
445
+ raise Exception(f"Model Predict failed with response {response.status!r}")
446
+ else:
447
+ if not generation_started:
448
+ generation_started = True
449
+ yield response
@@ -1,14 +1,9 @@
1
- from .models.base_typed_model import AnyAnyModel, TextInputModel, VisualInputModel
2
1
  from .models.model_builder import ModelBuilder
2
+ from .models.model_class import ModelClass
3
3
  from .models.model_runner import ModelRunner
4
- from .utils.data_handler import InputDataHandler, OutputDataHandler
5
4
 
6
5
  __all__ = [
7
6
  "ModelRunner",
8
7
  "ModelBuilder",
9
- "InputDataHandler",
10
- "OutputDataHandler",
11
- "AnyAnyModel",
12
- "TextInputModel",
13
- "VisualInputModel",
8
+ "ModelClass",
14
9
  ]
@@ -0,0 +1,11 @@
1
+ FROM --platform=$TARGETPLATFORM public.ecr.aws/docker/library/python:3.12-slim-bookworm as pybase
2
+
3
+ #############################
4
+ # Final runtime image
5
+ #############################
6
+ FROM --platform=$TARGETPLATFORM ${RUNTIME_IMAGE} as final
7
+
8
+ COPY --from=pybase --link=true /usr/bin/ls /usr/bin/cat /usr/bin/which /usr/bin/bash /usr/bin/sort /usr/bin/du /usr/bin/
9
+ COPY --from=pybase --link=true /bin/rbash /bin/sh /bin/rm /bin/
10
+ COPY --from=pybase --link=true /lib/*-linux-gnu/libselinux.so.1 /lib/*-linux-gnu/libpcre2-8.so.0 /lib/x86_64-linux-gnu/
11
+ COPY --from=pybase --link=true /lib/*-linux-gnu/libselinux.so.1 /lib/*-linux-gnu/libpcre2-8.so.0 /lib/aarch64-linux-gnu/
@@ -0,0 +1,9 @@
1
+ FROM --platform=$TARGETPLATFORM public.ecr.aws/docker/library/python:3.12-slim-bookworm as pybase
2
+
3
+ #############################
4
+ # Final runtime image
5
+ #############################
6
+ FROM --platform=$TARGETPLATFORM ${RUNTIME_IMAGE} as final
7
+
8
+ COPY --from=pybase --link=true /usr/bin/ls /usr/bin/cat /usr/bin/which /usr/bin/bash /usr/bin/sort /usr/bin/du /usr/bin/
9
+ COPY --from=pybase --link=true /bin/rbash /bin/sh /bin/rm /bin/
@@ -44,6 +44,9 @@ ENV PYTHONPATH=${PYTHONPATH}:/home/nonroot/main \
44
44
  CLARIFAI_COMPUTE_CLUSTER_ID=${CLARIFAI_COMPUTE_CLUSTER_ID} \
45
45
  CLARIFAI_API_BASE=${CLARIFAI_API_BASE:-https://api.clarifai.com}
46
46
 
47
+ # # Write out the model function signatures
48
+ # RUN ["python", "-m", "clarifai.cli", "model", "signatures", "--model_path", "/home/nonroot/main", "--out_path", "/home/nonroot/main/signatures.yaml"]
49
+
47
50
  # Finally run the clarifai entrypoint to start the runner loop and local dev server.
48
51
  # Note(zeiler): we may want to make this a clarifai CLI call.
49
52
  ENTRYPOINT ["python", "-m", "clarifai.runners.server"]