clarifai 11.1.6rc1__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 (31) hide show
  1. clarifai/__init__.py +1 -1
  2. clarifai/cli/__pycache__/model.cpython-310.pyc +0 -0
  3. clarifai/cli/model.py +25 -0
  4. clarifai/client/model.py +158 -393
  5. clarifai/client/model_client.py +4 -2
  6. clarifai/runners/__init__.py +2 -7
  7. clarifai/runners/__pycache__/__init__.cpython-310.pyc +0 -0
  8. clarifai/runners/__pycache__/server.cpython-310.pyc +0 -0
  9. clarifai/runners/dockerfile_template/Dockerfile.template +3 -0
  10. clarifai/runners/models/__pycache__/model_builder.cpython-310.pyc +0 -0
  11. clarifai/runners/models/__pycache__/model_class.cpython-310.pyc +0 -0
  12. clarifai/runners/models/__pycache__/model_run_locally.cpython-310.pyc +0 -0
  13. clarifai/runners/models/__pycache__/model_runner.cpython-310.pyc +0 -0
  14. clarifai/runners/models/__pycache__/model_servicer.cpython-310.pyc +0 -0
  15. clarifai/runners/models/model_builder.py +24 -7
  16. clarifai/runners/models/model_class.py +256 -28
  17. clarifai/runners/models/model_run_locally.py +3 -78
  18. clarifai/runners/models/model_runner.py +2 -0
  19. clarifai/runners/models/model_servicer.py +11 -2
  20. clarifai/runners/utils/__pycache__/data_types.cpython-310.pyc +0 -0
  21. clarifai/runners/utils/__pycache__/method_signatures.cpython-310.pyc +0 -0
  22. clarifai/runners/utils/__pycache__/serializers.cpython-310.pyc +0 -0
  23. clarifai/runners/utils/data_types.py +46 -5
  24. clarifai/runners/utils/method_signatures.py +104 -39
  25. clarifai/runners/utils/serializers.py +19 -5
  26. {clarifai-11.1.6rc1.dist-info → clarifai-11.1.7rc1.dist-info}/METADATA +2 -1
  27. {clarifai-11.1.6rc1.dist-info → clarifai-11.1.7rc1.dist-info}/RECORD +31 -31
  28. {clarifai-11.1.6rc1.dist-info → clarifai-11.1.7rc1.dist-info}/LICENSE +0 -0
  29. {clarifai-11.1.6rc1.dist-info → clarifai-11.1.7rc1.dist-info}/WHEEL +0 -0
  30. {clarifai-11.1.6rc1.dist-info → clarifai-11.1.7rc1.dist-info}/entry_points.txt +0 -0
  31. {clarifai-11.1.6rc1.dist-info → clarifai-11.1.7rc1.dist-info}/top_level.txt +0 -0
@@ -81,8 +81,10 @@ class ModelClient:
81
81
  time.sleep(next(backoff_iterator))
82
82
  continue
83
83
  break
84
- if response.status.code == status_code_pb2.INPUT_UNSUPPORTED_FORMAT:
85
- # return code from older models that don't support _GET_SIGNATURES
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
86
88
  self._method_signatures = {}
87
89
  self._define_compatability_functions()
88
90
  return
@@ -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
  ]
@@ -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"]
@@ -14,13 +14,14 @@ from google.protobuf import json_format
14
14
  from rich import print
15
15
  from rich.markup import escape
16
16
 
17
- from clarifai.client import BaseClient
17
+ from clarifai.client.base import BaseClient
18
18
  from clarifai.runners.models.model_class import ModelClass
19
19
  from clarifai.runners.utils.const import (
20
20
  AVAILABLE_PYTHON_IMAGES, AVAILABLE_TORCH_IMAGES, CONCEPTS_REQUIRED_MODEL_TYPE,
21
21
  DEFAULT_DOWNLOAD_CHECKPOINT_WHEN, DEFAULT_PYTHON_VERSION, DEFAULT_RUNTIME_DOWNLOAD_PATH,
22
22
  PYTHON_BASE_IMAGE, TORCH_BASE_IMAGE)
23
23
  from clarifai.runners.utils.loader import HuggingFaceLoader
24
+ from clarifai.runners.utils.method_signatures import signatures_to_yaml
24
25
  from clarifai.urls.helper import ClarifaiUrlHelper
25
26
  from clarifai.utils.logging import logger
26
27
  from clarifai.versions import CLIENT_VERSION
@@ -69,6 +70,18 @@ class ModelBuilder:
69
70
  """
70
71
  Create an instance of the model class, as specified in the config file.
71
72
  """
73
+ model_class = self.load_model_class()
74
+
75
+ # initialize the model
76
+ model = model_class()
77
+ if load_model:
78
+ model.load_model()
79
+ return model
80
+
81
+ def load_model_class(self):
82
+ """
83
+ Import the model class from the model.py file.
84
+ """
72
85
  # look for default model.py file location
73
86
  for loc in ["model.py", "1/model.py"]:
74
87
  model_file = os.path.join(self.folder, loc)
@@ -107,12 +120,7 @@ class ModelBuilder:
107
120
  "Could not determine model class. There should be exactly one model inheriting from ModelClass defined in the model.py"
108
121
  )
109
122
  model_class = classes[0]
110
-
111
- # initialize the model
112
- model = model_class()
113
- if load_model:
114
- model.load_model()
115
- return model
123
+ return model_class
116
124
 
117
125
  def _validate_folder(self, folder):
118
126
  if folder == ".":
@@ -253,6 +261,15 @@ class ModelBuilder:
253
261
  total_size += member.size
254
262
  return total_size
255
263
 
264
+ def method_signatures_yaml(self):
265
+ """
266
+ Returns the method signatures for the model class in YAML format.
267
+ """
268
+ model_class = self.load_model_class()
269
+ method_info = model_class._get_method_info()
270
+ signatures = {name: m.signature for name, m in method_info.items()}
271
+ return signatures_to_yaml(signatures)
272
+
256
273
  @property
257
274
  def client(self):
258
275
  if self._client is None:
@@ -1,41 +1,269 @@
1
- from abc import ABC, abstractmethod
2
- from typing import Iterator
1
+ import inspect
2
+ import itertools
3
+ import logging
4
+ import os
5
+ import traceback
6
+ from abc import ABC
7
+ from typing import Any, Dict, Iterator, List
3
8
 
4
- from clarifai_grpc.grpc.api import service_pb2
9
+ from clarifai_grpc.grpc.api import resources_pb2, service_pb2
10
+ from clarifai_grpc.grpc.api.status import status_code_pb2, status_pb2
11
+
12
+ from clarifai.runners.utils import data_types
13
+ from clarifai.runners.utils.method_signatures import (build_function_signature, deserialize,
14
+ get_stream_from_signature, serialize,
15
+ signatures_to_json)
16
+
17
+ _METHOD_INFO_ATTR = '_cf_method_info'
18
+
19
+ _RAISE_EXCEPTIONS = os.getenv("RAISE_EXCEPTIONS", "false").lower() in ("true", "1")
5
20
 
6
21
 
7
22
  class ModelClass(ABC):
23
+ '''
24
+ Base class for model classes that can be run as a service.
25
+
26
+ Define predict, generate, or stream methods using the @ModelClass.method decorator.
27
+
28
+ Example:
29
+
30
+ from clarifai.runners.model_class import ModelClass
31
+ from clarifai.runners.utils.data_types import NamedFields, Stream
32
+
33
+ class MyModel(ModelClass):
34
+
35
+ @ModelClass.method
36
+ def predict(self, x: str, y: int) -> List[str]:
37
+ return [x] * y
38
+
39
+ @ModelClass.method
40
+ def generate(self, x: str, y: int) -> Stream[str]:
41
+ for i in range(y):
42
+ yield x + str(i)
43
+
44
+ @ModelClass.method
45
+ def stream(self, input_stream: Stream[NamedFields(x=str, y=int)]) -> Stream[str]:
46
+ for item in input_stream:
47
+ yield item.x + ' ' + str(item.y)
48
+ '''
49
+
50
+ @staticmethod
51
+ def method(func):
52
+ setattr(func, _METHOD_INFO_ATTR, _MethodInfo(func))
53
+ return func
54
+
55
+ def load_model(self):
56
+ """Load the model."""
57
+
58
+ def _handle_get_signatures_request(self) -> service_pb2.MultiOutputResponse:
59
+ methods = self._get_method_info()
60
+ signatures = {method.name: method.signature for method in methods.values()}
61
+ resp = service_pb2.MultiOutputResponse(status=status_pb2.Status(code=status_code_pb2.SUCCESS))
62
+ output = resp.outputs.add()
63
+ output.status.code = status_code_pb2.SUCCESS
64
+ output.data.text.raw = signatures_to_json(signatures)
65
+ return resp
66
+
67
+ def _batch_predict(self, method, inputs: List[Dict[str, Any]]) -> List[Any]:
68
+ """Batch predict method for multiple inputs."""
69
+ outputs = []
70
+ for input in inputs:
71
+ output = method(**input)
72
+ outputs.append(output)
73
+ return outputs
74
+
75
+ def _batch_generate(self, method, inputs: List[Dict[str, Any]]) -> Iterator[List[Any]]:
76
+ """Batch generate method for multiple inputs."""
77
+ generators = [method(**input) for input in inputs]
78
+ for outputs in itertools.zip_longest(*generators):
79
+ yield outputs
8
80
 
9
81
  def predict_wrapper(
10
82
  self, request: service_pb2.PostModelOutputsRequest) -> service_pb2.MultiOutputResponse:
11
- """This method is used for input/output proto data conversion"""
12
- return self.predict(request)
83
+ outputs = []
84
+ try:
85
+ # TODO add method name field to proto
86
+ method_name = 'predict'
87
+ if len(request.inputs) > 0 and '_method_name' in request.inputs[0].data.metadata:
88
+ method_name = request.inputs[0].data.metadata['_method_name']
89
+ if method_name == '_GET_SIGNATURES': # special case to fetch signatures, TODO add endpoint for this
90
+ return self._handle_get_signatures_request()
91
+ if method_name not in self._get_method_info():
92
+ raise ValueError(f"Method {method_name} not found in model class")
93
+ method = getattr(self, method_name)
94
+ method_info = method._cf_method_info
95
+ signature = method_info.signature
96
+ python_param_types = method_info.python_param_types
97
+ inputs = self._convert_input_protos_to_python(request.inputs, signature.inputs,
98
+ python_param_types)
99
+ if len(inputs) == 1:
100
+ inputs = inputs[0]
101
+ output = method(**inputs)
102
+ outputs.append(self._convert_output_to_proto(output, signature.outputs))
103
+ else:
104
+ outputs = self._batch_predict(method, inputs)
105
+ outputs = [self._convert_output_to_proto(output, signature.outputs) for output in outputs]
106
+
107
+ return service_pb2.MultiOutputResponse(
108
+ outputs=outputs, status=status_pb2.Status(code=status_code_pb2.SUCCESS))
109
+ except Exception as e:
110
+ if _RAISE_EXCEPTIONS:
111
+ raise
112
+ logging.exception("Error in predict")
113
+ return service_pb2.MultiOutputResponse(status=status_pb2.Status(
114
+ code=status_code_pb2.FAILURE,
115
+ details=str(e),
116
+ stack_trace=traceback.format_exc().split('\n')))
13
117
 
14
118
  def generate_wrapper(self, request: service_pb2.PostModelOutputsRequest
15
119
  ) -> Iterator[service_pb2.MultiOutputResponse]:
16
- """This method is used for input/output proto data conversion and yield outcome"""
17
- return self.generate(request)
120
+ try:
121
+ method_name = 'generate'
122
+ if len(request.inputs) > 0 and '_method_name' in request.inputs[0].data.metadata:
123
+ method_name = request.inputs[0].data.metadata['_method_name']
124
+ method = getattr(self, method_name)
125
+ method_info = method._cf_method_info
126
+ signature = method_info.signature
127
+ python_param_types = method_info.python_param_types
128
+
129
+ inputs = self._convert_input_protos_to_python(request.inputs, signature.inputs,
130
+ python_param_types)
131
+ if len(inputs) == 1:
132
+ inputs = inputs[0]
133
+ for output in method(**inputs):
134
+ resp = service_pb2.MultiOutputResponse()
135
+ self._convert_output_to_proto(output, signature.outputs, proto=resp.outputs.add())
136
+ resp.status.code = status_code_pb2.SUCCESS
137
+ yield resp
138
+ else:
139
+ for outputs in self._batch_generate(method, inputs):
140
+ resp = service_pb2.MultiOutputResponse()
141
+ for output in outputs:
142
+ self._convert_output_to_proto(output, signature.outputs, proto=resp.outputs.add())
143
+ resp.status.code = status_code_pb2.SUCCESS
144
+ yield resp
145
+ except Exception as e:
146
+ if _RAISE_EXCEPTIONS:
147
+ raise
148
+ logging.exception("Error in generate")
149
+ yield service_pb2.MultiOutputResponse(status=status_pb2.Status(
150
+ code=status_code_pb2.FAILURE,
151
+ details=str(e),
152
+ stack_trace=traceback.format_exc().split('\n')))
18
153
 
19
- def stream_wrapper(self, request: service_pb2.PostModelOutputsRequest
154
+ def stream_wrapper(self, request_iterator: Iterator[service_pb2.PostModelOutputsRequest]
20
155
  ) -> Iterator[service_pb2.MultiOutputResponse]:
21
- """This method is used for input/output proto data conversion and yield outcome"""
22
- return self.stream(request)
156
+ try:
157
+ request = next(request_iterator) # get first request to determine method
158
+ assert len(request.inputs) == 1, "Streaming requires exactly one input"
23
159
 
24
- @abstractmethod
25
- def load_model(self):
26
- raise NotImplementedError("load_model() not implemented")
27
-
28
- @abstractmethod
29
- def predict(self,
30
- request: service_pb2.PostModelOutputsRequest) -> service_pb2.MultiOutputResponse:
31
- raise NotImplementedError("run_input() not implemented")
32
-
33
- @abstractmethod
34
- def generate(self, request: service_pb2.PostModelOutputsRequest
35
- ) -> Iterator[service_pb2.MultiOutputResponse]:
36
- raise NotImplementedError("generate() not implemented")
37
-
38
- @abstractmethod
39
- def stream(self, request_iterator: Iterator[service_pb2.PostModelOutputsRequest]
40
- ) -> Iterator[service_pb2.MultiOutputResponse]:
41
- raise NotImplementedError("stream() not implemented")
160
+ method_name = 'generate'
161
+ if len(request.inputs) > 0 and '_method_name' in request.inputs[0].data.metadata:
162
+ method_name = request.inputs[0].data.metadata['_method_name']
163
+ method = getattr(self, method_name)
164
+ method_info = method._cf_method_info
165
+ signature = method_info.signature
166
+ python_param_types = method_info.python_param_types
167
+
168
+ # find the streaming vars in the signature
169
+ stream_sig = get_stream_from_signature(signature.inputs)
170
+ if stream_sig is None:
171
+ raise ValueError("Streaming method must have a Stream input")
172
+ stream_argname = stream_sig.name
173
+
174
+ # convert all inputs for the first request, including the first stream value
175
+ inputs = self._convert_input_protos_to_python(request.inputs, signature.inputs,
176
+ python_param_types)
177
+ kwargs = inputs[0]
178
+
179
+ # first streaming item
180
+ first_item = kwargs.pop(stream_argname)
181
+
182
+ # streaming generator
183
+ def InputStream():
184
+ yield first_item
185
+ # subsequent streaming items contain only the streaming input
186
+ for request in request_iterator:
187
+ item = self._convert_input_protos_to_python(request.inputs, stream_sig,
188
+ python_param_types)
189
+ item = item[0][stream_argname]
190
+ yield item
191
+
192
+ # add stream generator back to the input kwargs
193
+ kwargs[stream_argname] = InputStream()
194
+
195
+ for output in method(**kwargs):
196
+ resp = service_pb2.MultiOutputResponse()
197
+ self._convert_output_to_proto(output, signature.outputs, proto=resp.outputs.add())
198
+ resp.status.code = status_code_pb2.SUCCESS
199
+ yield resp
200
+ except Exception as e:
201
+ if _RAISE_EXCEPTIONS:
202
+ raise
203
+ logging.exception("Error in stream")
204
+ yield service_pb2.MultiOutputResponse(status=status_pb2.Status(
205
+ code=status_code_pb2.FAILURE,
206
+ details=str(e),
207
+ stack_trace=traceback.format_exc().split('\n')))
208
+
209
+ def _convert_input_protos_to_python(self, inputs: List[resources_pb2.Input], variables_signature,
210
+ python_param_types) -> List[Dict[str, Any]]:
211
+ result = []
212
+ for input in inputs:
213
+ kwargs = deserialize(input.data, variables_signature)
214
+ # dynamic cast to annotated types
215
+ for k, v in kwargs.items():
216
+ if k not in python_param_types:
217
+ continue
218
+ kwargs[k] = data_types.cast(v, python_param_types[k])
219
+ result.append(kwargs)
220
+ return result
221
+
222
+ def _convert_output_to_proto(self, output: Any, variables_signature,
223
+ proto=None) -> resources_pb2.Output:
224
+ if proto is None:
225
+ proto = resources_pb2.Output()
226
+ serialize({'return': output}, variables_signature, proto.data, is_output=True)
227
+ proto.status.code = status_code_pb2.SUCCESS
228
+ return proto
229
+
230
+ @classmethod
231
+ def _register_model_methods(cls):
232
+ # go up the class hierarchy to find all decorated methods, and add to registry of current class
233
+ methods = {}
234
+ for base in reversed(cls.__mro__):
235
+ for name, method in base.__dict__.items():
236
+ method_info = getattr(method, _METHOD_INFO_ATTR, None)
237
+ if not method_info: # regular function, not a model method
238
+ continue
239
+ methods[name] = method_info
240
+ # check for generic predict(request) -> response, etc. methods
241
+ #for name in ('predict', 'generate', 'stream'):
242
+ # if hasattr(cls, name):
243
+ # method = getattr(cls, name)
244
+ # if not hasattr(method, _METHOD_INFO_ATTR): # not already put in registry
245
+ # methods[name] = _MethodInfo(method)
246
+ # set method table for this class in the registry
247
+ return methods
248
+
249
+ @classmethod
250
+ def _get_method_info(cls, func_name=None):
251
+ if not hasattr(cls, _METHOD_INFO_ATTR):
252
+ setattr(cls, _METHOD_INFO_ATTR, cls._register_model_methods())
253
+ method_info = getattr(cls, _METHOD_INFO_ATTR)
254
+ if func_name:
255
+ return method_info[func_name]
256
+ return method_info
257
+
258
+
259
+ class _MethodInfo:
260
+
261
+ def __init__(self, method):
262
+ self.name = method.__name__
263
+ self.signature = build_function_signature(method)
264
+ self.python_param_types = {
265
+ p.name: p.annotation
266
+ for p in inspect.signature(method).parameters.values()
267
+ if p.annotation != inspect.Parameter.empty
268
+ }
269
+ self.python_param_types.pop('self', None)
@@ -7,14 +7,11 @@ import subprocess
7
7
  import sys
8
8
  import tempfile
9
9
  import time
10
- import traceback
11
10
  import venv
12
11
 
13
12
  from clarifai_grpc.grpc.api import resources_pb2, service_pb2
14
- from clarifai_grpc.grpc.api.status import status_code_pb2, status_pb2
15
13
 
16
14
  from clarifai.runners.models.model_builder import ModelBuilder
17
- from clarifai.runners.utils.url_fetcher import ensure_urls_downloaded
18
15
  from clarifai.utils.logging import logger
19
16
 
20
17
 
@@ -111,85 +108,13 @@ class ModelRunLocally:
111
108
  for i in range(1):
112
109
  yield request
113
110
 
114
- def _run_model_inference(self, model):
115
- """Perform inference using the model."""
116
- request = self._build_request()
117
- stream_request = self._build_stream_request()
118
-
119
- ensure_urls_downloaded(request)
120
- predict_response = None
121
- generate_response = None
122
- stream_response = None
123
- try:
124
- predict_response = model.predict(request)
125
- except NotImplementedError:
126
- logger.info("Model does not implement predict() method.")
127
- except Exception as e:
128
- logger.error(f"Model Prediction failed: {e}")
129
- traceback.print_exc()
130
- predict_response = service_pb2.MultiOutputResponse(status=status_pb2.Status(
131
- code=status_code_pb2.MODEL_PREDICTION_FAILED,
132
- description="Prediction failed",
133
- details="",
134
- internal_details=str(e),
135
- ))
136
-
137
- if predict_response:
138
- if predict_response.outputs[0].status.code != status_code_pb2.SUCCESS:
139
- logger.error(f"Moddel Prediction failed: {predict_response}")
140
- else:
141
- logger.info(f"Model Prediction succeeded: {predict_response}")
142
-
143
- try:
144
- generate_response = model.generate(request)
145
- except NotImplementedError:
146
- logger.info("Model does not implement generate() method.")
147
- except Exception as e:
148
- logger.error(f"Model Generation failed: {e}")
149
- traceback.print_exc()
150
- generate_response = service_pb2.MultiOutputResponse(status=status_pb2.Status(
151
- code=status_code_pb2.MODEL_GENERATION_FAILED,
152
- description="Generation failed",
153
- details="",
154
- internal_details=str(e),
155
- ))
156
-
157
- if generate_response:
158
- generate_first_res = next(generate_response)
159
- if generate_first_res.outputs[0].status.code != status_code_pb2.SUCCESS:
160
- logger.error(f"Moddel Prediction failed: {generate_first_res}")
161
- else:
162
- logger.info(
163
- f"Model Prediction succeeded for generate and first response: {generate_first_res}")
164
-
165
- try:
166
- stream_response = model.stream(stream_request)
167
- except NotImplementedError:
168
- logger.info("Model does not implement stream() method.")
169
- except Exception as e:
170
- logger.error(f"Model Stream failed: {e}")
171
- traceback.print_exc()
172
- stream_response = service_pb2.MultiOutputResponse(status=status_pb2.Status(
173
- code=status_code_pb2.MODEL_STREAM_FAILED,
174
- description="Stream failed",
175
- details="",
176
- internal_details=str(e),
177
- ))
178
-
179
- if stream_response:
180
- stream_first_res = next(stream_response)
181
- if stream_first_res.outputs[0].status.code != status_code_pb2.SUCCESS:
182
- logger.error(f"Moddel Prediction failed: {stream_first_res}")
183
- else:
184
- logger.info(
185
- f"Model Prediction succeeded for stream and first response: {stream_first_res}")
186
-
187
111
  def _run_test(self):
188
112
  """Test the model locally by making a prediction."""
189
113
  # Create the model
190
114
  model = self.builder.create_model_instance()
191
- # send an inference.
192
- self._run_model_inference(model)
115
+ # call its test method, if it has one
116
+ if hasattr(model, "test"):
117
+ model.test()
193
118
 
194
119
  def test_model(self):
195
120
  """Test the model by running it locally in the virtual environment."""
@@ -82,6 +82,8 @@ class ModelRunner(BaseRunner, HealthProbeRequestHandler):
82
82
  ensure_urls_downloaded(request)
83
83
 
84
84
  resp = self.model.predict_wrapper(request)
85
+ if resp.status.code != status_code_pb2.SUCCESS:
86
+ return service_pb2.RunnerItemOutput(multi_output_response=resp)
85
87
  successes = [o.status.code == status_code_pb2.SUCCESS for o in resp.outputs]
86
88
  if all(successes):
87
89
  status = status_pb2.Status(
@@ -1,3 +1,4 @@
1
+ import os
1
2
  from itertools import tee
2
3
  from typing import Iterator
3
4
 
@@ -6,6 +7,8 @@ from clarifai_grpc.grpc.api.status import status_code_pb2, status_pb2
6
7
 
7
8
  from ..utils.url_fetcher import ensure_urls_downloaded
8
9
 
10
+ _RAISE_EXCEPTIONS = os.getenv("RAISE_EXCEPTIONS", "false").lower() in ("true", "1")
11
+
9
12
 
10
13
  class ModelServicer(service_pb2_grpc.V2Servicer):
11
14
  """
@@ -33,6 +36,8 @@ class ModelServicer(service_pb2_grpc.V2Servicer):
33
36
  try:
34
37
  return self.model.predict_wrapper(request)
35
38
  except Exception as e:
39
+ if _RAISE_EXCEPTIONS:
40
+ raise
36
41
  return service_pb2.MultiOutputResponse(status=status_pb2.Status(
37
42
  code=status_code_pb2.MODEL_PREDICTION_FAILED,
38
43
  description="Failed",
@@ -50,8 +55,10 @@ class ModelServicer(service_pb2_grpc.V2Servicer):
50
55
  ensure_urls_downloaded(request)
51
56
 
52
57
  try:
53
- return self.model.generate_wrapper(request)
58
+ yield from self.model.generate_wrapper(request)
54
59
  except Exception as e:
60
+ if _RAISE_EXCEPTIONS:
61
+ raise
55
62
  yield service_pb2.MultiOutputResponse(status=status_pb2.Status(
56
63
  code=status_code_pb2.MODEL_PREDICTION_FAILED,
57
64
  description="Failed",
@@ -74,8 +81,10 @@ class ModelServicer(service_pb2_grpc.V2Servicer):
74
81
  ensure_urls_downloaded(req)
75
82
 
76
83
  try:
77
- return self.model.stream_wrapper(request_copy)
84
+ yield from self.model.stream_wrapper(request_copy)
78
85
  except Exception as e:
86
+ if _RAISE_EXCEPTIONS:
87
+ raise
79
88
  yield service_pb2.MultiOutputResponse(status=status_pb2.Status(
80
89
  code=status_code_pb2.MODEL_PREDICTION_FAILED,
81
90
  description="Failed",
@@ -34,9 +34,47 @@ class MessageData:
34
34
  raise TypeError(f'Incompatible type for {self.__class__.__name__}: {python_type}')
35
35
 
36
36
 
37
- class NamedFields(dict):
38
- __getattr__ = dict.__getitem__
39
- __setattr__ = dict.__setitem__
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())})"
40
78
 
41
79
  def __origin__(self):
42
80
  return self
@@ -381,6 +419,9 @@ def cast(value, python_type):
381
419
  if list_type and isinstance(value, np.ndarray):
382
420
  return value.tolist()
383
421
  if list_type and isinstance(value, list):
384
- inner_type = get_args(python_type)[0]
385
- return [cast(item, inner_type) for item in value]
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)}')
386
427
  return value