clarifai 9.6.1__py3-none-any.whl → 9.6.3__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 (44) hide show
  1. clarifai/auth/helper.py +3 -3
  2. clarifai/models/model_serving/constants.py +2 -3
  3. clarifai/models/model_serving/examples/text_to_text/bart-summarize/1/__init__.py +0 -0
  4. clarifai/models/model_serving/examples/text_to_text/bart-summarize/1/inference.py +47 -0
  5. clarifai/models/model_serving/examples/text_to_text/bart-summarize/1/model.py +60 -0
  6. clarifai/models/model_serving/examples/visual_embedding/vit-base/1/__init__.py +0 -0
  7. clarifai/models/model_serving/examples/visual_embedding/vit-base/1/inference.py +51 -0
  8. clarifai/models/model_serving/examples/visual_embedding/vit-base/1/model.py +60 -0
  9. clarifai/models/model_serving/examples/visual_segmentation/segformer-b2/1/__init__.py +0 -0
  10. clarifai/models/model_serving/examples/visual_segmentation/segformer-b2/1/inference.py +55 -0
  11. clarifai/models/model_serving/examples/visual_segmentation/segformer-b2/1/model.py +60 -0
  12. clarifai/models/model_serving/model_config/deploy.py +27 -3
  13. clarifai/models/model_serving/model_config/triton_config.py +30 -0
  14. clarifai/models/model_serving/models/model_types.py +122 -0
  15. clarifai/models/model_serving/models/output.py +62 -0
  16. clarifai/models/model_serving/models/pb_model.py +0 -1
  17. clarifai/modules/style.css +7 -0
  18. clarifai/runners/base.py +140 -0
  19. clarifai/runners/example.py +36 -0
  20. {clarifai-9.6.1.dist-info → clarifai-9.6.3.dist-info}/METADATA +1 -1
  21. {clarifai-9.6.1.dist-info → clarifai-9.6.3.dist-info}/RECORD +44 -22
  22. clarifai_utils/auth/helper.py +3 -3
  23. clarifai_utils/models/model_serving/constants.py +2 -3
  24. clarifai_utils/models/model_serving/examples/text_to_text/bart-summarize/1/__init__.py +0 -0
  25. clarifai_utils/models/model_serving/examples/text_to_text/bart-summarize/1/inference.py +47 -0
  26. clarifai_utils/models/model_serving/examples/text_to_text/bart-summarize/1/model.py +60 -0
  27. clarifai_utils/models/model_serving/examples/visual_embedding/vit-base/1/__init__.py +0 -0
  28. clarifai_utils/models/model_serving/examples/visual_embedding/vit-base/1/inference.py +51 -0
  29. clarifai_utils/models/model_serving/examples/visual_embedding/vit-base/1/model.py +60 -0
  30. clarifai_utils/models/model_serving/examples/visual_segmentation/segformer-b2/1/__init__.py +0 -0
  31. clarifai_utils/models/model_serving/examples/visual_segmentation/segformer-b2/1/inference.py +55 -0
  32. clarifai_utils/models/model_serving/examples/visual_segmentation/segformer-b2/1/model.py +60 -0
  33. clarifai_utils/models/model_serving/model_config/deploy.py +27 -3
  34. clarifai_utils/models/model_serving/model_config/triton_config.py +30 -0
  35. clarifai_utils/models/model_serving/models/model_types.py +122 -0
  36. clarifai_utils/models/model_serving/models/output.py +62 -0
  37. clarifai_utils/models/model_serving/models/pb_model.py +0 -1
  38. clarifai_utils/modules/style.css +7 -0
  39. clarifai_utils/runners/base.py +140 -0
  40. clarifai_utils/runners/example.py +36 -0
  41. {clarifai-9.6.1.dist-info → clarifai-9.6.3.dist-info}/LICENSE +0 -0
  42. {clarifai-9.6.1.dist-info → clarifai-9.6.3.dist-info}/WHEEL +0 -0
  43. {clarifai-9.6.1.dist-info → clarifai-9.6.3.dist-info}/entry_points.txt +0 -0
  44. {clarifai-9.6.1.dist-info → clarifai-9.6.3.dist-info}/top_level.txt +0 -0
clarifai/auth/helper.py CHANGED
@@ -131,7 +131,7 @@ class ClarifaiAuthHelper:
131
131
 
132
132
  # Then add in the query params.
133
133
  try:
134
- auth = auth.add_streamlit_query_params(query_params)
134
+ auth.add_streamlit_query_params(st.experimental_get_query_params())
135
135
  except Exception as e:
136
136
  st.error(e)
137
137
  st.stop()
@@ -165,7 +165,7 @@ class ClarifaiAuthHelper:
165
165
  auth = ClarifaiAuthHelper("", "", "", "", validate=False)
166
166
 
167
167
  # Then add in the query params.
168
- auth = auth.add_streamlit_query_params(query_params)
168
+ auth.add_streamlit_query_params(query_params)
169
169
 
170
170
  # Then validate.
171
171
  auth.validate()
@@ -238,7 +238,7 @@ Additionally, these optional params are supported:
238
238
  """
239
239
  user_id = os.environ.get("CLARIFAI_USER_ID", "")
240
240
  app_id = os.environ.get("CLARIFAI_APP_ID", "")
241
- token = os.environ("CLARIFAI_SESSION_TOKEN", "")
241
+ token = os.environ.get("CLARIFAI_SESSION_TOKEN", "")
242
242
  pat = os.environ.get("CLARIFAI_PAT", "")
243
243
  base = os.environ.get("CLARIFAI_API_BASE", DEFAULT_BASE)
244
244
  ui = os.environ.get("CLARIFAI_UI", DEFAULT_UI)
@@ -1,6 +1,5 @@
1
1
  # Clarifai model types
2
2
  MODEL_TYPES = [
3
- "visual-detector",
4
- "visual-classifier",
5
- "text-classifier",
3
+ "visual-detector", "visual-classifier", "text-classifier", "text-to-text", "text-embedder",
4
+ "text-to-image", "visual-embedder", "visual-segmenter"
6
5
  ]
@@ -0,0 +1,47 @@
1
+ # This file contains boilerplate code to allow users write their model
2
+ # inference code that will then interact with the Triton Inference Server
3
+ # Python backend to serve end user requests.
4
+ # The module name, module path, class name & get_predictions() method names MUST be maintained as is
5
+ # but other methods may be added within the class as deemed fit provided
6
+ # they are invoked within the main get_predictions() inference method
7
+ # if they play a role in any step of model inference
8
+ """User model inference script."""
9
+
10
+ import os
11
+ from pathlib import Path
12
+ import numpy as np
13
+ from transformers import pipeline
14
+
15
+ from clarifai.models.model_serving.models.model_types import text_to_text
16
+ from clarifai.models.model_serving.models.output import TextOutput
17
+
18
+
19
+ class InferenceModel:
20
+ """User model inference class."""
21
+
22
+ def __init__(self) -> None:
23
+ """
24
+ Load inference time artifacts that are called frequently .e.g. models, tokenizers, etc.
25
+ in this method so they are loaded only once for faster inference.
26
+ """
27
+ self.base_path: Path = os.path.dirname(__file__)
28
+ self.huggingface_model_path = os.path.join(self.base_path, "bart-large-summarizer")
29
+ self.pipeline = pipeline("summarization", model=self.huggingface_model_path)
30
+
31
+ @text_to_text
32
+ def get_predictions(self, input_data):
33
+ """
34
+ Generates summaries of input text.
35
+
36
+ Args:
37
+ -----
38
+ input_data: A single input data item to predict on.
39
+ Input data can be an image or text, etc depending on the model type.
40
+
41
+ Returns:
42
+ --------
43
+ One of the clarifai.models.model_serving.models.output types. Refer to the README/docs
44
+ """
45
+ summary = self.pipeline(input_data, max_length=50, min_length=30, do_sample=False)
46
+ generated_text = np.array([summary[0]['summary_text']], dtype=object)
47
+ return TextOutput(predicted_text=generated_text)
@@ -0,0 +1,60 @@
1
+ # Copyright 2023 Clarifai, Inc.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """Triton inference server Python Backend Model."""
14
+
15
+ import os
16
+ import sys
17
+
18
+ try:
19
+ import triton_python_backend_utils as pb_utils
20
+ except ModuleNotFoundError:
21
+ pass
22
+ from google.protobuf import text_format
23
+ from tritonclient.grpc.model_config_pb2 import ModelConfig
24
+
25
+
26
+ class TritonPythonModel:
27
+ """
28
+ Triton Python BE Model.
29
+ """
30
+
31
+ def initialize(self, args):
32
+ """
33
+ Triton server init.
34
+ """
35
+ args["model_repository"] = args["model_repository"].replace("/1/model.py", "")
36
+ sys.path.append(os.path.dirname(__file__))
37
+ from inference import InferenceModel
38
+
39
+ self.inference_obj = InferenceModel()
40
+
41
+ # Read input_name from config file
42
+ self.config_msg = ModelConfig()
43
+ with open(os.path.join(args["model_repository"], "config.pbtxt"), "r") as f:
44
+ cfg = f.read()
45
+ text_format.Merge(cfg, self.config_msg)
46
+ self.input_name = [inp.name for inp in self.config_msg.input][0]
47
+
48
+ def execute(self, requests):
49
+ """
50
+ Serve model inference requests.
51
+ """
52
+ responses = []
53
+
54
+ for request in requests:
55
+ in_batch = pb_utils.get_input_tensor_by_name(request, self.input_name)
56
+ in_batch = in_batch.as_numpy()
57
+ inference_response = self.inference_obj.get_predictions(in_batch)
58
+ responses.append(inference_response)
59
+
60
+ return responses
@@ -0,0 +1,51 @@
1
+ # This file contains boilerplate code to allow users write their model
2
+ # inference code that will then interact with the Triton Inference Server
3
+ # Python backend to serve end user requests.
4
+ # The module name, module path, class name & get_predictions() method names MUST be maintained as is
5
+ # but other methods may be added within the class as deemed fit provided
6
+ # they are invoked within the main get_predictions() inference method
7
+ # if they play a role in any step of model inference
8
+ """User model inference script."""
9
+
10
+ import os
11
+ from pathlib import Path
12
+
13
+ import torch
14
+ from transformers import AutoModel, ViTImageProcessor
15
+
16
+ from clarifai.models.model_serving.models.model_types import visual_embedder
17
+ from clarifai.models.model_serving.models.output import EmbeddingOutput
18
+
19
+
20
+ class InferenceModel:
21
+ """User model inference class."""
22
+
23
+ def __init__(self) -> None:
24
+ """
25
+ Load inference time artifacts that are called frequently .e.g. models, tokenizers, etc.
26
+ in this method so they are loaded only once for faster inference.
27
+ """
28
+ self.base_path: Path = os.path.dirname(__file__)
29
+ self.huggingface_model_path = os.path.join(self.base_path, "vit-base-patch16-224")
30
+ self.processor = ViTImageProcessor.from_pretrained(self.huggingface_model_path)
31
+ self.model = AutoModel.from_pretrained(self.huggingface_model_path)
32
+
33
+ @visual_embedder
34
+ def get_predictions(self, input_data):
35
+ """
36
+ Main model inference method.
37
+
38
+ Args:
39
+ -----
40
+ input_data: A single input data item to predict on.
41
+ Input data can be an image or text, etc depending on the model type.
42
+
43
+ Returns:
44
+ --------
45
+ One of the clarifai.models.model_serving.models.output types. Refer to the README/docs
46
+ """
47
+ inputs = self.processor(images=input_data, return_tensors="pt")
48
+ with torch.no_grad():
49
+ embedding_vector = self.model(**inputs).last_hidden_state[:, 0].cpu().numpy()
50
+
51
+ return EmbeddingOutput(embedding_vector=embedding_vector[0])
@@ -0,0 +1,60 @@
1
+ # Copyright 2023 Clarifai, Inc.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """Triton inference server Python Backend Model."""
14
+
15
+ import os
16
+ import sys
17
+
18
+ try:
19
+ import triton_python_backend_utils as pb_utils
20
+ except ModuleNotFoundError:
21
+ pass
22
+ from google.protobuf import text_format
23
+ from tritonclient.grpc.model_config_pb2 import ModelConfig
24
+
25
+
26
+ class TritonPythonModel:
27
+ """
28
+ Triton Python BE Model.
29
+ """
30
+
31
+ def initialize(self, args):
32
+ """
33
+ Triton server init.
34
+ """
35
+ args["model_repository"] = args["model_repository"].replace("/1/model.py", "")
36
+ sys.path.append(os.path.dirname(__file__))
37
+ from inference import InferenceModel
38
+
39
+ self.inference_obj = InferenceModel()
40
+
41
+ # Read input_name from config file
42
+ self.config_msg = ModelConfig()
43
+ with open(os.path.join(args["model_repository"], "config.pbtxt"), "r") as f:
44
+ cfg = f.read()
45
+ text_format.Merge(cfg, self.config_msg)
46
+ self.input_name = [inp.name for inp in self.config_msg.input][0]
47
+
48
+ def execute(self, requests):
49
+ """
50
+ Serve model inference requests.
51
+ """
52
+ responses = []
53
+
54
+ for request in requests:
55
+ in_batch = pb_utils.get_input_tensor_by_name(request, self.input_name)
56
+ in_batch = in_batch.as_numpy()
57
+ inference_response = self.inference_obj.get_predictions(in_batch)
58
+ responses.append(inference_response)
59
+
60
+ return responses
@@ -0,0 +1,55 @@
1
+ # This file contains boilerplate code to allow users write their model
2
+ # inference code that will then interact with the Triton Inference Server
3
+ # Python backend to serve end user requests.
4
+ # The module name, module path, class name & get_predictions() method names MUST be maintained as is
5
+ # but other methods may be added within the class as deemed fit provided
6
+ # they are invoked within the main get_predictions() inference method
7
+ # if they play a role in any step of model inference
8
+ """User model inference script."""
9
+
10
+ import os
11
+ from pathlib import Path
12
+
13
+ import torch
14
+ from transformers import AutoModelForSemanticSegmentation, SegformerImageProcessor
15
+
16
+ from clarifai.models.model_serving.models.model_types import visual_segmenter
17
+ from clarifai.models.model_serving.models.output import MasksOutput
18
+
19
+
20
+ class InferenceModel:
21
+ """User model inference class."""
22
+
23
+ def __init__(self) -> None:
24
+ """
25
+ Load inference time artifacts that are called frequently .e.g. models, tokenizers, etc.
26
+ in this method so they are loaded only once for faster inference.
27
+ """
28
+ self.base_path: Path = os.path.dirname(__file__)
29
+ self.huggingface_model_path = os.path.join(self.base_path, "segformer_b2_clothes")
30
+ #self.labels_path = os.path.join(Path(self.base_path).parents[0], "labels.txt")
31
+ self.processor = SegformerImageProcessor.from_pretrained(self.huggingface_model_path)
32
+ self.model = AutoModelForSemanticSegmentation.from_pretrained(self.huggingface_model_path)
33
+
34
+ @visual_segmenter
35
+ def get_predictions(self, input_data):
36
+ """
37
+ Main model inference method.
38
+
39
+ Args:
40
+ -----
41
+ input_data: A single input data item to predict on.
42
+ Input data can be an image or text, etc depending on the model type.
43
+
44
+ Returns:
45
+ --------
46
+ One of the clarifai.models.model_serving.models.output types. Refer to the README/docs
47
+ """
48
+ inputs = self.processor(images=input_data, return_tensors="pt")
49
+ with torch.no_grad():
50
+ output = self.model(**inputs)
51
+
52
+ logits = output.logits.cpu()
53
+ mask = logits.argmax(dim=1)[0].numpy()
54
+
55
+ return MasksOutput(predicted_mask=mask)
@@ -0,0 +1,60 @@
1
+ # Copyright 2023 Clarifai, Inc.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """Triton inference server Python Backend Model."""
14
+
15
+ import os
16
+ import sys
17
+
18
+ try:
19
+ import triton_python_backend_utils as pb_utils
20
+ except ModuleNotFoundError:
21
+ pass
22
+ from google.protobuf import text_format
23
+ from tritonclient.grpc.model_config_pb2 import ModelConfig
24
+
25
+
26
+ class TritonPythonModel:
27
+ """
28
+ Triton Python BE Model.
29
+ """
30
+
31
+ def initialize(self, args):
32
+ """
33
+ Triton server init.
34
+ """
35
+ args["model_repository"] = args["model_repository"].replace("/1/model.py", "")
36
+ sys.path.append(os.path.dirname(__file__))
37
+ from inference import InferenceModel
38
+
39
+ self.inference_obj = InferenceModel()
40
+
41
+ # Read input_name from config file
42
+ self.config_msg = ModelConfig()
43
+ with open(os.path.join(args["model_repository"], "config.pbtxt"), "r") as f:
44
+ cfg = f.read()
45
+ text_format.Merge(cfg, self.config_msg)
46
+ self.input_name = [inp.name for inp in self.config_msg.input][0]
47
+
48
+ def execute(self, requests):
49
+ """
50
+ Serve model inference requests.
51
+ """
52
+ responses = []
53
+
54
+ for request in requests:
55
+ in_batch = pb_utils.get_input_tensor_by_name(request, self.input_name)
56
+ in_batch = in_batch.as_numpy()
57
+ inference_response = self.inference_obj.get_predictions(in_batch)
58
+ responses.append(inference_response)
59
+
60
+ return responses
@@ -36,16 +36,40 @@ class ClarifaiFieldsMap:
36
36
  """
37
37
  Set mapping of clarifai in/output vs triton in/output
38
38
  """
39
+ text_input_fields = {"text": "text"}
40
+ image_input_fields = {"image": "image"}
41
+
42
+ embedding_output_fields = {"embeddings": "embeddings"}
43
+
39
44
  if self.model_type == "visual-detector":
40
- self.input_fields_map = {"image": "image"}
45
+ self.input_fields_map = image_input_fields
41
46
  self.output_fields_map = {
42
47
  "regions[...].region_info.bounding_box": "predicted_bboxes",
43
48
  "regions[...].data.concepts[...].id": "predicted_labels",
44
49
  "regions[...].data.concepts[...].value": "predicted_scores"
45
50
  }
46
51
  elif self.model_type == "visual-classifier":
47
- self.input_fields_map = {"image": "image"}
52
+ self.input_fields_map = image_input_fields
48
53
  self.output_fields_map = {"concepts": "softmax_predictions"}
49
54
  elif self.model_type == "text-classifier":
50
- self.input_fields_map = {"text": "text"}
55
+ self.input_fields_map = text_input_fields
51
56
  self.output_fields_map = {"concepts": "softmax_predictions"}
57
+ elif self.model_type == "text-embedder":
58
+ self.input_fields_map = text_input_fields
59
+ self.output_fields_map = embedding_output_fields
60
+ elif self.model_type == "text-to-text":
61
+ self.input_fields_map = text_input_fields
62
+ # input and output fields are the same for text-to-text
63
+ self.output_fields_map = text_input_fields
64
+ elif self.model_type == "text-to-image":
65
+ self.input_fields_map = text_input_fields
66
+ # image output fields match image_input fields
67
+ self.output_fields_map = image_input_fields
68
+ elif self.model_type == "visual-embedder":
69
+ self.input_fields_map = image_input_fields
70
+ self.output_fields_map = embedding_output_fields
71
+ elif self.model_type == "visual-segmenter":
72
+ self.input_fields_map = image_input_fields
73
+ self.output_fields_map = {
74
+ "regions[...].region_info.mask,regions[...].data.concepts": "predicted_mask"
75
+ }
@@ -163,3 +163,33 @@ class TritonModelConfig:
163
163
  # with each value being the confidence for the respective model output.
164
164
  del pred_labels.labels
165
165
  self.output.append(pred_labels)
166
+
167
+ elif self.model_type == "text-to-text":
168
+ self.input.append(text_input)
169
+ pred_text = OutputConfig(name="text", data_type="TYPE_STRING", dims=[1], labels=False)
170
+ self.output.append(pred_text)
171
+
172
+ elif self.model_type == "text-embedder":
173
+ self.input.append(text_input)
174
+ embedding_vector = OutputConfig(
175
+ name="embeddings", data_type="TYPE_FP32", dims=[-1], labels=False)
176
+ self.output.append(embedding_vector)
177
+
178
+ elif self.model_type == "text-to-image":
179
+ self.input.append(text_input)
180
+ gen_image = OutputConfig(
181
+ name="image", data_type="TYPE_UINT8", dims=[-1, -1, 3], labels=False)
182
+ self.output.append(gen_image)
183
+
184
+ elif self.model_type == "visual-embedder":
185
+ self.input.append(image_input)
186
+ embedding_vector = OutputConfig(
187
+ name="embeddings", data_type="TYPE_FP32", dims=[-1], labels=False)
188
+ self.output.append(embedding_vector)
189
+
190
+ elif self.model_type == "visual-segmenter":
191
+ self.input.append(image_input)
192
+ pred_masks = OutputConfig(
193
+ name="predicted_mask", data_type="TYPE_INT64", dims=[-1, -1], labels=True)
194
+ del pred_masks.labels
195
+ self.output.append(pred_masks)
@@ -112,3 +112,125 @@ def text_classifier(func: Callable):
112
112
  return inference_response
113
113
 
114
114
  return parse_predictions
115
+
116
+
117
+ def text_to_text(func: Callable):
118
+ """
119
+ Text to text type output parser.
120
+ Convert a sequence of text into another e.g. text generation,
121
+ summarization or translation.
122
+ """
123
+
124
+ @wraps(func)
125
+ def parse_predictions(self, input_data: np.ndarray):
126
+ """
127
+ Format predictions and return clarifai compatible output.
128
+ """
129
+ out_text = []
130
+ input_data = [in_elem[0].decode() for in_elem in input_data]
131
+ for item in input_data:
132
+ preds = func(self, item)
133
+ out_text.append(preds.predicted_text)
134
+
135
+ out_text_tensor = pb_utils.Tensor("text", np.asarray(out_text, dtype=object))
136
+ inference_response = pb_utils.InferenceResponse(output_tensors=[out_text_tensor])
137
+
138
+ return inference_response
139
+
140
+ return parse_predictions
141
+
142
+
143
+ def text_embedder(func: Callable):
144
+ """
145
+ Text embedder type output parser.
146
+ Generates embeddings for an input text.
147
+ """
148
+
149
+ @wraps(func)
150
+ def parse_predictions(self, input_data: np.ndarray):
151
+ """
152
+ Format predictions and return clarifai compatible output.
153
+ """
154
+ out_embeddings = []
155
+ input_data = [in_elem[0].decode() for in_elem in input_data]
156
+ for item in input_data:
157
+ preds = func(self, item)
158
+ out_embeddings.append(preds.embedding_vector)
159
+
160
+ out_embed_tensor = pb_utils.Tensor("embeddings", np.asarray(out_embeddings, dtype=np.float32))
161
+ inference_response = pb_utils.InferenceResponse(output_tensors=[out_embed_tensor])
162
+
163
+ return inference_response
164
+
165
+ return parse_predictions
166
+
167
+
168
+ def visual_embedder(func: Callable):
169
+ """
170
+ Visual embedder type output parser.
171
+ Generates embeddings for an input image.
172
+ """
173
+
174
+ @wraps(func)
175
+ def parse_predictions(self, input_data: np.ndarray):
176
+ """
177
+ Format predictions and return clarifai compatible output.
178
+ """
179
+ out_embeddings = []
180
+ for item in input_data:
181
+ preds = func(self, item)
182
+ out_embeddings.append(preds.embedding_vector)
183
+
184
+ out_embed_tensor = pb_utils.Tensor("embeddings", np.asarray(out_embeddings, dtype=np.float32))
185
+ inference_response = pb_utils.InferenceResponse(output_tensors=[out_embed_tensor])
186
+
187
+ return inference_response
188
+
189
+ return parse_predictions
190
+
191
+
192
+ def visual_segmenter(func: Callable):
193
+ """
194
+ Visual segmenter type output parser.
195
+ """
196
+
197
+ @wraps(func)
198
+ def parse_predictions(self, input_data: np.ndarray):
199
+ """
200
+ Format predictions and return clarifai compatible output.
201
+ """
202
+ masks = []
203
+ for item in input_data:
204
+ preds = func(self, item)
205
+ masks.append(preds.predicted_mask)
206
+
207
+ out_mask_tensor = pb_utils.Tensor("predicted_mask", np.asarray(masks, dtype=np.int64))
208
+ inference_response = pb_utils.InferenceResponse(output_tensors=[out_mask_tensor])
209
+
210
+ return inference_response
211
+
212
+ return parse_predictions
213
+
214
+
215
+ def text_to_image(func: Callable):
216
+ """
217
+ Text to image type output parser.
218
+ """
219
+
220
+ @wraps(func)
221
+ def parse_predictions(self, input_data: np.ndarray):
222
+ """
223
+ Format predictions and return clarifai compatible output.
224
+ """
225
+ gen_images = []
226
+ input_data = [in_elem[0].decode() for in_elem in input_data]
227
+ for item in input_data:
228
+ preds = func(self, item)
229
+ gen_images.append(preds.image)
230
+
231
+ out_image_tensor = pb_utils.Tensor("image", np.asarray(gen_images, dtype=np.uint8))
232
+ inference_response = pb_utils.InferenceResponse(output_tensors=[out_image_tensor])
233
+
234
+ return inference_response
235
+
236
+ return parse_predictions
@@ -59,3 +59,65 @@ class ClassifierOutput:
59
59
  """
60
60
  assert self.predicted_scores.ndim == 1, \
61
61
  f"All predictions must be 1-dimensional, Got scores-dims: {self.predicted_scores.ndim} instead."
62
+
63
+
64
+ @dataclass
65
+ class TextOutput:
66
+ """
67
+ Takes model text predictions
68
+ """
69
+ predicted_text: np.ndarray
70
+
71
+ def __post_init__(self):
72
+ """
73
+ Validate input upon initialization.
74
+ """
75
+ assert self.predicted_text.ndim == 1, \
76
+ f"All predictions must be 1-dimensional, Got text-dims: {self.predicted_text.ndim} instead."
77
+
78
+
79
+ @dataclass
80
+ class EmbeddingOutput:
81
+ """
82
+ Takes embedding vector returned by a model.
83
+ """
84
+ embedding_vector: np.ndarray
85
+
86
+ def __post_init__(self):
87
+ """
88
+ Validate input upon initialization.
89
+ """
90
+ assert self.embedding_vector.ndim == 1, \
91
+ f"Embeddings must be 1-dimensional, Got embedding-dims: {self.embedding_vector.ndim} instead."
92
+
93
+
94
+ @dataclass
95
+ class MasksOutput:
96
+ """
97
+ Takes image segmentation masks returned by a model.
98
+ """
99
+ predicted_mask: np.ndarray
100
+
101
+ def __post_init__(self):
102
+ """
103
+ Validate input upon initialization.
104
+ """
105
+ assert self.predicted_mask.ndim == 2, \
106
+ f"predicted_mask must be 2-dimensional, Got mask dims: {self.predicted_mask.ndim} instead."
107
+
108
+
109
+ @dataclass
110
+ class ImageOutput:
111
+ """
112
+ Takes a predicted/generated image array as returned by a model.
113
+ """
114
+ image: np.ndarray
115
+
116
+ def __post_init__(self):
117
+ """
118
+ Validate input upon initialization.
119
+ """
120
+ assert self.image.ndim == 3, \
121
+ f"Generated image must be 3-dimensional, Got image-dims: {self.image.ndim} instead."
122
+ assert self.image.shape[2] == 3, \
123
+ f"The image channels dimension must equal 3, Got channel dim: {self.image.shape[2]} instead."
@@ -37,7 +37,6 @@ class TritonPythonModel:
37
37
  from inference import InferenceModel
38
38
 
39
39
  self.inference_obj = InferenceModel()
40
- self.device = "cuda:0" if "GPU" in args["model_instance_kind"] else "cpu"
41
40
 
42
41
  # Read input_name from config file
43
42
  self.config_msg = ModelConfig()
@@ -203,6 +203,13 @@ code
203
203
  border-color: #d0d5dd;
204
204
  box-shadow: 0 1px 2px rgba(16,24,40,.05);
205
205
  }
206
+
207
+ .stTextInput > div > div > input {
208
+ background-color: white;
209
+ }
210
+
211
+
212
+
206
213
  div[data-testid="stFileUploader"]>section {
207
214
  border: 1px dashed #d0d5dd;
208
215
  border-radius: 8px;