18 from typing
import Any, Dict, Union, Optional
19 from typing_extensions
import Self, override
20 from datetime
import datetime
21 from zipfile
import ZipFile
22 from pathlib
import Path
27 from ..tag
import Taggable, EntityTagType
28 from ..utils
import isEntityNameValid
29 from ..._folder_manager
import folder_manager
30 from ...networking
import networkManager, NetworkObject, ChunkUploadSession, MAX_CHUNK_SIZE, NetworkRequestError
31 from ...codable
import KeyDescriptor
34 class Model(NetworkObject, Taggable):
37 Represents a machine learning model object on Coretex.ai
38 Contains properties that describe the model
47 date of model creation
49 dataset id that is used for training the model
51 project id that is used for training the model
53 task id that is used for training the model
55 True if model is trained, False otherwise
57 True if model is deleted, False otherwise
61 TaskRun id of trained model
79 def path(self) -> Path:
80 return folder_manager.modelsFolder / str(self.id)
83 def zipPath(self) -> Path:
84 return self.
pathpath.with_suffix(
".zip")
87 def entityTagType(self) -> EntityTagType:
88 return EntityTagType.model
95 str -> name of model descriptor file
98 return "model_descriptor.json"
101 def _keyDescriptors(cls) -> Dict[str, KeyDescriptor]:
102 descriptors = super()._keyDescriptors()
113 meta: Optional[Dict[str, Any]] =
None
117 Creates Model as a result of TaskRun
124 Project to which the Model will be added
127 meta : Optional[Dict[str, Any]]
136 NetworkRequestError -> If model creation failed
140 >>> from coretex import Model, currentTaskRun
141 >>> model = Model.createModel("model-name", currentTaskRun().id, 0.87)
144 if not isEntityNameValid(name):
145 raise ValueError(
">> [Coretex] Model name is invalid. Requirements: alphanumeric characters (\"a-z\", and \"0-9\") and dash (\"-\") with length between 3 to 50")
148 logging.getLogger(
"coretexpylib").warning(f
">> [Coretex] Invalid value for accuracy: ({accuracy} < 0), clipping to 0.")
151 logging.getLogger(
"coretexpylib").warning(f
">> [Coretex] Invalid value for accuracy: ({accuracy} > 1), clipping to 1.")
153 accuracy = max(0, min(accuracy, 1))
160 project_id = projectId,
168 Saves a model descriptor - a JSON file that provides a description of a
169 machine learning model. It includes information such as the model's
170 architecture, input and output shapes, labels, description and etc.
174 path : Union[Path, str]
175 path to where the model descriptor will be saved
176 contents : Dict[str, Any]
177 key-value pairs which will be stored as json
181 >>> from coretex import currentTaskRun, Model
182 >>> model = Model.createModel("model-name", currentTaskRun().id, accuracy)
183 >>> model.saveModelDescriptor(modelPath, {
184 "project_task": currentTaskRun().projectType,
186 "modelName": model.name,
187 "description": currentTaskRun().description,
190 Input shape is [x, y]
192 x is actually number of samples in dataset\n
193 y represents number of unique taxons for selected level in dataset,
195 "input_shape": [x, y],
197 "output_description":
198 Output shape - [x, z]
200 x is actually number of samples in dataset\n
201 z represents that output 2d array (table) is going to have only 1 column (1 prediction for each sample in dataset),
203 "output_shape": [x, z]
207 if isinstance(path, str):
212 with modelDescriptorPath.open(
"w", encoding =
"utf-8")
as file:
213 json.dump(contents, file, ensure_ascii =
False, indent = 4)
216 def entityUrl(self) -> str:
217 return f
'model-item?id={self.id}'
219 def download(self, path: Optional[Path] =
None, ignoreCache: bool =
False) ->
None:
221 Downloads and extracts the model zip file from Coretex.ai
227 if self.isDeleted
or not self.isTrained:
230 if path.exists()
and not ignoreCache:
233 modelZip = path.with_suffix(
".zip")
234 response = networkManager.download(f
"{self._endpoint()}/download", modelZip, {
238 if response.hasFailed():
239 raise NetworkRequestError(response,
"Failed to download Model")
241 with ZipFile(modelZip)
as zipFile:
242 zipFile.extractall(path)
244 def upload(self, path: Union[Path, str]) ->
None:
246 Uploads the provided model folder as zip file to Coretex.ai
250 path : Union[Path, str]
251 Path to the model directory
255 ValueError -> if provided path is not a directory
256 NetworkRequestError -> if Model upload failed
260 >>> from coretex import Model, currentTaskRun
261 >>> model = Model.createModel("model-name", currentTaskRun().id, 0.87)
262 >>> model.upload("path/to/model-dir")
265 if isinstance(path, str):
268 if not path.is_dir():
269 raise ValueError(
"\"path\" must be a directory")
271 zipPath = path.with_suffix(
".zip")
272 with ZipFile(zipPath,
"w")
as zipFile:
273 for value
in path.rglob(
"*"):
274 if not value.is_file():
277 zipFile.write(value, value.relative_to(path))
279 uploadSession = ChunkUploadSession(MAX_CHUNK_SIZE, zipPath)
280 uploadId = uploadSession.run()
287 response = networkManager.formData(
"model/upload", parameters)
288 if response.hasFailed():
289 raise NetworkRequestError(response,
"Failed to upload model")
Self createModel(cls, str name, int projectId, float accuracy, Optional[Dict[str, Any]] meta=None)
str modelDescriptorFileName(cls)
None saveModelDescriptor(cls, Union[Path, str] path, Dict[str, Any] contents)
None download(self, Optional[Path] path=None, bool ignoreCache=False)
None upload(self, Union[Path, str] path)