Coretex
coretex.entities.model.model.Model Class Reference

Inherits NetworkObject, and Taggable.

Public Member Functions

str modelDescriptorFileName (cls)
 
Self createModel (cls, str name, int projectId, float accuracy, Optional[Dict[str, Any]] meta=None)
 
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)
 

Detailed Description

    Represents a machine learning model object on Coretex.ai
    Contains properties that describe the model

    Properties
    ----------
    name : str
        model name
    createdById : str
        id of model
    createdOn : datetime
        date of model creation
    datasetId : int
        dataset id that is used for training the model
    projectId : int
        project id that is used for training the model
    taskId : int
        task id that is used for training the model
    isTrained : bool
        True if model is trained, False otherwise
    isDeleted : bool
        True if model is deleted, False otherwise
    accuracy : float
        model accuracy
    taskRunId : int
        TaskRun id of trained model
    meta : Dict[str, Any]
        model meta data

Definition at line 34 of file model.py.

Member Function Documentation

◆ createModel()

Self coretex.entities.model.model.Model.createModel (   cls,
str  name,
int  projectId,
float  accuracy,
Optional[Dict[str, Any]]   meta = None 
)
    Creates Model as a result of TaskRun

    Parameters
    ----------
    name : str
        model name
    projectId : int
        Project to which the Model will be added
    accuracy : float
        model accuracy
    meta : Optional[Dict[str, Any]]
        model metadata

    Returns
    -------
    Self -> Model object

    Raises
    -------
    NetworkRequestError -> If model creation failed

    Example
    -------
    >>> from coretex import Model, currentTaskRun
    >>> model = Model.createModel("model-name", currentTaskRun().id, 0.87)

Definition at line 108 of file model.py.

114  ) -> Self:
115 
116  """
117  Creates Model as a result of TaskRun
118 
119  Parameters
120  ----------
121  name : str
122  model name
123  projectId : int
124  Project to which the Model will be added
125  accuracy : float
126  model accuracy
127  meta : Optional[Dict[str, Any]]
128  model metadata
129 
130  Returns
131  -------
132  Self -> Model object
133 
134  Raises
135  -------
136  NetworkRequestError -> If model creation failed
137 
138  Example
139  -------
140  >>> from coretex import Model, currentTaskRun
141  >>> model = Model.createModel("model-name", currentTaskRun().id, 0.87)
142  """
143 
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")
146 
147  if accuracy < 0:
148  logging.getLogger("coretexpylib").warning(f">> [Coretex] Invalid value for accuracy: ({accuracy} < 0), clipping to 0.")
149 
150  if accuracy > 1:
151  logging.getLogger("coretexpylib").warning(f">> [Coretex] Invalid value for accuracy: ({accuracy} > 1), clipping to 1.")
152 
153  accuracy = max(0, min(accuracy, 1))
154 
155  if meta is None:
156  meta = {}
157 
158  return cls.create(
159  name = name,
160  project_id = projectId,
161  accuracy = accuracy,
162  meta = meta
163  )
164 

◆ download()

None coretex.entities.model.model.Model.download (   self,
Optional[Path]   path = None,
bool   ignoreCache = False 
)
    Downloads and extracts the model zip file from Coretex.ai

Definition at line 219 of file model.py.

219  def download(self, path: Optional[Path] = None, ignoreCache: bool = False) -> None:
220  """
221  Downloads and extracts the model zip file from Coretex.ai
222  """
223 
224  if path is None:
225  path = self.path
226 
227  if self.isDeleted or not self.isTrained:
228  return
229 
230  if path.exists() and not ignoreCache:
231  return
232 
233  modelZip = path.with_suffix(".zip")
234  response = networkManager.download(f"{self._endpoint()}/download", modelZip, {
235  "id": self.id
236  })
237 
238  if response.hasFailed():
239  raise NetworkRequestError(response, "Failed to download Model")
240 
241  with ZipFile(modelZip) as zipFile:
242  zipFile.extractall(path)
243 

◆ modelDescriptorFileName()

str coretex.entities.model.model.Model.modelDescriptorFileName (   cls)
    Returns
    -------
    str -> name of model descriptor file

Definition at line 91 of file model.py.

91  def modelDescriptorFileName(cls) -> str:
92  """
93  Returns
94  -------
95  str -> name of model descriptor file
96  """
97 
98  return "model_descriptor.json"
99 

◆ saveModelDescriptor()

None coretex.entities.model.model.Model.saveModelDescriptor (   cls,
Union[Path, str]  path,
Dict[str, Any]  contents 
)
    Saves a model descriptor - a JSON file that provides a description of a
    machine learning model. It includes information such as the model's
    architecture, input and output shapes, labels, description and etc.

    Parameters
    ----------
    path : Union[Path, str]
        path to where the model descriptor will be saved
    contents : Dict[str, Any]
        key-value pairs which will be stored as json

    Example
    -------
    >>> from coretex import currentTaskRun, Model
    >>> model = Model.createModel("model-name", currentTaskRun().id, accuracy)
    >>> model.saveModelDescriptor(modelPath, {
            "project_task": currentTaskRun().projectType,
            "labels": labels,
            "modelName": model.name,
            "description": currentTaskRun().description,

            "input_description":
                Input shape is [x, y]

                x is actually number of samples in dataset\n
                y represents number of unique taxons for selected level in dataset,

            "input_shape": [x, y],

            "output_description":
                Output shape - [x, z]

                x is actually number of samples in dataset\n
                z represents that output 2d array (table) is going to have only 1 column (1 prediction for each sample in dataset),

            "output_shape": [x, z]
        })

Definition at line 166 of file model.py.

166  def saveModelDescriptor(cls, path: Union[Path, str], contents: Dict[str, Any]) -> None:
167  """
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.
171 
172  Parameters
173  ----------
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
178 
179  Example
180  -------
181  >>> from coretex import currentTaskRun, Model
182  >>> model = Model.createModel("model-name", currentTaskRun().id, accuracy)
183  >>> model.saveModelDescriptor(modelPath, {
184  "project_task": currentTaskRun().projectType,
185  "labels": labels,
186  "modelName": model.name,
187  "description": currentTaskRun().description,
188 
189  "input_description":
190  Input shape is [x, y]
191 
192  x is actually number of samples in dataset\n
193  y represents number of unique taxons for selected level in dataset,
194 
195  "input_shape": [x, y],
196 
197  "output_description":
198  Output shape - [x, z]
199 
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),
202 
203  "output_shape": [x, z]
204  })
205  """
206 
207  if isinstance(path, str):
208  path = Path(path)
209 
210  modelDescriptorPath = path / cls.modelDescriptorFileName()
211 
212  with modelDescriptorPath.open("w", encoding = "utf-8") as file:
213  json.dump(contents, file, ensure_ascii = False, indent = 4)
214 

◆ upload()

None coretex.entities.model.model.Model.upload (   self,
Union[Path, str]  path 
)
    Uploads the provided model folder as zip file to Coretex.ai

    Parameters
    ----------
    path : Union[Path, str]
        Path to the model directory

    Raises
    -------
    ValueError -> if provided path is not a directory
    NetworkRequestError -> if Model upload failed

    Example
    -------
    >>> from coretex import Model, currentTaskRun
    >>> model = Model.createModel("model-name", currentTaskRun().id, 0.87)
    >>> model.upload("path/to/model-dir")

Definition at line 244 of file model.py.

244  def upload(self, path: Union[Path, str]) -> None:
245  """
246  Uploads the provided model folder as zip file to Coretex.ai
247 
248  Parameters
249  ----------
250  path : Union[Path, str]
251  Path to the model directory
252 
253  Raises
254  -------
255  ValueError -> if provided path is not a directory
256  NetworkRequestError -> if Model upload failed
257 
258  Example
259  -------
260  >>> from coretex import Model, currentTaskRun
261  >>> model = Model.createModel("model-name", currentTaskRun().id, 0.87)
262  >>> model.upload("path/to/model-dir")
263  """
264 
265  if isinstance(path, str):
266  path = Path(path)
267 
268  if not path.is_dir():
269  raise ValueError("\"path\" must be a directory")
270 
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():
275  continue
276 
277  zipFile.write(value, value.relative_to(path))
278 
279  uploadSession = ChunkUploadSession(MAX_CHUNK_SIZE, zipPath)
280  uploadId = uploadSession.run()
281 
282  parameters = {
283  "id": self.id,
284  "file_id": uploadId
285  }
286 
287  response = networkManager.formData("model/upload", parameters)
288  if response.hasFailed():
289  raise NetworkRequestError(response, "Failed to upload model")

The documentation for this class was generated from the following file: