clarifai 10.8.4__py3-none-any.whl → 10.8.5__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/client/dataset.py +9 -3
- clarifai/constants/dataset.py +1 -1
- clarifai/datasets/upload/base.py +6 -3
- clarifai/datasets/upload/features.py +10 -0
- clarifai/datasets/upload/image.py +22 -13
- clarifai/datasets/upload/multimodal.py +70 -0
- clarifai/datasets/upload/text.py +8 -5
- clarifai/utils/misc.py +6 -0
- {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/METADATA +2 -1
- {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/RECORD +15 -58
- clarifai/models/model_serving/README.md +0 -158
- clarifai/models/model_serving/__init__.py +0 -14
- clarifai/models/model_serving/cli/__init__.py +0 -12
- clarifai/models/model_serving/cli/_utils.py +0 -53
- clarifai/models/model_serving/cli/base.py +0 -14
- clarifai/models/model_serving/cli/build.py +0 -79
- clarifai/models/model_serving/cli/clarifai_clis.py +0 -33
- clarifai/models/model_serving/cli/create.py +0 -171
- clarifai/models/model_serving/cli/example_cli.py +0 -34
- clarifai/models/model_serving/cli/login.py +0 -26
- clarifai/models/model_serving/cli/upload.py +0 -183
- clarifai/models/model_serving/constants.py +0 -21
- clarifai/models/model_serving/docs/cli.md +0 -161
- clarifai/models/model_serving/docs/concepts.md +0 -229
- clarifai/models/model_serving/docs/dependencies.md +0 -11
- clarifai/models/model_serving/docs/inference_parameters.md +0 -139
- clarifai/models/model_serving/docs/model_types.md +0 -19
- clarifai/models/model_serving/model_config/__init__.py +0 -16
- clarifai/models/model_serving/model_config/base.py +0 -369
- clarifai/models/model_serving/model_config/config.py +0 -312
- clarifai/models/model_serving/model_config/inference_parameter.py +0 -129
- clarifai/models/model_serving/model_config/model_types_config/multimodal-embedder.yaml +0 -25
- clarifai/models/model_serving/model_config/model_types_config/text-classifier.yaml +0 -19
- clarifai/models/model_serving/model_config/model_types_config/text-embedder.yaml +0 -20
- clarifai/models/model_serving/model_config/model_types_config/text-to-image.yaml +0 -19
- clarifai/models/model_serving/model_config/model_types_config/text-to-text.yaml +0 -19
- clarifai/models/model_serving/model_config/model_types_config/visual-classifier.yaml +0 -22
- clarifai/models/model_serving/model_config/model_types_config/visual-detector.yaml +0 -32
- clarifai/models/model_serving/model_config/model_types_config/visual-embedder.yaml +0 -19
- clarifai/models/model_serving/model_config/model_types_config/visual-segmenter.yaml +0 -19
- clarifai/models/model_serving/model_config/output.py +0 -133
- clarifai/models/model_serving/model_config/triton/__init__.py +0 -14
- clarifai/models/model_serving/model_config/triton/serializer.py +0 -136
- clarifai/models/model_serving/model_config/triton/triton_config.py +0 -182
- clarifai/models/model_serving/model_config/triton/wrappers.py +0 -281
- clarifai/models/model_serving/repo_build/__init__.py +0 -14
- clarifai/models/model_serving/repo_build/build.py +0 -198
- clarifai/models/model_serving/repo_build/static_files/_requirements.txt +0 -2
- clarifai/models/model_serving/repo_build/static_files/base_test.py +0 -169
- clarifai/models/model_serving/repo_build/static_files/inference.py +0 -26
- clarifai/models/model_serving/repo_build/static_files/sample_clarifai_config.yaml +0 -25
- clarifai/models/model_serving/repo_build/static_files/test.py +0 -40
- clarifai/models/model_serving/repo_build/static_files/triton/model.py +0 -75
- clarifai/models/model_serving/utils.py +0 -31
- {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/LICENSE +0 -0
- {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/WHEEL +0 -0
- {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/entry_points.txt +0 -0
- {clarifai-10.8.4.dist-info → clarifai-10.8.5.dist-info}/top_level.txt +0 -0
@@ -1,53 +0,0 @@
|
|
1
|
-
from __future__ import annotations # isort: skip
|
2
|
-
import os
|
3
|
-
import shutil
|
4
|
-
import subprocess
|
5
|
-
from typing import Dict, Union
|
6
|
-
|
7
|
-
from ..constants import (CLARIFAI_EXAMPLES_REPO, CLARIFAI_EXAMPLES_REPO_PATH,
|
8
|
-
MODEL_UPLOAD_EXAMPLE_FOLDER)
|
9
|
-
|
10
|
-
|
11
|
-
def download_examples_repo(forced_download: bool = False):
|
12
|
-
|
13
|
-
def _pull():
|
14
|
-
subprocess.run(f"git clone {CLARIFAI_EXAMPLES_REPO} {CLARIFAI_EXAMPLES_REPO_PATH}", shell=True)
|
15
|
-
|
16
|
-
if not os.path.isdir(CLARIFAI_EXAMPLES_REPO_PATH):
|
17
|
-
print(f"Download examples to {CLARIFAI_EXAMPLES_REPO_PATH}")
|
18
|
-
_pull()
|
19
|
-
else:
|
20
|
-
if forced_download:
|
21
|
-
|
22
|
-
def _rm_dir_readonly(func, path, _):
|
23
|
-
import stat
|
24
|
-
os.chmod(path, stat.S_IWRITE)
|
25
|
-
func(path)
|
26
|
-
|
27
|
-
print("Removing old examples...")
|
28
|
-
shutil.rmtree(CLARIFAI_EXAMPLES_REPO_PATH, onerror=_rm_dir_readonly)
|
29
|
-
_pull()
|
30
|
-
|
31
|
-
|
32
|
-
def list_model_upload_examples(
|
33
|
-
forced_download: bool = False) -> Dict[str, tuple[str, Union[str, None]]]:
|
34
|
-
download_examples_repo(forced_download)
|
35
|
-
model_upload_folder = MODEL_UPLOAD_EXAMPLE_FOLDER
|
36
|
-
model_upload_path = os.path.join(CLARIFAI_EXAMPLES_REPO_PATH, model_upload_folder)
|
37
|
-
examples = {}
|
38
|
-
for model_type_ex in os.listdir(model_upload_path):
|
39
|
-
_folder = os.path.join(model_upload_path, model_type_ex)
|
40
|
-
if os.path.isdir(_folder):
|
41
|
-
_walk = list(os.walk(_folder))
|
42
|
-
if len(_walk) > 0:
|
43
|
-
_, model_names, _files = _walk[0]
|
44
|
-
readme = [item for item in _files if "readme" in item.lower()]
|
45
|
-
for name in model_names:
|
46
|
-
examples.update({
|
47
|
-
f"{model_type_ex}/{name}": [
|
48
|
-
os.path.join(_folder, name),
|
49
|
-
os.path.join(_folder, readme[0]) or None
|
50
|
-
]
|
51
|
-
})
|
52
|
-
|
53
|
-
return examples
|
@@ -1,14 +0,0 @@
|
|
1
|
-
from abc import ABC, abstractmethod
|
2
|
-
from argparse import _SubParsersAction
|
3
|
-
|
4
|
-
|
5
|
-
class BaseClarifaiCli(ABC):
|
6
|
-
|
7
|
-
@staticmethod
|
8
|
-
@abstractmethod
|
9
|
-
def register(parser: _SubParsersAction):
|
10
|
-
raise NotImplementedError()
|
11
|
-
|
12
|
-
@abstractmethod
|
13
|
-
def run(self):
|
14
|
-
raise NotImplementedError()
|
@@ -1,79 +0,0 @@
|
|
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
|
-
"""Commandline interface for model upload utils."""
|
14
|
-
import argparse
|
15
|
-
import os
|
16
|
-
import subprocess
|
17
|
-
|
18
|
-
from ..repo_build import RepositoryBuilder
|
19
|
-
from .base import BaseClarifaiCli
|
20
|
-
|
21
|
-
|
22
|
-
class BuildCli(BaseClarifaiCli):
|
23
|
-
|
24
|
-
@staticmethod
|
25
|
-
def register(parser: argparse._SubParsersAction):
|
26
|
-
parser = parser.add_parser("build", help="Build clarifai model for uploading")
|
27
|
-
sub_parser = parser.add_subparsers()
|
28
|
-
|
29
|
-
BuildModelSubCli.register(sub_parser)
|
30
|
-
|
31
|
-
parser.set_defaults(func=BuildCli)
|
32
|
-
|
33
|
-
|
34
|
-
class BuildModelSubCli(BaseClarifaiCli):
|
35
|
-
|
36
|
-
@staticmethod
|
37
|
-
def register(parser: argparse._SubParsersAction):
|
38
|
-
sub_parser = parser.add_parser("model", help="Build Clarifai model")
|
39
|
-
sub_parser.add_argument(
|
40
|
-
"path",
|
41
|
-
type=str,
|
42
|
-
nargs='?',
|
43
|
-
help="Path to working directory, default is current directory",
|
44
|
-
default=".")
|
45
|
-
sub_parser.add_argument(
|
46
|
-
"--out-path", type=str, required=False, help="Output path of built model", default=None)
|
47
|
-
sub_parser.add_argument(
|
48
|
-
"--name",
|
49
|
-
type=str,
|
50
|
-
required=False,
|
51
|
-
help="Name of built file, default is `clarifai_model_id` in config if set or `model`",
|
52
|
-
default=None)
|
53
|
-
sub_parser.add_argument(
|
54
|
-
"--no-test",
|
55
|
-
action="store_true",
|
56
|
-
help="Trigger this flag to skip testing before uploading")
|
57
|
-
sub_parser.set_defaults(func=BuildModelSubCli)
|
58
|
-
|
59
|
-
def __init__(self, args: argparse.Namespace) -> None:
|
60
|
-
self.path = args.path
|
61
|
-
self.no_test = args.no_test
|
62
|
-
self.test_path = os.path.join(self.path, "test.py")
|
63
|
-
self.output_path = args.out_path or self.path
|
64
|
-
self.serving_backend = "triton"
|
65
|
-
self.name = args.name
|
66
|
-
|
67
|
-
def run(self):
|
68
|
-
|
69
|
-
# Run test before uploading
|
70
|
-
if not self.no_test:
|
71
|
-
assert os.path.exists(
|
72
|
-
self.test_path), FileNotFoundError(f"Could not find `test.py` in {self.path}")
|
73
|
-
result = subprocess.run(f"pytest -s --log-level=INFO {self.test_path}", shell=True)
|
74
|
-
assert result.returncode == 0, "Test has failed. Please make sure no error exists in your code."
|
75
|
-
|
76
|
-
# build
|
77
|
-
print("Start building...")
|
78
|
-
RepositoryBuilder.build(
|
79
|
-
self.path, backend=self.serving_backend, output_dir=self.output_path, name=self.name)
|
@@ -1,33 +0,0 @@
|
|
1
|
-
from argparse import ArgumentParser
|
2
|
-
|
3
|
-
from .build import BuildCli
|
4
|
-
from .create import CreateCli
|
5
|
-
from .example_cli import ExampleCli
|
6
|
-
from .login import LoginCli
|
7
|
-
from .upload import UploadCli
|
8
|
-
|
9
|
-
|
10
|
-
def main():
|
11
|
-
|
12
|
-
parser = ArgumentParser("clarifai")
|
13
|
-
cmd_parser = parser.add_subparsers(help="Clarifai cli helpers")
|
14
|
-
|
15
|
-
UploadCli.register(cmd_parser)
|
16
|
-
CreateCli.register(cmd_parser)
|
17
|
-
LoginCli.register(cmd_parser)
|
18
|
-
ExampleCli.register(cmd_parser)
|
19
|
-
BuildCli.register(cmd_parser)
|
20
|
-
|
21
|
-
args = parser.parse_args()
|
22
|
-
|
23
|
-
if not hasattr(args, "func"):
|
24
|
-
parser.print_help()
|
25
|
-
exit(1)
|
26
|
-
|
27
|
-
# Run
|
28
|
-
service = args.func(args)
|
29
|
-
service.run()
|
30
|
-
|
31
|
-
|
32
|
-
if __name__ == "__main__":
|
33
|
-
main()
|
@@ -1,171 +0,0 @@
|
|
1
|
-
import os
|
2
|
-
import shutil
|
3
|
-
from argparse import Namespace, _SubParsersAction
|
4
|
-
from typing import List
|
5
|
-
|
6
|
-
from InquirerPy import prompt
|
7
|
-
|
8
|
-
from ..model_config import MODEL_TYPES
|
9
|
-
from ..repo_build import RepositoryBuilder
|
10
|
-
from ._utils import list_model_upload_examples
|
11
|
-
from .base import BaseClarifaiCli
|
12
|
-
|
13
|
-
|
14
|
-
class CreateCli(BaseClarifaiCli):
|
15
|
-
|
16
|
-
@staticmethod
|
17
|
-
def register(parser: _SubParsersAction):
|
18
|
-
creator_parser = parser.add_parser("create", help="Create component of Clarifai platform")
|
19
|
-
sub_creator_parser = creator_parser.add_subparsers()
|
20
|
-
|
21
|
-
SubCreateModelCli.register(sub_creator_parser)
|
22
|
-
|
23
|
-
creator_parser.set_defaults(func=CreateCli)
|
24
|
-
|
25
|
-
|
26
|
-
class SubCreateModelCli(BaseClarifaiCli):
|
27
|
-
|
28
|
-
@staticmethod
|
29
|
-
def register(parser: _SubParsersAction):
|
30
|
-
model_parser = parser.add_parser("model")
|
31
|
-
model_parser.add_argument(
|
32
|
-
"--working-dir",
|
33
|
-
type=str,
|
34
|
-
required=True,
|
35
|
-
help="Path to your working dir. Create new dir if it does not exist")
|
36
|
-
model_parser.add_argument(
|
37
|
-
"--from-example",
|
38
|
-
required=False,
|
39
|
-
action="store_true",
|
40
|
-
help="Create repository from example")
|
41
|
-
model_parser.add_argument(
|
42
|
-
"--example-id",
|
43
|
-
required=False,
|
44
|
-
type=str,
|
45
|
-
help="Example id, run `clarifai example list` to list of examples")
|
46
|
-
|
47
|
-
model_parser.add_argument(
|
48
|
-
"--type",
|
49
|
-
type=str,
|
50
|
-
choices=MODEL_TYPES,
|
51
|
-
required=False,
|
52
|
-
help="Clarifai supported model types.")
|
53
|
-
model_parser.add_argument(
|
54
|
-
"--image-shape",
|
55
|
-
nargs='+',
|
56
|
-
type=int,
|
57
|
-
required=False,
|
58
|
-
help="H W dims for models with an image input type. H and W each have a max value of 1024",
|
59
|
-
default=[-1, -1])
|
60
|
-
model_parser.add_argument(
|
61
|
-
"--max-bs", type=int, default=1, required=False, help="Max batch size")
|
62
|
-
|
63
|
-
model_parser.add_argument(
|
64
|
-
"--overwrite", action="store_true", help="Overwrite working-dir if exists")
|
65
|
-
|
66
|
-
model_parser.set_defaults(func=SubCreateModelCli)
|
67
|
-
|
68
|
-
def __init__(self, args: Namespace) -> None:
|
69
|
-
self.working_dir: str = args.working_dir
|
70
|
-
self.from_example = args.from_example
|
71
|
-
self.example_id = args.example_id
|
72
|
-
self.overwrite = args.overwrite
|
73
|
-
|
74
|
-
if os.path.exists(self.working_dir):
|
75
|
-
if self.overwrite:
|
76
|
-
print(f"Overwrite {self.working_dir}")
|
77
|
-
else:
|
78
|
-
raise FileExistsError(
|
79
|
-
f"{self.working_dir} exists. If you want to overwrite it, please set `--overwrite` flag"
|
80
|
-
)
|
81
|
-
|
82
|
-
# prevent wrong args when creating from example
|
83
|
-
if not self.from_example:
|
84
|
-
self.image_shape: List[int] = args.image_shape
|
85
|
-
|
86
|
-
self.type: str = args.type
|
87
|
-
self.max_bs: int = args.max_bs
|
88
|
-
|
89
|
-
else:
|
90
|
-
if not self.example_id:
|
91
|
-
questions = [
|
92
|
-
{
|
93
|
-
"type": "list",
|
94
|
-
"message": "Select an example:",
|
95
|
-
"choices": list_model_upload_examples(),
|
96
|
-
},
|
97
|
-
]
|
98
|
-
result = prompt(questions)
|
99
|
-
self.example_id = result[0]
|
100
|
-
|
101
|
-
else:
|
102
|
-
available_examples = list(list_model_upload_examples().keys())
|
103
|
-
assert self.example_id in available_examples, f"Available examples are: {available_examples}, got {self.example_id}."
|
104
|
-
|
105
|
-
def run(self):
|
106
|
-
if self.from_example:
|
107
|
-
os.makedirs(self.working_dir, exist_ok=True)
|
108
|
-
model_repo, readme = list_model_upload_examples()[self.example_id]
|
109
|
-
shutil.copytree(model_repo, self.working_dir, dirs_exist_ok=True)
|
110
|
-
if readme:
|
111
|
-
shutil.copy(readme, os.path.join(self.working_dir, "readme.md"))
|
112
|
-
|
113
|
-
else:
|
114
|
-
RepositoryBuilder.init_repository(
|
115
|
-
self.type,
|
116
|
-
self.working_dir,
|
117
|
-
backend="triton",
|
118
|
-
max_batch_size=self.max_bs,
|
119
|
-
image_shape=self.image_shape)
|
120
|
-
|
121
|
-
from itertools import islice
|
122
|
-
from pathlib import Path
|
123
|
-
|
124
|
-
def tree(dir_path: Path,
|
125
|
-
level: int = -1,
|
126
|
-
limit_to_directories: bool = False,
|
127
|
-
length_limit: int = 1000):
|
128
|
-
# prefix components:
|
129
|
-
space = ' '
|
130
|
-
branch = '│ '
|
131
|
-
# pointers:
|
132
|
-
tee = '├── '
|
133
|
-
last = '└── '
|
134
|
-
"""Given a directory Path object print a visual tree structure"""
|
135
|
-
dir_path = Path(dir_path) # accept string coerceable to Path
|
136
|
-
files = 0
|
137
|
-
directories = 0
|
138
|
-
|
139
|
-
def inner(dir_path: Path, prefix: str = '', level=-1):
|
140
|
-
nonlocal files, directories
|
141
|
-
if not level:
|
142
|
-
return # 0, stop iterating
|
143
|
-
if limit_to_directories:
|
144
|
-
contents = [d for d in dir_path.iterdir() if d.is_dir()]
|
145
|
-
else:
|
146
|
-
contents = list(dir_path.iterdir())
|
147
|
-
pointers = [tee] * (len(contents) - 1) + [last]
|
148
|
-
for pointer, path in zip(pointers, contents):
|
149
|
-
if path.is_dir():
|
150
|
-
yield prefix + pointer + path.name
|
151
|
-
directories += 1
|
152
|
-
extension = branch if pointer == tee else space
|
153
|
-
yield from inner(path, prefix=prefix + extension, level=level - 1)
|
154
|
-
elif not limit_to_directories:
|
155
|
-
yield prefix + pointer + path.name
|
156
|
-
files += 1
|
157
|
-
|
158
|
-
print(dir_path.name)
|
159
|
-
iterator = inner(dir_path, level=level)
|
160
|
-
for line in islice(iterator, length_limit):
|
161
|
-
print(line)
|
162
|
-
if next(iterator, None):
|
163
|
-
print(f'... length_limit, {length_limit}, reached, counted:')
|
164
|
-
print(f'\n{directories} directories' + (f', {files} files' if files else ''))
|
165
|
-
|
166
|
-
print("-" * 75)
|
167
|
-
print(f"* Created repository at: {self.working_dir}")
|
168
|
-
tree(self.working_dir)
|
169
|
-
print()
|
170
|
-
print("* Please make sure your code is tested using `test.py` before uploading")
|
171
|
-
print("-" * 75)
|
@@ -1,34 +0,0 @@
|
|
1
|
-
from argparse import Namespace, _SubParsersAction
|
2
|
-
|
3
|
-
from ._utils import list_model_upload_examples
|
4
|
-
from .base import BaseClarifaiCli
|
5
|
-
|
6
|
-
|
7
|
-
class ExampleCli(BaseClarifaiCli):
|
8
|
-
|
9
|
-
@staticmethod
|
10
|
-
def register(parser: _SubParsersAction):
|
11
|
-
creator_parser = parser.add_parser("example", help="Download/List examples of model upload")
|
12
|
-
sub_creator_parser = creator_parser.add_subparsers()
|
13
|
-
|
14
|
-
SubListExampleCli.register(sub_creator_parser)
|
15
|
-
|
16
|
-
creator_parser.set_defaults(func=ExampleCli)
|
17
|
-
|
18
|
-
|
19
|
-
class SubListExampleCli(BaseClarifaiCli):
|
20
|
-
|
21
|
-
@staticmethod
|
22
|
-
def register(parser: _SubParsersAction):
|
23
|
-
_parser = parser.add_parser("list")
|
24
|
-
_parser.add_argument("--force-download", action="store_true", help="Force download examples")
|
25
|
-
_parser.set_defaults(func=SubListExampleCli)
|
26
|
-
|
27
|
-
def __init__(self, args: Namespace) -> None:
|
28
|
-
self.force_download = args.force_download
|
29
|
-
|
30
|
-
def run(self):
|
31
|
-
_list = list_model_upload_examples(self.force_download)
|
32
|
-
print(f"Found {len(_list)} examples")
|
33
|
-
for each in _list:
|
34
|
-
print(f" * {each}")
|
@@ -1,26 +0,0 @@
|
|
1
|
-
import argparse
|
2
|
-
|
3
|
-
from clarifai.models.model_serving.constants import CLARIFAI_PAT_PATH
|
4
|
-
from ..utils import _persist_pat
|
5
|
-
from .base import BaseClarifaiCli
|
6
|
-
|
7
|
-
|
8
|
-
class LoginCli(BaseClarifaiCli):
|
9
|
-
|
10
|
-
@staticmethod
|
11
|
-
def register(parser: argparse._SubParsersAction):
|
12
|
-
upload_parser = parser.add_parser("login", help="Login to Clarifai and save PAT locally")
|
13
|
-
upload_parser.set_defaults(func=LoginCli)
|
14
|
-
|
15
|
-
def __init__(self, args: argparse.Namespace) -> None:
|
16
|
-
pass
|
17
|
-
|
18
|
-
def _parse_config(self):
|
19
|
-
# do something with self.config_path
|
20
|
-
raise NotImplementedError()
|
21
|
-
|
22
|
-
def run(self):
|
23
|
-
msg = "Get your PAT from https://clarifai.com/settings/security and pass it here: "
|
24
|
-
_pat = input(msg)
|
25
|
-
_persist_pat(_pat)
|
26
|
-
print(f"Your PAT is saved at {CLARIFAI_PAT_PATH}")
|
@@ -1,183 +0,0 @@
|
|
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
|
-
"""Commandline interface for model upload utils."""
|
14
|
-
import argparse
|
15
|
-
import os
|
16
|
-
import subprocess
|
17
|
-
|
18
|
-
from clarifai.models.model_serving.model_config import get_model_config, load_user_config
|
19
|
-
from clarifai.models.model_serving.model_config.inference_parameter import InferParamManager
|
20
|
-
|
21
|
-
from ..constants import BUILT_MODEL_EXT
|
22
|
-
from ..utils import login
|
23
|
-
from .base import BaseClarifaiCli
|
24
|
-
|
25
|
-
|
26
|
-
class UploadCli(BaseClarifaiCli):
|
27
|
-
|
28
|
-
@staticmethod
|
29
|
-
def register(parser: argparse._SubParsersAction):
|
30
|
-
creator_parser = parser.add_parser("upload", help="Upload component to Clarifai platform")
|
31
|
-
sub_creator_parser = creator_parser.add_subparsers()
|
32
|
-
|
33
|
-
UploadModelSubCli.register(sub_creator_parser)
|
34
|
-
|
35
|
-
creator_parser.set_defaults(func=UploadCli)
|
36
|
-
|
37
|
-
|
38
|
-
class UploadModelSubCli(BaseClarifaiCli):
|
39
|
-
|
40
|
-
@staticmethod
|
41
|
-
def register(parser: argparse._SubParsersAction):
|
42
|
-
upload_parser = parser.add_parser("model", help="Upload Clarifai model")
|
43
|
-
upload_parser.add_argument(
|
44
|
-
"path",
|
45
|
-
type=str,
|
46
|
-
nargs='?',
|
47
|
-
help=
|
48
|
-
"Path to working dir to get clarifai_config.yaml or path to yaml. Default is current directory",
|
49
|
-
default=".")
|
50
|
-
upload_parser.add_argument(
|
51
|
-
"--url", type=str, required=False, help="Direct download url of zip file", default=None)
|
52
|
-
upload_parser.add_argument(
|
53
|
-
"--file", type=str, required=False, help="Local built file", default=None)
|
54
|
-
upload_parser.add_argument("--id", type=str, required=False, help="Model ID")
|
55
|
-
upload_parser.add_argument(
|
56
|
-
"--user-app",
|
57
|
-
type=str,
|
58
|
-
required=False,
|
59
|
-
help="User ID and App ID separated by '/', e.g., <user_id>/<app_id>")
|
60
|
-
upload_parser.add_argument(
|
61
|
-
"--no-test",
|
62
|
-
action="store_true",
|
63
|
-
help="Trigger this flag to skip testing before uploading")
|
64
|
-
upload_parser.add_argument(
|
65
|
-
"--no-resume",
|
66
|
-
action="store_true",
|
67
|
-
help="Trigger this flag to not resume uploading local file")
|
68
|
-
upload_parser.add_argument(
|
69
|
-
"--update-version",
|
70
|
-
action="store_true",
|
71
|
-
required=False,
|
72
|
-
help="Update exist model with new version")
|
73
|
-
|
74
|
-
upload_parser.set_defaults(func=UploadModelSubCli)
|
75
|
-
|
76
|
-
def __init__(self, args: argparse.Namespace) -> None:
|
77
|
-
self.no_test = args.no_test
|
78
|
-
self.no_resume = args.no_resume
|
79
|
-
|
80
|
-
working_dir_or_config = args.path
|
81
|
-
# if input a config file, then not running test
|
82
|
-
if working_dir_or_config.endswith(".yaml"):
|
83
|
-
# to folder
|
84
|
-
working_dir_or_config = os.path.split(working_dir_or_config)[0]
|
85
|
-
config_yaml_path = working_dir_or_config
|
86
|
-
self.test_path = None
|
87
|
-
self.no_test = True
|
88
|
-
# if it is a directory - working dir then it must contain config and test
|
89
|
-
else:
|
90
|
-
config_yaml_path = os.path.join(working_dir_or_config, "clarifai_config.yaml")
|
91
|
-
self.test_path = os.path.join(working_dir_or_config, "test.py")
|
92
|
-
|
93
|
-
assert os.path.exists(config_yaml_path), FileNotFoundError(
|
94
|
-
f"`{config_yaml_path}` does not exist")
|
95
|
-
self.config = load_user_config(cfg_path=config_yaml_path)
|
96
|
-
|
97
|
-
self.file = args.file
|
98
|
-
self.url = args.url
|
99
|
-
if self.file:
|
100
|
-
assert not self.url, ValueError("Expected either file or url, not both.")
|
101
|
-
assert os.path.exists(self.file), FileNotFoundError
|
102
|
-
elif self.url:
|
103
|
-
if len(self.url.split(":")) == 1:
|
104
|
-
# if URL has no scheme, default to https
|
105
|
-
self.url = f"https://{self.url}"
|
106
|
-
assert self.url.startswith("http") or self.url.startswith("https") or self.url.startswith(
|
107
|
-
"s3"
|
108
|
-
), f"Invalid URL scheme, supported schemes are 'http', 'https', or 's3'. Got {self.url}"
|
109
|
-
self.file = None
|
110
|
-
else:
|
111
|
-
for _fname in os.listdir(working_dir_or_config):
|
112
|
-
if _fname.endswith(BUILT_MODEL_EXT):
|
113
|
-
self.file = os.path.join(working_dir_or_config, _fname)
|
114
|
-
break
|
115
|
-
assert self.file, ValueError(
|
116
|
-
f"Not using url/file but also not found built file with extension {BUILT_MODEL_EXT}")
|
117
|
-
|
118
|
-
self.user_id, self.app_id = "", ""
|
119
|
-
user_app = args.user_app
|
120
|
-
self.url: str = args.url
|
121
|
-
self.update_version = args.update_version
|
122
|
-
|
123
|
-
clarifai_cfg = self.config.clarifai_model
|
124
|
-
self.url: str = args.url
|
125
|
-
self.id = args.id or clarifai_cfg.clarifai_model_id
|
126
|
-
self.type = clarifai_cfg.type
|
127
|
-
self.desc = clarifai_cfg.description
|
128
|
-
self.infer_param = clarifai_cfg.inference_parameters
|
129
|
-
user_app = user_app or clarifai_cfg.clarifai_user_app_id
|
130
|
-
|
131
|
-
if user_app:
|
132
|
-
user_app = user_app.split('/')
|
133
|
-
assert len(
|
134
|
-
user_app
|
135
|
-
) == 2, f"id must be combination of user_id and app_id separated by `/`, e.g. <user_id>/<app_id>. Got {args.id}"
|
136
|
-
self.user_id, self.app_id = user_app
|
137
|
-
|
138
|
-
login()
|
139
|
-
|
140
|
-
def run(self):
|
141
|
-
from clarifai.client import App, Model
|
142
|
-
|
143
|
-
# Run test before uploading
|
144
|
-
if not self.no_test:
|
145
|
-
assert os.path.exists(self.test_path), FileNotFoundError(f"Not found {self.test_path}")
|
146
|
-
result = subprocess.run(f"pytest -s --log-level=INFO {self.test_path}", shell=True)
|
147
|
-
assert result.returncode == 0, "Test has failed. Please make sure no error exists in your code."
|
148
|
-
|
149
|
-
clarifai_key_map = get_model_config(model_type=self.type).clarifai_model.field_maps
|
150
|
-
# inference parameters
|
151
|
-
inference_parameters = None
|
152
|
-
if isinstance(self.infer_param, str) and os.path.isfile(self.infer_param):
|
153
|
-
inference_parameters = InferParamManager(json_path=self.infer_param).get_list_params()
|
154
|
-
inputs = clarifai_key_map.input_fields_map
|
155
|
-
outputs = clarifai_key_map.output_fields_map
|
156
|
-
|
157
|
-
# if updating new version of existing model
|
158
|
-
def update_version():
|
159
|
-
model = Model(model_id=self.id, app_id=self.app_id)
|
160
|
-
if self.url:
|
161
|
-
model.create_version_by_url(
|
162
|
-
url=self.url,
|
163
|
-
input_field_maps=inputs,
|
164
|
-
output_field_maps=outputs,
|
165
|
-
inference_parameter_configs=inference_parameters,
|
166
|
-
description=self.desc)
|
167
|
-
elif self.file:
|
168
|
-
model.create_version_by_file(
|
169
|
-
file_path=self.file,
|
170
|
-
input_field_maps=inputs,
|
171
|
-
output_field_maps=outputs,
|
172
|
-
inference_parameter_configs=inference_parameters,
|
173
|
-
no_resume=self.no_resume,
|
174
|
-
description=self.desc)
|
175
|
-
else:
|
176
|
-
raise ValueError
|
177
|
-
|
178
|
-
if self.update_version:
|
179
|
-
update_version()
|
180
|
-
else:
|
181
|
-
# creating new model
|
182
|
-
_ = App(app_id=self.app_id).create_model(self.id, model_type_id=self.type)
|
183
|
-
update_version()
|
@@ -1,21 +0,0 @@
|
|
1
|
-
import os
|
2
|
-
|
3
|
-
MAX_HW_DIM = 1024
|
4
|
-
IMAGE_TENSOR_NAME = "image"
|
5
|
-
TEXT_TENSOR_NAME = "text"
|
6
|
-
|
7
|
-
BUILT_MODEL_EXT = ".clarifai"
|
8
|
-
|
9
|
-
USER_CACHE_DIR = os.path.join(os.path.expanduser("~"), ".cache")
|
10
|
-
CLARIFAI_HOME = os.path.expanduser(
|
11
|
-
os.getenv(
|
12
|
-
"CLARIFAI_HOME",
|
13
|
-
os.path.join(os.getenv("XDG_CACHE_HOME", USER_CACHE_DIR), "clarifai"),
|
14
|
-
))
|
15
|
-
os.makedirs(CLARIFAI_HOME, exist_ok=True)
|
16
|
-
CLARIFAI_PAT_PATH = os.path.join(CLARIFAI_HOME, "pat")
|
17
|
-
|
18
|
-
CLARIFAI_EXAMPLES_REPO = "https://github.com/Clarifai/examples.git"
|
19
|
-
repo_name = CLARIFAI_EXAMPLES_REPO.split("/")[-1].replace(".git", "")
|
20
|
-
CLARIFAI_EXAMPLES_REPO_PATH = os.path.join(CLARIFAI_HOME, repo_name)
|
21
|
-
MODEL_UPLOAD_EXAMPLE_FOLDER = "model_upload"
|