clarifai 11.4.3rc1__py3-none-any.whl → 11.4.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- clarifai/__init__.py +1 -1
- clarifai/cli/base.py +1 -2
- clarifai/cli/model.py +0 -2
- clarifai/client/app.py +2 -1
- clarifai/client/auth/helper.py +6 -4
- clarifai/client/compute_cluster.py +2 -1
- clarifai/client/dataset.py +2 -1
- clarifai/client/deployment.py +2 -1
- clarifai/client/input.py +2 -1
- clarifai/client/model.py +2 -1
- clarifai/client/model_client.py +2 -2
- clarifai/client/module.py +2 -1
- clarifai/client/nodepool.py +2 -1
- clarifai/client/runner.py +2 -1
- clarifai/client/search.py +2 -1
- clarifai/client/user.py +2 -1
- clarifai/client/workflow.py +2 -1
- clarifai/runners/models/mcp_class.py +6 -35
- clarifai/runners/models/model_builder.py +46 -42
- clarifai/runners/utils/code_script.py +40 -11
- clarifai/runners/utils/data_types/data_types.py +48 -0
- clarifai/runners/utils/data_utils.py +67 -43
- clarifai/runners/utils/method_signatures.py +0 -20
- clarifai/runners/utils/openai_convertor.py +103 -0
- clarifai/urls/helper.py +80 -12
- clarifai/utils/config.py +1 -1
- clarifai/utils/constants.py +4 -0
- {clarifai-11.4.3rc1.dist-info → clarifai-11.4.4.dist-info}/METADATA +13 -2
- clarifai-11.4.4.dist-info/RECORD +112 -0
- {clarifai-11.4.3rc1.dist-info → clarifai-11.4.4.dist-info}/WHEEL +1 -1
- clarifai/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/__pycache__/errors.cpython-312.pyc +0 -0
- clarifai/__pycache__/errors.cpython-39.pyc +0 -0
- clarifai/__pycache__/versions.cpython-312.pyc +0 -0
- clarifai/__pycache__/versions.cpython-39.pyc +0 -0
- clarifai/cli/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/base.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/compute_cluster.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/deployment.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/model.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/nodepool.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/app.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/app.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/base.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/base.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/compute_cluster.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/dataset.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/deployment.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/input.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/lister.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/model.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/model_client.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/module.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/nodepool.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/runner.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/search.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/user.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/workflow.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/helper.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/helper.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/register.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/register.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/stub.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/stub.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/base.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/base.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/dataset.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/input.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/model.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/rag.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/search.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/workflow.cpython-312.pyc +0 -0
- clarifai/datasets/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/datasets/export/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/datasets/export/__pycache__/inputs_annotations.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/base.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/features.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/image.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/multimodal.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/text.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/utils.cpython-312.pyc +0 -0
- clarifai/datasets/upload/loaders/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/datasets/upload/loaders/__pycache__/coco_detection.cpython-312.pyc +0 -0
- clarifai/datasets/upload/loaders/__pycache__/imagenet_classification.cpython-312.pyc +0 -0
- clarifai/modules/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/modules/__pycache__/css.cpython-312.pyc +0 -0
- clarifai/rag/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/rag/__pycache__/rag.cpython-312.pyc +0 -0
- clarifai/rag/__pycache__/utils.cpython-312.pyc +0 -0
- clarifai/runners/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/runners/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/runners/__pycache__/server.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/runners/models/__pycache__/base_typed_model.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/mcp_class.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_builder.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_builder.cpython-39.pyc +0 -0
- clarifai/runners/models/__pycache__/model_class.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_run_locally.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_runner.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_servicer.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/test_model_builder.cpython-312-pytest-8.3.5.pyc +0 -0
- clarifai/runners/models/base_typed_model.py +0 -238
- clarifai/runners/models/example_mcp_server.py +0 -44
- clarifai/runners/models/mcp_class.py~ +0 -149
- clarifai/runners/models/test_model_builder.py +0 -89
- clarifai/runners/utils/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/code_script.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/const.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/data_handler.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/data_types.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/data_utils.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/loader.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/method_signatures.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/serializers.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/url_fetcher.cpython-312.pyc +0 -0
- clarifai/runners/utils/data_handler.py +0 -231
- clarifai/runners/utils/data_types/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/runners/utils/data_types/__pycache__/data_types.cpython-312.pyc +0 -0
- clarifai/schema/__pycache__/search.cpython-312.pyc +0 -0
- clarifai/urls/__pycache__/helper.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/cli.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/config.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/constants.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/constants.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/logging.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/logging.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/misc.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/misc.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/model_train.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/protobuf.cpython-312.pyc +0 -0
- clarifai/utils/config.py~ +0 -145
- clarifai/utils/evaluation/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/utils/evaluation/__pycache__/helpers.cpython-312.pyc +0 -0
- clarifai/utils/evaluation/__pycache__/main.cpython-312.pyc +0 -0
- clarifai/workflows/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/workflows/__pycache__/export.cpython-312.pyc +0 -0
- clarifai/workflows/__pycache__/utils.cpython-312.pyc +0 -0
- clarifai/workflows/__pycache__/validate.cpython-312.pyc +0 -0
- clarifai-11.4.3rc1.dist-info/RECORD +0 -230
- {clarifai-11.4.3rc1.dist-info → clarifai-11.4.4.dist-info}/entry_points.txt +0 -0
- {clarifai-11.4.3rc1.dist-info → clarifai-11.4.4.dist-info/licenses}/LICENSE +0 -0
- {clarifai-11.4.3rc1.dist-info → clarifai-11.4.4.dist-info}/top_level.txt +0 -0
@@ -1,89 +0,0 @@
|
|
1
|
-
import unittest
|
2
|
-
from unittest.mock import patch, mock_open
|
3
|
-
from clarifai.runners.models.model_builder import (
|
4
|
-
ModelBuilder,
|
5
|
-
DEFAULT_DOWNLOAD_CHECKPOINT_WHEN,
|
6
|
-
)
|
7
|
-
|
8
|
-
mock_data = """
|
9
|
-
checkpoints:
|
10
|
-
type: huggingface
|
11
|
-
repo_id: test_repo
|
12
|
-
model:
|
13
|
-
user_id: test_user
|
14
|
-
app_id: test_app
|
15
|
-
id: test_model
|
16
|
-
model_type_id: test_type
|
17
|
-
inference_compute_info:
|
18
|
-
cpu_limit: "2"
|
19
|
-
cpu_memory: "4Gi"
|
20
|
-
num_accelerators: 0
|
21
|
-
"""
|
22
|
-
|
23
|
-
|
24
|
-
class TestModelBuilder(unittest.TestCase):
|
25
|
-
@patch("builtins.open", new_callable=mock_open, read_data=mock_data)
|
26
|
-
@patch("os.path.exists")
|
27
|
-
@patch("os.listdir")
|
28
|
-
def test_validate_folder(self, mock_listdir, mock_exists, mock_open_file):
|
29
|
-
mock_exists.return_value = True
|
30
|
-
mock_listdir.return_value = ["config.yaml", "1", "requirements.txt"]
|
31
|
-
|
32
|
-
builder = ModelBuilder(folder="test_folder", validate_api_ids=False)
|
33
|
-
validated_folder = builder._validate_folder("test_folder")
|
34
|
-
self.assertIn("test_folder", validated_folder)
|
35
|
-
|
36
|
-
def test_default_download_checkpoint_when(self):
|
37
|
-
self.assertEqual(DEFAULT_DOWNLOAD_CHECKPOINT_WHEN, "runtime")
|
38
|
-
|
39
|
-
@patch(
|
40
|
-
"builtins.open",
|
41
|
-
new_callable=mock_open,
|
42
|
-
read_data="checkpoints:\n type: huggingface\n repo_id: test_repo\n",
|
43
|
-
)
|
44
|
-
@patch("os.path.exists")
|
45
|
-
@patch("yaml.safe_load")
|
46
|
-
def test_load_config(self, mock_yaml_load, mock_exists, mock_open_file):
|
47
|
-
mock_exists.return_value = True
|
48
|
-
mock_yaml_load.return_value = {
|
49
|
-
"checkpoints": {"type": "huggingface", "repo_id": "test_repo"}
|
50
|
-
}
|
51
|
-
config = ModelBuilder._load_config("config.yaml")
|
52
|
-
self.assertIn("checkpoints", config)
|
53
|
-
self.assertEqual(config["checkpoints"]["type"], "huggingface")
|
54
|
-
|
55
|
-
@patch("shutil.copy")
|
56
|
-
@patch("os.path.exists")
|
57
|
-
def test_backup_config(self, mock_exists, mock_copy):
|
58
|
-
mock_exists.side_effect = [True, False] # config exists, backup does not
|
59
|
-
ModelBuilder._backup_config("config.yaml")
|
60
|
-
mock_copy.assert_called_once_with("config.yaml", "config.yaml.bak")
|
61
|
-
|
62
|
-
@patch("builtins.open", new_callable=mock_open)
|
63
|
-
@patch("yaml.safe_dump")
|
64
|
-
def test_save_config(self, mock_yaml_dump, mock_open_file):
|
65
|
-
config = {"key": "value"}
|
66
|
-
ModelBuilder._save_config("config.yaml", config)
|
67
|
-
mock_yaml_dump.assert_called_once_with(config, mock_open_file())
|
68
|
-
|
69
|
-
def test_validate_config_model(self):
|
70
|
-
builder = ModelBuilder(folder="test_folder", validate_api_ids=False)
|
71
|
-
builder.config = {"model": {}}
|
72
|
-
try:
|
73
|
-
builder._validate_config_model()
|
74
|
-
except AssertionError:
|
75
|
-
self.fail("_validate_config_model raised AssertionError unexpectedly!")
|
76
|
-
|
77
|
-
@patch("os.path.exists")
|
78
|
-
@patch("os.listdir")
|
79
|
-
def test_validate_folder_missing_config(self, mock_listdir, mock_exists):
|
80
|
-
mock_exists.return_value = True
|
81
|
-
mock_listdir.return_value = ["1", "requirements.txt"]
|
82
|
-
|
83
|
-
builder = ModelBuilder(folder="test_folder", validate_api_ids=False)
|
84
|
-
with self.assertRaises(AssertionError):
|
85
|
-
builder._validate_folder("test_folder")
|
86
|
-
|
87
|
-
|
88
|
-
if __name__ == "__main__":
|
89
|
-
unittest.main()
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
@@ -1,231 +0,0 @@
|
|
1
|
-
from typing import Dict, List, Tuple, Union
|
2
|
-
|
3
|
-
import numpy as np
|
4
|
-
from clarifai_grpc.grpc.api import resources_pb2
|
5
|
-
from clarifai_grpc.grpc.api.status import status_code_pb2, status_pb2
|
6
|
-
from PIL import Image
|
7
|
-
|
8
|
-
from clarifai.client.auth.helper import ClarifaiAuthHelper
|
9
|
-
|
10
|
-
from .data_utils import bytes_to_image, image_to_bytes
|
11
|
-
|
12
|
-
|
13
|
-
class BaseDataHandler:
|
14
|
-
|
15
|
-
def __init__(self,
|
16
|
-
proto: Union[resources_pb2.Input, resources_pb2.Output],
|
17
|
-
auth: ClarifaiAuthHelper = None):
|
18
|
-
self._proto = proto
|
19
|
-
self._auth = auth
|
20
|
-
|
21
|
-
#
|
22
|
-
def to_python(self):
|
23
|
-
return dict(text=self.text, image=self.image, audio=self.audio)
|
24
|
-
|
25
|
-
# ---------------- Start get/setters ---------------- #
|
26
|
-
# Proto
|
27
|
-
@property
|
28
|
-
def proto(self):
|
29
|
-
return self._proto
|
30
|
-
|
31
|
-
# Status
|
32
|
-
@property
|
33
|
-
def status(self) -> status_pb2.Status:
|
34
|
-
return self._proto.status
|
35
|
-
|
36
|
-
def set_status(self, code: str, description: str = ""):
|
37
|
-
self._proto.status.code = code
|
38
|
-
self._proto.status.description = description
|
39
|
-
|
40
|
-
# Text
|
41
|
-
@property
|
42
|
-
def text(self) -> Union[None, str]:
|
43
|
-
data = self._proto.data.text
|
44
|
-
text = None
|
45
|
-
if data.ByteSize():
|
46
|
-
if data.raw:
|
47
|
-
text = data.raw
|
48
|
-
else:
|
49
|
-
raise NotImplementedError
|
50
|
-
return text
|
51
|
-
|
52
|
-
def set_text(self, text: str):
|
53
|
-
self._proto.data.text.raw = text
|
54
|
-
|
55
|
-
# Image
|
56
|
-
@property
|
57
|
-
def image(self, format: str = "np") -> Union[None, Image.Image, np.ndarray]:
|
58
|
-
data = self._proto.data.image
|
59
|
-
image = None
|
60
|
-
if data.ByteSize():
|
61
|
-
data: resources_pb2.Image = data
|
62
|
-
if data.base64:
|
63
|
-
image = data.base64
|
64
|
-
elif data.url:
|
65
|
-
raise NotImplementedError
|
66
|
-
image = bytes_to_image(image)
|
67
|
-
image = image if not format == "np" else np.asarray(image).astype("uint8")
|
68
|
-
return image
|
69
|
-
|
70
|
-
def set_image(self, image: Union[Image.Image, np.ndarray]):
|
71
|
-
if isinstance(image, np.ndarray):
|
72
|
-
image = Image.fromarray(image)
|
73
|
-
self._proto.data.image.base64 = image_to_bytes(image)
|
74
|
-
|
75
|
-
# Audio
|
76
|
-
@property
|
77
|
-
def audio(self) -> bytes:
|
78
|
-
data = self._proto.data.audio
|
79
|
-
audio = None
|
80
|
-
if data.ByteSize():
|
81
|
-
if data.base64:
|
82
|
-
audio = data.base64
|
83
|
-
return audio
|
84
|
-
|
85
|
-
def set_audio(self, audio: bytes):
|
86
|
-
self._proto.data.audio.base64 = audio
|
87
|
-
|
88
|
-
# Bboxes
|
89
|
-
@property
|
90
|
-
def bboxes(self, real_coord: bool = False, image_width: int = None,
|
91
|
-
image_height: int = None) -> Tuple[List, List, List]:
|
92
|
-
if real_coord:
|
93
|
-
assert (image_height or image_width
|
94
|
-
), "image_height and image_width are required when when return real coordinates"
|
95
|
-
xyxy = []
|
96
|
-
scores = []
|
97
|
-
concepts = []
|
98
|
-
for _, each in enumerate(self._proto.data.regions):
|
99
|
-
box = each.region_info
|
100
|
-
score = each.value
|
101
|
-
concept = each.data.concepts[0].id
|
102
|
-
x1 = box.left_col
|
103
|
-
y1 = box.top_row
|
104
|
-
x2 = box.right_col
|
105
|
-
y2 = box.bottom_row
|
106
|
-
if real_coord:
|
107
|
-
x1 = x1 * image_width
|
108
|
-
y1 = y1 * image_height
|
109
|
-
x2 = x2 * image_width
|
110
|
-
y2 = y2 * image_height
|
111
|
-
xyxy.append([x1, y1, x2, y2])
|
112
|
-
scores.append(score)
|
113
|
-
concepts.append(concept)
|
114
|
-
|
115
|
-
return xyxy, scores, concepts
|
116
|
-
|
117
|
-
def set_bboxes(self,
|
118
|
-
boxes: list,
|
119
|
-
scores: list,
|
120
|
-
concepts: list,
|
121
|
-
real_coord: bool = False,
|
122
|
-
image_width: int = None,
|
123
|
-
image_height: int = None):
|
124
|
-
if real_coord:
|
125
|
-
assert (image_height and
|
126
|
-
image_width), "image_height and image_width are required when `real_coord` is set"
|
127
|
-
bboxes = [[x[1] / image_height, x[0] / image_width, x[3] / image_height, x[2] / image_width]
|
128
|
-
for x in boxes] # normalize the bboxes to [0,1] and [y1 x1 y2 x2]
|
129
|
-
bboxes = np.clip(bboxes, 0, 1.0)
|
130
|
-
|
131
|
-
regions = []
|
132
|
-
for ith, bbox in enumerate(bboxes):
|
133
|
-
score = scores[ith]
|
134
|
-
concept = concepts[ith]
|
135
|
-
if any([each > 1.0 for each in bbox]):
|
136
|
-
assert ValueError(
|
137
|
-
"Box coordinates is not normalized between [0, 1]. Please set format_box to True and provide image_height and image_width to normalize"
|
138
|
-
)
|
139
|
-
region = resources_pb2.RegionInfo(bounding_box=resources_pb2.BoundingBox(
|
140
|
-
top_row=bbox[0], # y_min
|
141
|
-
left_col=bbox[1], # x_min
|
142
|
-
bottom_row=bbox[2], # y_max
|
143
|
-
right_col=bbox[3], # x_max
|
144
|
-
))
|
145
|
-
data = resources_pb2.Data(concepts=resources_pb2.Concept(id=concept, value=score))
|
146
|
-
regions.append(resources_pb2.Region(region_info=region, data=data))
|
147
|
-
|
148
|
-
self._proto.data.regions = regions
|
149
|
-
|
150
|
-
# Concepts
|
151
|
-
@property
|
152
|
-
def concepts(self) -> Dict[str, float]:
|
153
|
-
con_scores = {}
|
154
|
-
for each in self.proto.data.concepts:
|
155
|
-
con_scores.update({each.id: each.value})
|
156
|
-
return con_scores
|
157
|
-
|
158
|
-
def set_concepts(self, concept_score_pairs: Dict[str, float]):
|
159
|
-
concepts = []
|
160
|
-
for concept, score in concept_score_pairs.items():
|
161
|
-
con_score = resources_pb2.Concept(id=concept, name=concept, value=score)
|
162
|
-
concepts.append(con_score)
|
163
|
-
if concepts:
|
164
|
-
self._proto.data.ClearField("concepts")
|
165
|
-
for each in concepts:
|
166
|
-
self._proto.data.concepts.append(each)
|
167
|
-
|
168
|
-
# Embeddings
|
169
|
-
@property
|
170
|
-
def embeddings(self) -> List[List[float]]:
|
171
|
-
return [each.vector for each in self.proto.data.embeddings]
|
172
|
-
|
173
|
-
def set_embeddings(self, list_vectors: List[List[float]]):
|
174
|
-
if list_vectors[0]:
|
175
|
-
self._proto.data.ClearField("embeddings")
|
176
|
-
for vec in list_vectors:
|
177
|
-
self._proto.data.embeddings.append(
|
178
|
-
resources_pb2.Embedding(vector=vec, num_dimensions=len(vec)))
|
179
|
-
|
180
|
-
# ---------------- End get/setters ---------------- #
|
181
|
-
|
182
|
-
# Constructors
|
183
|
-
@classmethod
|
184
|
-
def from_proto(cls, proto):
|
185
|
-
clss = cls(proto=proto)
|
186
|
-
return clss
|
187
|
-
|
188
|
-
@classmethod
|
189
|
-
def from_data(
|
190
|
-
cls,
|
191
|
-
status_code: int = status_code_pb2.SUCCESS,
|
192
|
-
status_description: str = "",
|
193
|
-
text: str = None,
|
194
|
-
image: Union[Image.Image, np.ndarray] = None,
|
195
|
-
audio: bytes = None,
|
196
|
-
boxes: dict = None,
|
197
|
-
concepts: Dict[str, float] = {},
|
198
|
-
embeddings: List[List[float]] = [],
|
199
|
-
) -> 'OutputDataHandler':
|
200
|
-
clss = cls(proto=resources_pb2.Output())
|
201
|
-
if isinstance(image, Image.Image) or isinstance(image, np.ndarray):
|
202
|
-
clss.set_image(image)
|
203
|
-
if text:
|
204
|
-
clss.set_text(text)
|
205
|
-
if audio:
|
206
|
-
clss.set_audio(audio)
|
207
|
-
if boxes:
|
208
|
-
clss.set_bboxes(**boxes)
|
209
|
-
if concepts:
|
210
|
-
clss.set_concepts(concepts)
|
211
|
-
if embeddings:
|
212
|
-
clss.set_embeddings(embeddings)
|
213
|
-
|
214
|
-
clss.set_status(code=status_code, description=status_description)
|
215
|
-
return clss
|
216
|
-
|
217
|
-
|
218
|
-
class InputDataHandler(BaseDataHandler):
|
219
|
-
|
220
|
-
def __init__(self,
|
221
|
-
proto: resources_pb2.Input = resources_pb2.Input(),
|
222
|
-
auth: ClarifaiAuthHelper = None):
|
223
|
-
super().__init__(proto=proto, auth=auth)
|
224
|
-
|
225
|
-
|
226
|
-
class OutputDataHandler(BaseDataHandler):
|
227
|
-
|
228
|
-
def __init__(self,
|
229
|
-
proto: resources_pb2.Output = resources_pb2.Output(),
|
230
|
-
auth: ClarifaiAuthHelper = None):
|
231
|
-
super().__init__(proto=proto, auth=auth)
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
clarifai/utils/config.py~
DELETED
@@ -1,145 +0,0 @@
|
|
1
|
-
import click
|
2
|
-
import sys
|
3
|
-
import os
|
4
|
-
import typing as t
|
5
|
-
import yaml
|
6
|
-
|
7
|
-
from dataclasses import dataclass, field
|
8
|
-
from clarifai.utils.cli import AliasedGroup, TableFormatter, load_command_modules, load_command_modules
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
@dataclass
|
13
|
-
class AccessToken():
|
14
|
-
type: str
|
15
|
-
value: str
|
16
|
-
|
17
|
-
def __str__(self):
|
18
|
-
return f'{self.type}:{self.value}' if self.type == 'env' else '********'
|
19
|
-
|
20
|
-
def to_serializable_dict(self):
|
21
|
-
return self.__dict__
|
22
|
-
|
23
|
-
@classmethod
|
24
|
-
def from_serializable_dict(cls, _dict):
|
25
|
-
return cls(**_dict)
|
26
|
-
|
27
|
-
# Dictionary protocol methods:
|
28
|
-
|
29
|
-
def __getitem__(self, key: str) -> t.Any:
|
30
|
-
if key == 'type':
|
31
|
-
return self.type
|
32
|
-
elif key == 'value':
|
33
|
-
return self.value
|
34
|
-
else:
|
35
|
-
raise KeyError(key)
|
36
|
-
|
37
|
-
def __setitem__(self, key: str, value: t.Any) -> None:
|
38
|
-
if key == 'type':
|
39
|
-
self.type = value
|
40
|
-
elif key == 'value':
|
41
|
-
self.value = value
|
42
|
-
else:
|
43
|
-
raise KeyError(key)
|
44
|
-
|
45
|
-
def __delitem__(self, key: str) -> None:
|
46
|
-
raise TypeError("Cannot delete attributes from AccessToken")
|
47
|
-
|
48
|
-
def __iter__(self):
|
49
|
-
return iter(['type', 'value'])
|
50
|
-
|
51
|
-
def __len__(self) -> int:
|
52
|
-
return 2
|
53
|
-
|
54
|
-
def __contains__(self, key: str) -> bool:
|
55
|
-
return key in ['type', 'value']
|
56
|
-
|
57
|
-
def keys(self):
|
58
|
-
return ['type', 'value']
|
59
|
-
|
60
|
-
def values(self):
|
61
|
-
return [self.type, self.value]
|
62
|
-
|
63
|
-
def items(self):
|
64
|
-
return [('type', self.type), ('value', self.value)]
|
65
|
-
|
66
|
-
def get(self, key: str, default: t.Any = None) -> t.Any:
|
67
|
-
try:
|
68
|
-
return self[key]
|
69
|
-
except KeyError:
|
70
|
-
return default
|
71
|
-
|
72
|
-
|
73
|
-
@dataclass
|
74
|
-
class Context():
|
75
|
-
name: str
|
76
|
-
user_id: str
|
77
|
-
base_url: str
|
78
|
-
access_token: AccessToken = field(default_factory=lambda: AccessToken('env', 'CLARIFAI_PAT'))
|
79
|
-
env: t.Dict[str, str] = field(default_factory=dict)
|
80
|
-
|
81
|
-
pat: str = None
|
82
|
-
|
83
|
-
def _resolve_pat(self) -> str:
|
84
|
-
if self.access_token['type'].lower() == 'env':
|
85
|
-
return os.getenv(self.access_token['value'], '')
|
86
|
-
elif self.access_token['type'].lower() == 'raw':
|
87
|
-
return self.access_token['value']
|
88
|
-
else:
|
89
|
-
raise Exception('Only "env" and "raw" methods are supported')
|
90
|
-
|
91
|
-
def __post_init__(self):
|
92
|
-
self.pat = self._resolve_pat()
|
93
|
-
self.access_token = AccessToken(**self.access_token)
|
94
|
-
|
95
|
-
def to_serializable_dict(self):
|
96
|
-
result = {
|
97
|
-
'name': self.name,
|
98
|
-
'user_id': self.user_id,
|
99
|
-
'base_url': self.base_url,
|
100
|
-
'access_token': self.access_token.to_serializable_dict(),
|
101
|
-
}
|
102
|
-
if self.env:
|
103
|
-
result['env'] = self.env
|
104
|
-
return result
|
105
|
-
|
106
|
-
|
107
|
-
@dataclass
|
108
|
-
class Config():
|
109
|
-
current_context: str
|
110
|
-
filename: str
|
111
|
-
contexts: dict[str, Context] = field(default_factory=dict)
|
112
|
-
|
113
|
-
def __post_init__(self):
|
114
|
-
for k, v in self.contexts.items():
|
115
|
-
if 'name' not in v:
|
116
|
-
v['name'] = k
|
117
|
-
self.contexts = {k: Context(**v) for k, v in self.contexts.items()}
|
118
|
-
|
119
|
-
@classmethod
|
120
|
-
def from_yaml(cls, filename: str = DEFAULT_CONFIG):
|
121
|
-
with open(filename, 'r') as f:
|
122
|
-
cfg = yaml.safe_load(f)
|
123
|
-
return cls(**cfg, filename=filename)
|
124
|
-
|
125
|
-
def to_dict(self):
|
126
|
-
return {
|
127
|
-
'current_context': self.current_context,
|
128
|
-
'contexts': {k: v.to_serializable_dict()
|
129
|
-
for k, v in self.contexts.items()}
|
130
|
-
}
|
131
|
-
|
132
|
-
def to_yaml(self, filename: str = None):
|
133
|
-
if filename is None:
|
134
|
-
filename = self.filename
|
135
|
-
dir = os.path.dirname(filename)
|
136
|
-
if len(dir):
|
137
|
-
os.makedirs(dir, exist_ok=True)
|
138
|
-
_dict = self.to_dict()
|
139
|
-
for k, v in _dict['contexts'].items():
|
140
|
-
v.pop('name', None)
|
141
|
-
with open(filename, 'w') as f:
|
142
|
-
yaml.safe_dump(_dict, f)
|
143
|
-
|
144
|
-
def current(self) -> Context:
|
145
|
-
return self.contexts[self.current_context]
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|